I have been looking into this for a while and there are lots of questions on this topic but I have not been able to find a clear answer.
I have a Listbox
(listBox1) and IDictionary
(clients) object in Windows Forms application.
public static IDictionary<string, Object> clients = new Dictionary<string, Object>();
I can use the following to populate the ListBox
from the IDictionary
:
listBox1.DataSource=clients.ToList();
form_m.listBox1.DisplayMember = "key";
Question #1:
What is the correct way to use DataBinding
with a ListBox
?
I have tried the following:
listBox1.DataBindings.Add("DataSource", clients, "Key");
Getting this exception:
System.Reflection.TargetInvocationException:
Property accessor 'Key' on object 'System.Collections.Generic.Dictionary`2[[System.String, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089],[System.Net.Sockets.Socket, System, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]]' threw the following exception:'Object does not match target type.'System.Reflection.TargetException:
Object does not match target type.
And when trying:
listBox1.DataBindings.Add("DataSource", clients.ToList(), "Key");
I get this exception:
System.ArgumentException:
Complex DataBinding accepts as a data source either an IList or an IListSource.
Question #2:
This works fine but I want the ListBox to update when there is a new key/value added or removed from IDictionary
. As I understand, I need to make and use extended Observable
class of IDictionary
. Or, is there another simpler solution for this?
PS: It does not necessarily have to be the IDictionary
, any data structure would do. But, I need the ListBox to update, as changes are made in Data structure.
One such example I found was can-i-bind-my-itemscontrol-to-a-dictionary