开发者

.NET Dictionary Keys as ListBox DataSource

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!


  myListBox.DataSource = (from keys in myEntities.Keys
                         select keys)
                         .ToList();

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.


The main problem is that you can eventually use the dictionary Keys as a DataSource, but you don't have a way to notify the DataSource that you added or removed elements from the dictionary.

This is because the Dictionary doesn't have any notification event for that, hence the DataSource doesn't know how and when your dictionary has changed. The items that are already present in your list got their changes reflected simply because the DataSource holds a reference to them, and so when they change the changes are visible wherever there is a reference held.

For triggering a change in your Dictionary, as far as I know, you don't have many choices:

  • Write some code for reattaching the list to your DataSource every time you add or remove something from the Dictionary (with all the problems of keeping the selected items etc.)

  • Create your own data structure either by implementing IBindingList or by deriving from BindingList directly.

both of them are not easy solutions, so if your entities are relatively simple you might want to consider some alternatives such as DataTables, which could hold a complex key and other structured data.


Try using

myListBox.DataSource = myEntities
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜