1
Answer

Getting Combobox Selected Value in WPF

Photo of Abolfazl

Abolfazl

10y
15.2k
1
hi
i want to get selected value of a combobox that created in WPF,
i use this code  :


private void cmb_StuffGroup_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
string str;
ComboBoxItem item = (ComboBoxItem)cmb_StuffGroup.SelectedItem;
str = item.Content.ToString();
MessageBox.Show(str, "ITEM");
}


but when i run this code it stop with InvalidCastExeption in line 4.
whats wrong with this code??
thanks 

Answers (1)

2
Photo of Vulpes
NA 96k 2.6m 10y
If your ItemsSource for the ComboBox is a collection of strings, then SelectedItem will also be a string, albeit wrapped in an object.

So I'd try this:

private void cmb_StuffGroup_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
    string str = comboBox1.SelectedItem as string;
    if (str != null) MessageBox.Show(str, "ITEM");     
}



Accepted