elmnt57 elmnt57 -4 years ago 145
C# Question

C# get ComboBox selected Item number relative to the number of items in the ComboBox

Im having a hard time trying to figure this out, till i discovered this is the best approache to my problem, the thing is i have no idea how to do it.

Basicly lest say i have a ComboBox, with 5 items inside (the number of items isnt constant, just an example).

My goal is to, after somone select one of thoes 5 items, discover witch one was it by the number, i mean for example, i have 5 items in the ComboBox and i picked the third item counting from the top, i want my program to know that the user picked the third item.

Anny sujestions on how shoul i do it or has anny one done it and have the code? Cheers.

Answer Source

the combobox has a property called SelectedIndex. It will start with 0 which stands for the first element.

i picked the third item counting from the top

This item will have the index of 2. Take this index an add a 1 and your programm will know which element it has. Unless you want really the index then leave the addition away.
Here is the documentation

There is a cool event called SelectionChanged which you can use to catch the selection:

private void comboBox_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
    int i = comboBox.SelectedIndex;        
}
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download