1

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

Ola Ström
  • 4,136
  • 5
  • 22
  • 41
user2288650
  • 412
  • 1
  • 6
  • 23

1 Answers1

0

For question #1, you can bind a Dictionary to a ListBox by creating a BindingSource from it:

listBox1.DataSource = new BindingSource(clients, null); 
listBox1.DisplayMember = "Key"; 
listBox1.ValueMember = "Key"; 

For question #2, you can use a BindingList as a DataSource, and the ListBox will update automatically as the BindingList changes.

For example, if you drop a ListBox and a Button on a form, this code will add 5 items to the BindingList and bind the ListBox to it in the Load event. Then in the Button_Click event, another item is added to our BindingList and the ListBox reflects the change immediately:

BindingList<int> items = new BindingList<int>();

private void Form1_Load(object sender, EventArgs e)
{
    // Add some items to our binding list
    for (int i = 0; i < 5; i++)
    {
        items.Add(i);
    }

    // Bind our listbox
    listBox1.DataSource = items;
}

private void button1_Click(object sender, EventArgs e)
{
    // Add an item to our binding list on each click
    items.Add(items.Count + 1);
}
Rufus L
  • 36,127
  • 5
  • 30
  • 43