简体   繁体   中英

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

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).

You can find it by using the following code.

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

To get the item itself, write:

comboBox1.Items[index];

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
}

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.

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

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

    }

    ComboBox1.SelectedIndex = Selected;

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