根据API响应填充GridView列数据

时间:2012-02-23 19:32:26

标签: asp.net gridview

我是ASP.NET新手。我想根据API的响应动态地向GridView添加一列

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}

idUser已经在我的数据库表(用户)中,因此对于每个返回的行,我想调用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 个答案:

答案 0 :(得分: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();

或者如果您按照foreach循环的想法出售:

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();

我更喜欢使用for循环,因为通常你想在2个不同的集合上使用相同的索引号,这对于foreach循环你真的可以做到。在这种情况下,虽然它不重要。