Binding Combobox Using Dictionary as the Datasource
userListComboBox.DataSource = userCache.ToList();
userListComboBox.DisplayMember = "Key";
var colors = new Dictionary < string, string > ();
colors["10"] = "Red";
Binding to Combobox
comboBox1.DataSource = new BindingSource(colors, null);
comboBox1.DisplayMember = "Value";
comboBox1.ValueMember = "Key";
Full Source...Dictionary as a Combobox Datasource
Jeryy
SortedDictionary<string, int> userCache = new SortedDictionary<string, int>
{
{"a", 1},
{"b", 2},
{"c", 3}
};
comboBox1.DataSource = new BindingSource(userCache, null);
comboBox1.DisplayMember = "Key";
comboBox1.ValueMember = "Value";
But why are you setting the ValueMember
to "Value", shouldn't it be bound to "Key" (and DisplayMember
to "Value" as well)?
I used Sorin Comanescu's solution, but hit a problem when trying to get the selected value. My combobox was a toolstrip combobox. I used the "combobox" property, which exposes a normal combobox.
I had a
Dictionary<Control, string> controls = new Dictionary<Control, string>();
Binding code (Sorin Comanescu's solution - worked like a charm):
controls.Add(pictureBox1, "Image");
controls.Add(dgvText, "Text");
cbFocusedControl.ComboBox.DataSource = new BindingSource(controls, null);
cbFocusedControl.ComboBox.ValueMember = "Key";
cbFocusedControl.ComboBox.DisplayMember = "Value";
The problem was that when I tried to get the selected value, I didn't realize how to retrieve it. After several attempts I got this:
var control = ((KeyValuePair<Control, string>) cbFocusedControl.ComboBox.SelectedItem).Key
Hope it helps someone else!