C# Bound DataGridView to Hashtable
I want to make a C# DataGridView's DataSource
be a HashTable
where there are two columns:
- The first one would be the key;
- The second the val开发者_Python百科ue.
Is this possible?
EDIT: Please see my comment about setting/getting the value from/to a hashtable. Thanks!
The problem here is that you cannot bind directly to a HashTable
. You'll need something that implements: IList
, IListSource
, IBindingList
, IBindingListView
. HashTable does not implement any of those interfaces.
Try using LINQ to get your HashTable
into a 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();
Note that the anonymous class has 2 named properties (I used Col1
and Col2
for brevity. Your grid must know about them exactly:
Short answer: NO. DataGridView supports IList, so you could try using a List instead of a Hashtable.
http://social.msdn.microsoft.com/forums/en-US/csharpgeneral/thread/d4745e6e-fcb1-4083-8d4a-e654b5afa75a/
精彩评论