I’ve a ListBox in my winforms app. I want it to have as DataSource the keys of a dictionary so I do as follows:
IDictionary<Entity1, Entity2> myEntities = new Dictionary<Entity1, Entity2>();
myListBox.DataSource = myEntities.Keys;
So I’m getting at the second line the following error:
Complex databinding accepts as a datasource either in Ilist or IListSource
-
I’ve tried two things that wont do:
myListBox.DataSource = (IList<Entity1>)myEntities.Keys;
throws InvalidCastException exception:
Can’t convert an object of type ‘KeyCollection[Entity1,Entity2]’ to type ‘System.Collections.Generic.IList`1[Entity1]’.
-
And And I’ve also tried:
myListBox.DataSource = myEntities.Keys.ToList<Entity1>();
but with that way I lose the binding, when I modify myEntities, myListBox.DataSource does not change.
Note: The excepton messages are translated by me so they may not be exactly as I wrote.
Any way to do do this?
Thanks!
Third time a charm…
Okay,
I believe you will have to inherit the Dictionary and override the .Add method to trigger an event. On the event, you will need to re-query the Dictionary keys. According to resources I’ve found (including: How to Bind…) the Dictionary does not throw events when it’s contents change.