[英]C# populate DataGrid with List<List<string>>?
Let's say I have a DataGrid in WinForms (C#).假设我在 WinForms (C#) 中有一个 DataGrid。
I want to populate it but my data is in this format:我想填充它,但我的数据是这种格式:
List<List<string>> datas;
For simple test I add values:对于简单的测试,我添加了值:
List<List<string>> ds = new List<List<string>>();
List<string> row1 = new List<string>();
row1.Add("col1");
row1.Add("col2");
row1.Add("col3");
ds.Add(row1);
When I add ds
as datasouce for the grid it displays something I don't understand:当我将
ds
添加为网格的数据源时,它会显示我不理解的内容:
grid.DataSource = ds;
I tried also with LINQ, but did not succeed, datagrid is empty.我也试过 LINQ,但没有成功,datagrid 是空的。 How can I solve this?
我该如何解决这个问题?
I'd do it with or without LINQ if that is faster than manually iterating and populating with for loops.如果这比手动迭代和填充 for 循环更快,我会在有或没有 LINQ 的情况下这样做。
I modified the code found here to suit your needs;我修改了此处找到的代码以满足您的需求;
private void Form1_Load(object sender, EventArgs e)
{
List<List<string>> list = new List<List<string>>();
list.Add(new List<string>()
{
"Row 1, Col 1",
"Row 1, Col 2",
"Row 1, Col 3",
});
list.Add(new List<string>()
{
"Row 2, Col 1",
"Row 2, Col 2",
"Row 2, Col 3",
});
list.Add(new List<string>()
{
"Row 3, Col 1",
"Row 3, Col 2",
"Row 3, Col 3",
});
DataTable table = ConvertListToDataTable(list);
dataGridView1.DataSource = table;
}
static DataTable ConvertListToDataTable(List<List<string>> list)
{
DataTable table = new DataTable();
int columns = 0;
foreach (var item in list)
{
if (item.Count > columns)
{
columns = item.Count;
}
}
for (int i = 0; i < columns; i++)
{
table.Columns.Add();
}
foreach (var item in list)
{
DataRow new_row = table.NewRow();
foreach(var col in item)
{
new_row[item.IndexOf(col)] = col;
}
table.Rows.Add(new_row);
}
return table;
}
Which returns the datagrid as per below它按以下方式返回数据网格
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.