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

╄→гoц情女王★ 提交于 2019-11-29 11:26:14

问题


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


来源:https://stackoverflow.com/questions/10160708/how-do-i-find-an-item-by-value-in-an-combobox-in-c

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!