从数据库中检索数据并以字符串形式存储,并将所有字符串绑定到gridview

时间:2013-08-21 03:57:21

标签: asp.net sql-server-2008 c#-4.0

我正在使用存储过程将数据从数据库提取到gridview中。我不想在gridview中将列名指定为boundfield的datafeild属性。我想在后面的代码中将所有列提取为单独的字符串,并在datafield中指定字符串名称。

提前致谢

1 个答案:

答案 0 :(得分:0)

您可以遍历从数据库中的存储过程返回的DataTable,如下所示:

// Iterate through the columns of the DataTable to set the BoundFields dynamically
foreach (DataColumn theDataColumn in theDataTable.Columns)
{
    // Instantiate new BoundField
    BoundField theBoundField = new BoundField();

    // Set the DataField value
    theBoundField.DataField = theDataColumn.ColumnName;

    // Set the HeaderText value
    theBoundField.HeaderText = theDataColumn.ColumnName;

    // Add BoundField to the GridView
    GridView1.Columns.Add(theBoundField);
}