【问题标题】:How do I find an item by value in an combobox in C#?如何在 C# 的组合框中按值查找项目?
【发布时间】:2012-04-15 08:53:51
【问题描述】:

在 C# 中,我有 a 类型的变量 string

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

【问题讨论】:

  • 请显示组合框是如何填充的。
  • 请添加标签以表明您使用的是哪个 UI 工具包。

标签: c# combobox find items


【解决方案1】:

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

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

要获取项目本身,请编写:

comboBox1.Items[index];

【讨论】:

    【解决方案2】:

    您应该在 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
    }
    

    【讨论】:

    • 我认为 FindExactString() 适用于 ComboBox 的 DisplayMember 属性。我认为问题是询问如何匹配 ComboBox 的 ValueMember 属性。
    【解决方案3】:

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

    【讨论】:

      【解决方案4】:

      嗨,伙计们,如果搜索文本或值,最好的方法是

      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;
      

      【讨论】:

      • 使用 "if ((string) (ComboBox1.Items[i]) == "SearchValue")" 而不是 "ComboBox1.SelectedIndex = i; if ((string)(ComboBox1.SelectedValue) = = "搜索值")"
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-01-28
      • 2018-01-23
      相关资源
      最近更新 更多