2012-02-23 3 views
0

Я новичок в ASP.NET. Я хочу добавить столбец GridView динамически на основе отклике APIЗаполните данные столбца GridView на основе ответа API

id  User  secretcode 
1  u1  {response from the API based on the Id value} 
2  u1  {response from the API based on the Id value} 
3  u1  {response from the API based on the Id value} 
4  u1  {response from the API based on the Id value} 
5  u1  {response from the API based on the Id value} 

id и User уже находятся в моей таблице базы данных (пользователей), так что для каждой возвращенной строки, я хочу, чтобы позвонить API, чтобы заполнить мой 3-й столбец, т.е. secretcode. В принципе, я смущен тем, где использовать цикл ForEach.

Это грубый код, на котором я работаю:

DataTable table = new DataTable(); 
DataColumn col3 = new DataColumn("Secretcode"); 
col3.DataType = System.Type.GetType("System.Int"); 
table.Columns.Add(col3); 
row[col3] = {response data from API} 
gvTest.DataSource = table; 
gvTest.DataBind(); 

ответ

1

Возможно, что-то вроде этого

DataTable table = new DataTable(); 
DataColumn col = new DataColumn("Secretcode"); 
table.Columns.Add(col); 
for(int i = 0; i < table.Rows.Count; i++) 
{ 
    // Where 'SomeAPICall()' is calling the API and returning the 
    // correct data type. If it is returning an object you may want 
    // to convert it before you attach it to the table 

    table.Rows[i]["Secretcode"] = SomeAPICall(table.Rows[i]["id"]); 
} 
gvTest.DataSource = table; 
gvTest.DataBind(); 

Или, если вы продали на идее цикла Еогеасп:

DataTable table = new DataTable(); 
DataColumn col = new DataColumn("Secretcode"); 
table.Columns.Add(col); 
foreach(DataRow row in table.Rows) 
{ 
    // Where 'SomeAPICall()' is calling the API and returning the 
    // correct data type. If it is returning an object you may want 
    // to convert it before you attach it to the table 

    row["Secretcode"] = SomeAPICall(row["id"]); 
} 
gvTest.DataSource = table; 
gvTest.DataBind(); 

Я предпочитаю использовать для циклов вообще, потому что часто вы хотите использовать один и тот же индексный номер на 2 разных коллекциях wh что вы действительно не можете сделать с циклом foreach. В этом случае, хотя это не имеет значения.

+0

thnx, который помог –

Смежные вопросы