【问题标题】:Is there way to bind DataGridView to Dictionary and use Keys as Columns?有没有办法将 DataGridView 绑定到字典并将键用作列?
【发布时间】:2017-07-01 15:24:13
【问题描述】:

有没有办法将 DataGridView 绑定到 Dictionary 并使用 Keys 作为列?

例如我有类似的东西:

var items = new Dictionary<string, List<int>>();
items.Add("Column 1", new List<int>{ 1, 2, 3 });
items.Add("Column 2", new List<int>{ 1, 2, 3 });
items.Add("Column 3", new List<int>{ 1, 2, 3 });

我想看到类似的东西:

[ Column 1] [ Column 2] [ Column 3]
1           1           1
2           2           2
3           3           3

我尝试将简单字典转换为动态对象:

dynamic itemsData = new ExpandoObject();

IDictionary<string, object> items = (IDictionary<string, object>)itemsData;
items.Add("Column 1", new List<int>{ 1, 2, 3, 4, 5 });
items.Add("Column 2", new List<int>{ 1, 2, 3, 4, 5 });
items.Add("Column 3", new List<int>{ 1, 2, 3, 4, 5 });

bindingSource1.DataSource = itemsData;
dataGridView1.DataSource = bindingSource1;

但是没有任何效果,我得到了结果:

[ Key]    [ Value ]
Column 1  System.Collect...
Column 2  System.Collect...
Column 3  System.Collect...

谢谢。

【问题讨论】:

  • 您正在尝试将垂直数据添加到水平思考的对象。一般模式是将数据按行而不是列添加到数据网格中。

标签: c# dictionary data-binding datagridview bindingsource


【解决方案1】:

我不认为,您可以将字典绑定到 DataGridView。为了将对象绑定到 DataGridView 的 DataSource,该对象应该实现 IList、ListSource 但 Dictionary 没有。

一种解决方法是将您的字典转换为数据表并将其绑定到 DataGridView。

表列名称为 Column1, Column2 -----ColumnN 并创建对应的行数。

注意:转换开销可能会影响性能。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-12-25
    • 1970-01-01
    • 1970-01-01
    • 2019-07-12
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多