Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get the current index of a ComboBox?

Say I had a ComboBox with these values:

Black
Red
Blue

And I have Red currently selected. If the user then hits backspace and hits enter I am capturing the KeyDown event of the ComboBox.

In this event I want to delete Red from the list of items in the ComboBox.

However, because the text of the ComboBox is blank by the time KeyDown is called, the SelectedIndex is -1.

Currently I have a workaround that looks like this:

private void myComboBox_SelectedIndexChanged(object sender, EventArgs e)
{
    currentMyComboBoxIndex = myComboBox.FindStringExact(myComboBox.Text);
}

Which works.. but I was just wondering if there is a better way. It seems like this way could break somehow and it seems a bit messy. Is there no way to get the current index of the ComboBox without having to keep track of it with a member variable and updating it when the index changes?

Thank you.

like image 895
Tahmid Meridda Avatar asked Dec 16 '22 09:12

Tahmid Meridda


2 Answers

The way you are doing is fine. You have to keep the selected index in memory because it returns -1 as the SelectedIndex when the text is deleted. You could take the index in this way too.

private void myComboBox_SelectedIndexChanged(object sender, EventArgs e)
{
    currentMyComboBoxIndex = myComboBox.SelectedIndex;
}
like image 67
CharithJ Avatar answered Jan 04 '23 22:01

CharithJ


You can use the following code to get the selected item of the combo box as an object:

ComboBox comboBox = new ComboBox();
// Initialize combo box
comboBox.Items.Add("Black");
comboBox.Items.Add("Red");
comboBox.Items.Add("Blue");
// Get selected one
string current = (string)comboBox.SelectedItem;

Also, the selected item can be easily removed by using one of the following lines of code:

// By item
comboBox.Items.Remove(comboBox.SelectedItem);
// By Index
comboBox.Items.RemoveAt(comboBox.SelectedIndex);
like image 31
Hossein Mobasher Avatar answered Jan 04 '23 23:01

Hossein Mobasher