[英]How do I find an item by value in an combobox in C#?
In C#, I have variable, a
, of type string
.在 C# 中,我有
a
string
类型的变量a
。
How do I find item
by value of a
in combobox
(I want find item with value no display text of combobox).如何通过
combobox
的a
的值find item
(我想找到没有组合框显示文本的值的项目)。
You can find it by using the following code.您可以使用以下代码找到它。
int index = comboBox1.Items.IndexOf(a);
To get the item itself, write:要获取项目本身,请编写:
comboBox1.Items[index];
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.您应该在 FindStringExact() 的组合框控件上看到一个方法,它将搜索显示成员并在找到时返回该项目的索引。 If not found will return -1.
如果没有找到将返回-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
}
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的方式(解决方案)更好更好。
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;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.