如何将字典绑定到DataGridView的数据源

Eme*_*rop 2 c# dictionary datagridview

我认为这个问题很清楚。我有一个 Dictionary 实例,我想像 DataGridView 实例的 DataSource 一样绑定它。其实我可以这样直接绑定:

Dictionary<string,string> d = new Dictionary<string,string>();
d.Add("1","test1");
d.Add("2","test2");
DataGridView v = new DataGridView();

v.DataSource = d;
Run Code Online (Sandbox Code Playgroud)

但没有任何结果。

ter*_*zio 7

如果您确实想绑定到字典,可以使用 linq 尝试此操作,其中 foreach KeyValuePair 您将创建一个匿名类型并转换为列表,如下所示:

假设您的 datagridview 名为 dataGridView1:

Dictionary<string, string> d = new Dictionary<string, string>();
d.Add("1", "test1");
d.Add("2", "test2");
dataGridView1.DataSource = (from entry in d
                            orderby entry.Key
                            select new{entry.Key,entry.Value}).ToList();
Run Code Online (Sandbox Code Playgroud)


m1k*_*ael 5

查看DataSource 属性的文档。它仅处理特定类型(IList、IListSource 等)。所以你不能将它绑定到 IDictionary。所以,这会起作用:

List<KeyValuePair<string, string>> d = new List<KeyValuePair<string, string>>();
d.Add(new KeyValuePair<string, string>("1", "2323"));
d.Add(new KeyValuePair<string, string>("2", "1112323"));

DataGridView v = new DataGridView();
v.DataSource = d;
Run Code Online (Sandbox Code Playgroud)


小智 5

老问题,但由于我刚刚偶然发现它,也许其他人也会。字典知道如何将自己放入列表中,因此可以这样做:

myDataGrid.DataSource = myDictionary.ToList();
Run Code Online (Sandbox Code Playgroud)

  • 值得一提的是,您应该在页面顶部添加“using System.Linq” (3认同)