如何在 C# 的组合框中按值查找项目?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/10160708/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How do I find an item by value in an combobox in C#?
提问by Duy Khanh
In C#, I have variable, a, of type string.
在 C# 中,我有a类型为 的变量string。
How do I find itemby value of ain combobox(I want find item with value no display text of combobox).
我如何find item通过ain的值combobox(我想找到没有组合框显示文本的值的项目)。
采纳答案by st mnmn
You can find it by using the following code.
您可以使用以下代码找到它。
int index = comboBox1.Items.IndexOf(a);
To get the item itself, write:
要获取项目本身,请编写:
comboBox1.Items[index];
回答by user3290286
I know my solution is very simple and funny, but before I train I used it. Important: DropDownStyle of combobox must be "DropDownList"!
我知道我的解决方案非常简单和有趣,但在我训练之前我使用了它。重要提示:combobox 的 DropDownStyle 必须是“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.
它对我有用并解决了我的问题......但是@st-mnmn的方式(解决方案)更好更好。
回答by Andrew Mulvaine
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.
您应该在 FindStringExact() 的组合框控件上看到一个方法,它将搜索显示成员并在找到时返回该项目的索引。如果没有找到将返回-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
}
回答by Teezy7
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;

