【问题标题】:How to bind a dictionary object to a Windows Forms gridview如何将字典对象绑定到 Windows 窗体 gridview
【发布时间】:2011-09-09 22:12:41
【问题描述】:

如何将字典对象绑定到 Windows 窗体中的 datagridview?

 Dictionary<string, string> result = new Dictionary<string, string>();
 result.Add(arrFilename[i].fileName,"Found");
 dataGridView1.DataSource = result;

数据视图网格未绑定。解决办法是什么?

【问题讨论】:

    标签: c# winforms visual-studio-2005


    【解决方案1】:

    这并不简单,因为字典对象没有实现 datagridview 期望源遵守的 IList 接口。

    这可能会有所帮助:

    DataGridView bound to a Dictionary

    【讨论】:

      【解决方案2】:

      您不能使用字典。而是使用 DictionaryEntry 数组。 我认为是因为字典 List 中的每个项目都没有已知类型。

      它没有显示错误,但是如果您将组合框数据源设置为字典,它会显示 它没有实现IList

      【讨论】:

        【解决方案3】:

        DataGridView.DataSource 需要一个实现 IListIListSourceIBindingListIBindingListView 的对象。

        由于DictionaryDictionary.ValueCollectionDictionary.KeyCollection 都没有实现它,所以不能直接绑定到它。

        如果您只想要一个只读的值列表,您可以将它们添加到 List 并绑定到它,例如(假设您的字典使用 int 和 string 作为键和值类型):

        List<KeyValuePair<int,string>> list = new List<KeyValuePair<int,string>>();
        list.AddRange( myDict.Values);
        
        DataGridView1.DataSource = list;
        

        如果您想做更聪明的事情,那么最简单的解决方案是不使用Dictionary 作为您的数据结构。您可能会继承您的 Dictionary 并实现其中一个可绑定接口,但这可能比必要的工作量更大且更复杂。

        请参阅 Rory(MSDN 论坛)的 DataGridView bound to a generic dictionary

        【讨论】:

          猜你喜欢
          • 2011-06-05
          • 1970-01-01
          • 2012-05-09
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2011-04-05
          • 1970-01-01
          相关资源
          最近更新 更多