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

如何在C#中的组合框中按值查找项?,c#,combobox,find,items,C#,Combobox,Find,Items,在C#中,我有一个类型为string的变量a 如何通过组合框中的a值查找项目(我希望查找没有组合框显示文本值的项目)。您可以使用以下代码查找它 int index = comboBox1.Items.IndexOf(a); 要获取项目本身,请编写: comboBox1.Items[index]; 我知道我的解决方案非常简单有趣,但在我训练之前,我就用过了。重要提示:组合框的下拉样式必须是“DropDownList” 首先在组合框中,然后: bool foundit = false; Stri

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


如何通过
组合框
中的
a
值查找项目(我希望查找没有组合框显示文本值的项目)。

您可以使用以下代码查找它

int index = comboBox1.Items.IndexOf(a);
要获取项目本身,请编写:

comboBox1.Items[index];

我知道我的解决方案非常简单有趣,但在我训练之前,我就用过了。重要提示:组合框的下拉样式必须是“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的方法(解决方案)更好更好。

您应该在组合框控件上看到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
}

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

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;
int Selected=-1;
int count=ComboBox1.Items.count;

对于(int i=0;(i请显示combobox是如何填充的。请添加一个标记以指示您正在使用的UI工具包。我认为FindExactString()适用于combobox的DisplayMember属性。我认为问题在于如何匹配combobox的ValueMember属性。请使用“if((string)(Combobobox1.Items[i])=”SearchValue“)而不是“ComboBox1.SelectedIndex=i;if((字符串)(ComboBox1.SelectedValue)==”SearchValue“)