-->

How do I find an item by value in an combobox in C

2019-02-12 00:12发布

问题:

In C#, I have variable, a, of type string.

How do I find item by value of a in combobox (I want find item with value no display text of combobox).

回答1:

You can find it by using the following code.

int index = comboBox1.Items.IndexOf(a);

To get the item itself, write:

comboBox1.Items[index];


回答2:

You should see a method on the combo box control for FindStringExact(), which will search the displaymember and return the index of that item if found. If not found will return -1.

//to select the item if found: 
mycombobox.SelectedIndex = mycombobox.FindStringExact("Combo"); 

//to test if the item exists: 
int i = mycombobox.FindStringExact("Combo"); 
if(i >= 0)
{
  //exists
}


回答3:

I know my solution is very simple and funny, but before I train I used it. Important: DropDownStyle of combobox must be "DropDownList"!

First in combobox and then:

bool foundit = false;
String mystr = "item_1";
mycombobox.Text = mystr;
if (mycombobox.SelectedText == mystr) // Or using mycombobox.Text
    foundit = true;
else foundit = false;

It works for me right and resolved my problem... But the way (solution) from @st-mnmn is better and fine.



回答4:

Hi Guys the best way if searching for a text or value is

int Selected;    
int count = ComboBox1.Items.Count;
    for (int i = 0; (i<= (count - 1)); i++) 
     {        
         ComboBox1.SelectedIndex = i;
        if ((string)(ComboBox1.SelectedValue) == "SearchValue") 
        {
            Selected = i;
        }

    }

    ComboBox1.SelectedIndex = Selected;