简体   繁体   中英

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的

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 .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM