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
2009-10-01 23:24:15
+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
2009-10-01 23:25:03
Does it actually require a `BindingSource` there?
Pavel Minaev
2009-10-01 23:29:41
Yeah in my experience it needs the BindingSource.
Matt Hamilton
2009-10-01 23:34:31
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
2009-10-02 07:34:11
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
2009-10-02 08:57:30
Ok, the BindingList<T> seems to be working. Thank you!
Valerio Manfredi
2009-10-03 07:58:25
Anyone else getting an ArgumentNull exception when creating the new BindingSource(...)??
Steve H.
2010-03-30 15:44:38