【发布时间】:2012-04-15 08:53:51
【问题描述】:
在 C# 中,我有 a 类型的变量 string。
我如何通过combobox 中的a 的值来find item(我想找到值没有组合框显示文本的项目)。
【问题讨论】:
-
请显示组合框是如何填充的。
-
请添加标签以表明您使用的是哪个 UI 工具包。
在 C# 中,我有 a 类型的变量 string。
我如何通过combobox 中的a 的值来find item(我想找到值没有组合框显示文本的项目)。
【问题讨论】:
您可以使用以下代码找到它。
int index = comboBox1.Items.IndexOf(a);
要获取项目本身,请编写:
comboBox1.Items[index];
【讨论】:
您应该在 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
}
【讨论】:
我知道我的解决方案非常简单有趣,但在训练之前我使用了它。重要提示:组合框的 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 的方式(解决方案)更好更好。
【讨论】:
嗨,伙计们,如果搜索文本或值,最好的方法是
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;
【讨论】: