Search code examples
c#eventscomboboxselectionchanged

SelectionChanged event on ComboBox create dynamically


In my application I have 2 ComboBox. When I select a ComboBoxItem in the first ComboBox the second one generates the relative ComboBoxItem. But if I create a SelectionChanged event on the second ComboBox I get this error. Why? Thanks!

private void scarpeBox_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
    ComboBox combo = (ComboBox)sender;
    ComboBoxItem item = (ComboBoxItem)combo.SelectedItem;
    for (int i = 0; i < 16; i++)
        if (combo.Items[i] == item) id = i;
}

InvalidCastException


Solution

  • Your SelectedItem is of value String, it's not a control like you thought it would be. You're trying to convert your String to a ComboboxItem, which throws your exception.

    In your example, I would use the SelectedIndex property:

    private void scarpeBox_SelectionChanged(object sender, SelectionChangedEventArgs e)
    {
        ComboBox combo = (ComboBox)sender;
        id = combo.SelectedIndex;
    }
    

    Your loop seems to look for the position of your SelectedItem, so replace your code with above, and it will return the position of the item in the ComboBox.