【问题标题】:How to bind a Dictionary to DataSource of DataGridView如何将字典绑定到 DataGridView 的数据源
【发布时间】:2013-12-05 22:49:51
【问题描述】:

我认为这个问题很明确。我有一个 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;

但没有任何结果。

【问题讨论】:

  • 首先是填充您的Dictionary
  • 你的字典是空的!
  • 对不起,我已经修好了。
  • 这个问题有什么问题,它有负利率?我很困惑。

标签: c# dictionary datagridview


【解决方案1】:

查看 docs 的 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;

【讨论】:

    【解决方案2】:

    如果你真的想绑定到字典,你可以尝试使用 linq where 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();
    

    【讨论】:

    • 非常感谢。这是完美的答案。
    【解决方案3】:

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

    myDataGrid.DataSource = myDictionary.ToList();
    

    【讨论】:

    • 值得一提的是,您应该在页面顶部添加using System.Linq
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-03-12
    • 2010-10-25
    • 2012-02-09
    • 2015-12-02
    相关资源
    最近更新 更多