8

We have dictionary like this:

var dictionary = new Dictionary<int, int> { { 0, 100 }, { 1, 202 }, { 2, 309 }, };

and so on a lot of values. dictionary binded to comboBox like this:

comboBox1.ItemsSource = dictionary;
comboBox1.DisplayMemberPath = "Value";

I'm wonder how can I get selectedvalue of this comboBox, if comboBox.Text works only for manually inputted values and this code:

string value = comboBox1.SelectedValue.ToString();

return value like [1, 202], while I need clear int TValue "202". I'm unable to find similar question so I ask it there and hope that the answer may be useful for someone else.

Mike
  • 1,714
  • 2
  • 13
  • 27
  • Use this as an alternative to learning how to Create a `BindingSource` using a `Dictionary or Dictionaryt` http://stackoverflow.com/questions/6412739/binding-combobox-using-dictionary-as-the-datasource – MethodMan Mar 22 '13 at 21:16

2 Answers2

10

Looks like you have to cast SelectedValue into KeyValuePair<int, int>:

string value = ((KeyValuePair<int, int>)comboBox1.SelectedValue).Value.ToString();

However, you should put a brakepoint there and check what type SelectedValue really is.

I assume it's KeyValuePair<int, int> because your source collection is Dictionary<int, int> and because of output string for SelectedValue.ToString() which is [1, 202].

MarcinJuraszek
  • 118,129
  • 14
  • 170
  • 241
2

If you specify the ValueMember, you can avoid the cast operation. It's important that you set the path before the datasource, or it will fire the changed event with a selected value that is a keyvaluepair.

comboBox1.DisplayMemberPath = "Value";
comboBox1.SelectedValuePath= "Key";
comboBox1.ItemsSource = dictionary;
string value = comboBox1.SelectedValue.ToString();
VoteCoffee
  • 3,300
  • 26
  • 31