如何在C#中的combobox中按值找到项目?
在C#中,我有a
类型string
变量a
。
如何在combobox
找到a
的值(我想找到值没有combobox的显示文本的项目)。
您可以使用以下代码找到它。
int index = comboBox1.Items.IndexOf(a);
要获取项目本身,请写入:
comboBox1.Items[index];
您应该在FindStringExact()的combobox控件上看到一个方法,它将搜索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; 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;
我知道我的解决方案非常简单有趣,但在我训练之前我使用它。 重要提示:combobox的DropDownStyle必须是“DropDownList”!
首先在combobox中,然后:
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的方式(解决方案)更好更好。