elmnt57
elmnt57

Reputation: 19

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 approach to my problem, the thing is I have no idea how to do it.

Basically lets say I have a ComboBox, with 5 items inside (the number of items is not constant, just an example).

My goal is, after someone selects one of those 5 items, to discover which one it was 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.

Any suggestions on how I should do it or has anyone done it and has the code?

Upvotes: 0

Views: 2303

Answers (2)

FilipRistic
FilipRistic

Reputation: 2821

Lets say that you have comboBox and you have label and you want to update label to show index of selected item every time that you click to change selected item.
Just remember that index starts with 0. This is just example of how syntax should look, SelectedIndex method returns INT value in range from 0 to the number of elements-1 based on what item is currently selected.

private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
{
    label1.Text = comboBox1.SelectedIndex.ToString();
}

Upvotes: 0

Mong Zhu
Mong Zhu

Reputation: 23732

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;        
}

Upvotes: 3

Related Questions