在 C# 中,我有变量
a
,类型为 string
。
我如何
find item
按a
中的combobox
值(我想找到值没有组合框显示文本的项目)。
您可以使用以下代码找到它。
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;
对于 VB.NET 代码,请将其转换为 C#。
我准备了.NET 3.5 Windows应用程序的以下函数bcoz:
Public Function FindIndex_by_value(ByRef combo As ComboBox, ByVal value As String) As Integer
Dim idx As Integer
For i As Integer = 0 To combo.Items.Count - 1
Dim itm As DataRowView
itm = combo.Items(i)
Dim vl As String = itm.Item(0)
If vl = value Then
idx = i
Exit For
End If
Next
Return idx
End Function
使用此功能:
Dim idx As Integer = FindIndex_by_value(comboBox1, "Value_to_Search")
comboBox1.SelectedIndex = idx
重要: 这里 0 是值列的索引,我在数据库查询中使用第一列作为值列。