Asp.net 为列表创建自定义gridview模板字段<&燃气轮机;
我有一个字符串列表。我想使用gridview向用户显示它。由于列数未知,我决定动态创建gridview字段。我发现一些,但它们都使用DataTable。我尝试使用相同的方法,但在数据绑定事件的“\u columnName”时遇到问题:Asp.net 为列表创建自定义gridview模板字段<&燃气轮机;,asp.net,list,gridview,Asp.net,List,Gridview,我有一个字符串列表。我想使用gridview向用户显示它。由于列数未知,我决定动态创建gridview字段。我发现一些,但它们都使用DataTable。我尝试使用相同的方法,但在数据绑定事件的“\u columnName”时遇到问题: 因为列表中没有列。非常感谢您的建议。一个更简单的方法是将AutoGenerateColumns设置为true,并使用DataTable作为数据源 例如(aspx可以是空的GridView): void field_DataBinding(object se
因为列表中没有列。非常感谢您的建议。一个更简单的方法是将
AutoGenerateColumns
设置为true,并使用DataTable
作为数据源
例如(aspx可以是空的GridView):
void field_DataBinding(object sender, EventArgs e)
{
TextBox txtdata = (TextBox)sender;
GridViewRow container = (GridViewRow)txtdata.NamingContainer;
object dataValue = DataBinder.Eval(container.DataItem, _columnName);
if (dataValue != DBNull.Value)
{
txtdata.Text = dataValue.ToString();
}
}
List<List<String>> data = new List<List<String>>() {
new List<String>(){"Row1_Col1", "Row1_Col2", "Row1_Col3"},
new List<String>(){"Row2_Col1", "Row2_Col2", "Row2_Col3"},
new List<String>(){"Row3_Col1", "Row3_Col2", "Row3_Col3"},
new List<String>(){"Row4_Col1", "Row4_Col2", "Row4_Col3"},
new List<String>(){"Row5_Col1", "Row5_Col2", "Row5_Col3"},
};
var tbl = new DataTable();
int maxFieldCount = data.Max(l => l.Count);
for (int i = 1; i <= maxFieldCount; i++)
tbl.Columns.Add("Column" + i);
foreach (var list in data)
{
DataRow newRow = tbl.Rows.Add();
newRow.ItemArray = list.ToArray();
}
GridView1.DataSource = tbl;
GridView1.DataBind();