views:

1252

answers:

2

It is possible to bind a dictionary to a listbox, keeping in sync between the listbox and the member property?

A: 

I think you can use events for that. Whenever something changes in ListBox, an eventHandler method will add/remove same thing from Dictionary.

Braveyard
+4  A: 
var choices = new Dictionary<string, string>(); 
choices["A"] = "Arthur"; 
choices["F"] = "Ford"; 
choices["T"] = "Trillian"; 
choices["Z"] = "Zaphod"; 
listBox1.DataSource = new BindingSource(choices, null); 
listBox1.DisplayMember = "Value"; 
listBox1.ValueMember = "Key";

(Shamelessly lifted from my own blog: Bind a ComboBox to a generic Dictionary.)

This means you can use SelectedValue to get hold of the corresponding dictionary key for the selected item in the ListBox.

Matt Hamilton
Does it actually require a `BindingSource` there?
Pavel Minaev
Yeah in my experience it needs the BindingSource.
Matt Hamilton
I've tried this, and it works partially, ie if i do this, after setting datasource for listbox: choices["M"] = "abc";choices.Remove("T");the listbox does not reflect the changes in the choices dictionary...
Valerio Manfredi
Yeah, I'm not sure you'll get it to work if you're modifying the underlying dictionary after the fact. Dictionaries don't notify when they're changed like BindingList<T> or ObservableCollection<T> does.
Matt Hamilton
Ok, the BindingList<T> seems to be working. Thank you!
Valerio Manfredi
Anyone else getting an ArgumentNull exception when creating the new BindingSource(...)??
Steve H.