【问题标题】:Finding specific value within a loop在循环中查找特定值
【发布时间】:2014-01-30 19:50:17
【问题描述】:

我在ComboBox 中使用枚举。我希望它允许编辑,以便用户可以在其中输入内容。我将 Enum 转换为 string[] arrayItems,而 listItems 是 Enum 列表的长度。

现在我想检查用户的文本输入:如果它没有被列出,它应该会显示一条消息,表明该项目没有在那里列出。

但对于我的代码(如下),它多次显示错误:

// Converted enum to string[] before

for (int i = 0; i < listItems; i++)
{
    if (comboBox1.Text != arrayItems[i])
    {
        message = string.Format("Sorry! " + comboBox1.Text + " not found.");
    }
}

每次我启动它时都会显示错误,因为它会遍历列表中的每个元素。我希望它可以检查整个枚举列表并在输入错误的情况下给出一次错误。

【问题讨论】:

    标签: c# for-loop combobox enums iteration


    【解决方案1】:

    您可以将循环更改为

    bool ok = false;
    for (int i = 0; i < listItems; i++)
    {
        if (comboBox1.Text == arrayItems[i])
        {
            ok=true;
            break;
        }
    }
    
    if(ok==false)
    {
        message = string.Format("Sorry! " + comboBox1.Text + " not found.");
    }
    

    【讨论】:

    • 我发誓在发布与布尔变量同名的示例之前我没有看过你的代码:)
    【解决方案2】:
    if(arrayItrmd.Contains(combobox1.Text))
    {
        //logic if trur
    }
    

    【讨论】:

      【解决方案3】:

      您可以为此使用 LINQ 的 All。顾名思义,只有当所有元素都与您的查询相对应时,它才会成立。基本上相当于!Any

      if (arrayItrmd.All(item => item != comboBox1.Text))
      {
          message = string.Format("Sorry! " + comboBox1.Text + " not found.");
      }
      

      这意味着“如果 arrayItrmd 中的每个元素都不等于 comboBox1 的文本,则分配消息。”

      【讨论】:

        【解决方案4】:

        你可以忽略循环的使用

        if(tmpImageArray.FirstOrDefault(a => a == comboBox1.Text) == default(String))
        {
           message = comboBox1.Text + " not found";
        }
        else{
           message = comboBox1.Text + " found";
        }
        

        【讨论】:

          【解决方案5】:

          我已经这样解决了这个问题,

          首先我将绑定到组合框的枚举

           public enum comboboxVals
              {
                  one, two, three
              }
          

          然后像这样设置我的组合框的数据源

            comboBox1.DataSource = Enum.GetNames(typeof(comboboxVals));
          

          然后在我的组合框事件之一中实现代码以检查值是否有效,例如组合框离开、验证和验证事件..

           private void comboBox1_Validating(object sender, CancelEventArgs e)
                  {
                      var cbx = sender as ComboBox;
                      if (!Enum.IsDefined(typeof(comboboxVals), cbx.Text))
                      {
                          MessageBox.Show(cbx.Text + " not in the list");
                          e.Cancel=true;
                      }
                      else
                      {
                          // Implement your logic here
                      }
          
          
                  }
          

          【讨论】:

            猜你喜欢
            • 1970-01-01
            • 2017-11-12
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 2023-01-02
            • 2015-10-05
            相关资源
            最近更新 更多