1

I have a combobox that has a dictionary as a datasource. I am trying to lookup a key in the combobox and get the display value for it. FindString looks up the display value.

var dictionary = new Dictionary<string, string>();
dictionary.Add("key1", "value1");
dictionary.Add("key2", "value2");
dictionary.Add("key3", "value3");
comboBox1.DataSource = new BindingSource(dictionary, null);
comboBox1.ValueMember = "Key";
comboBox1.DisplayMember = "Value";
comboBox1.FindString("key3") //returns -1
comboBox1.FindString("value3") //returns 2

But I want to lookup key3's display value. How can I do that?

blue
  • 373
  • 2
  • 4
  • 12

1 Answers1

0

If you want to find the currently selected item and value:
comboBox1.SelectedValue and Text

If you want to enumerate through the original source, typically you would just enumerate the original source:

dictionary["key3"];

If you don't have access to it for some reason, just get it back from the comboBox:

var originalDictionary = ((Dictionary<string,string>)((BindingSource)comboBox1.DataSource).DataSource);
var randomValue = originalDictionary["key3"];
John Arlen
  • 6,539
  • 2
  • 33
  • 42
  • Thank you. I guess that could work but I find it odd to find a display value but not the key. – blue Mar 04 '12 at 06:05
  • comboBox1.SelectedValue gets you the 'key', if you are looking for the one item selected by the user. – John Arlen Mar 04 '12 at 06:54