0

I have a combo box and a button. When I click the button, it's supposed to change the selected value and then fire the code when the item was changed. Unfortunately, the selection changed event fires before I set the selected value of the combo box.

My Combo Box's code on initialize:

ListCB.SelectedValuePath = "Key";
ListCB.DisplayMemberPath = "Value";
ListCB.Items.Add(new KeyValuePair<int, string>(1, "One"));

ListCB.SelectedValuePath = "Key";
ListCB.DisplayMemberPath = "Value";
ListCB.Items.Add(new KeyValuePair<int, string>(2, "Two"));

ListCB.SelectedValuePath = "Key";
ListCB.DisplayMemberPath = "Value";
ListCB.Items.Add(new KeyValuePair<int, string>(3, "Three"));

My Button's code:

ListCB.SelectedValue = 3;

My Selection Changed Event:

private void ListCB_Change(object sender, SelectionChangedEventArgs e)
{
    MessageBox.Show("Value is now: " + ListCB.SelectedValue);
}

What happens is if for example I select 1 from the combo box and click the button, it will say Value now is: One instead of Three.

Am I using the wrong event? Or am I using a wrong way to change the selected value?

Klaus Bean
  • 37
  • 8
  • ListCB.SelectedIndex works as intended but unfortunately, it's not viable for my usage as the contents are volatile. – Klaus Bean Aug 20 '17 at 09:47

1 Answers1

1

Use SelectionChangedEventArgs to get newly selected item

private void ListCB_Change(object sender, SelectionChangedEventArgs e)
{
    var item = (KeyValuePair<int, string>)e.AddedItems[0];
    MessageBox.Show("Value is now: " + item.Key);
}
Mitya
  • 632
  • 5
  • 18
  • Thanks, this works, it now says the correct value. I got a question though, what's the reason behind the combobox's item updating only after the messagebox is finished? – Klaus Bean Aug 20 '17 at 10:37
  • @KlausBean There is a good explanation of how it works https://stackoverflow.com/a/31574510/2189031. In short words you need to use `SelectedItem` instead of `SelectedValue` after casting `sender` to `ComboBox` – Mitya Aug 20 '17 at 14:18