我想让 C# DataGridView 的 DataSource
成为一个 HashTable
,其中有两列:
- 第一个是关键;
- 第二个值。
这可能吗?
编辑:请参阅我关于从哈希表设置值/从哈希表获取值的评论。 谢谢!
最佳答案
这里的问题是您无法直接绑定(bind)到HashTable
。您需要实现以下功能:IList
、IListSource
、IBindingList
、IBindingListView
。 HashTable 没有实现任何这些接口(interface)。
尝试使用 LINQ 将 HashTable
放入 List
中:
Hashtable ht = new Hashtable();
ht.Add(1,"foo");
ht.Add(2,"bar");
dataGridView1.DataSource = ht.Cast<DictionaryEntry>()
.Select(x => new { Col1 = x.Key.ToString(),
Col2 = x.Value.ToString() })
.ToList();
请注意,匿名类有 2 个命名属性(为了简洁起见,我使用了 Col1
和 Col2
。您的网格必须准确地了解它们:
关于C# 将 DataGridView 绑定(bind)到 Hashtable,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6269361/