2012-04-11 34 views

回答

1

这里的问题是,(显然)DataGridView的DataSource属性没有按”不知道如何显示List<List<string>>。一种方法是将您的列表组合到一个DataGridView可以绑定的对象中。这里有几个方法可以做到这一点:

到DataTable:

要转换List<List<string>>到DataTable,我借来的代码中发现here并创造了这个扩展方法:

static class ListExtensions { 
    public static DataTable ToDataTable(this List<List<string>> list) { 
     DataTable tmp = new DataTable(); 
     tmp.Columns.Add("MyData"); 
     // Iterate through all List<string> elements and add each string value to a new DataTable Row.   
     list.ForEach(lst => lst.ForEach(s => tmp.Rows.Add(new object[] {s}))); 

     return tmp; 
    } 
} 

现在,您可以使用此扩展方法从您的List<List<string>>中获取可绑定到DataGridView的DataTable:

dataGridView.DataSource = data.ToDataTable(); 

一个匿名类型列表:

这里是这样的代码:

dataGridView.DataSource = data.SelectMany(lst => lst) 
           .Select(s => new { Value = s }).ToList(); 

我们需要匿名类型,因为一个DataGridView将无法显示在列表中的字符串值财产没有一点帮助,如描述here


这些方法当然都有缺点,但我相信沿这些方向的东西是最好的选择。

1
List<List<string>> data = new List<List<string>>(); 
dataGridView.DataSource = data; 
dataGridView.Databind(); 

一些海报说,这是在这种情况下,您可以(根据MSDN)JST设置datasurce和Windows Forms没有数据绑定

+1

Databind适用于ASP.NET; DataGridView是一个Windows窗体控件... – 2012-04-11 23:14:08

+0

Windows窗体中的DataGridView。 – BILL 2012-04-11 23:16:44

相关问题