如何在C#中的组合框中按值查找项目?

时间:2012-04-15 08:53:52

标签: c# combobox find items

在C#中,我的变量a的类型为string

我如何find item a combobox的{​​{1}}(我希望查找带有值的项目没有组合框的显示文字)。

4 个答案:

答案 0 :(得分:25)

您可以使用以下代码找到它。

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

要获取项目本身,请写下:

comboBox1.Items[index];

答案 1 :(得分:7)

你应该在FindStringExact()的组合框控件上看到一个方法,它将搜索displaymember并返回该项的索引(如果找到)。如果未找到则返回-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
}

答案 2 :(得分:0)

我知道我的解决方案非常简单有趣,但在我训练之前我使用它。重要提示:组合框的DropDownStyle必须是" DropDownList"!

首先在组合框中然后:

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

它对我有用并解决了我的问题...... 但是来自@ st-mnmn的方式(解决方案)更好更好。

答案 3 :(得分:0)

嗨,如果搜索文本或值是最好的方法

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;