如何在 C# 的组合框中按值查找项目?

问题描述 投票:0回答:5

在 C# 中,我有变量

a
,类型为
string

我如何

find item
a
中的
combobox
值(我想找到值没有组合框显示文本的项目)。

c# combobox find items
5个回答
39
投票

您可以使用以下代码找到它。

int index = comboBox1.Items.IndexOf(a);

要获取物品本身,请写:

comboBox1.Items[index];

14
投票

您应该在组合框控件上看到一个 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
}

0
投票

我知道我的解决方案非常简单有趣,但在训练之前我使用了它。重要提示:组合框的 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 的方法(解决方案)更好更好。


0
投票

大家好,如果搜索文本或值,最好的方法是

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;

0
投票

对于 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 是值列的索引,我在数据库查询中使用第一列作为值列。

© www.soinside.com 2019 - 2024. All rights reserved.