【问题标题】:How to see if a value is in a combo box如何查看一个值是否在组合框中
【发布时间】:2019-04-09 15:27:16
【问题描述】:

在我的 winform 中,我需要检查用户输入的字符串值是否在组合框中,其中组合框数据的值来自数据库。

是否可以简单地检查用户的值是否已经在组合框中,或者我必须手动检查数据库以查看数据是否存在?

    private void Button1_Click(object sender, EventArgs e)
    {
        if (!questionList.Items.Contains(customQ.Text.Trim()))
        {
            dbconnect.addQ(customQ.Text);
            refreshBox();
        }
    }

我尝试过使用包含,但它总是返回 false,即使数据不在组合框中,任何反馈都表示赞赏:)

【问题讨论】:

    标签: c# asp.net .net winforms combobox


    【解决方案1】:

    您应该能够使用 FindStringExact 方法来确定 ComboBox 中是否已存在项目。

    if (questionList.FindStringExact(customQ.Text.Trim()) < 0)
    {
        // The item was not found to already exist
    }
    

    您可以在 .NET 文档中阅读有关 FindStringExact 方法的更多信息:

    https://docs.microsoft.com/en-us/dotnet/api/system.windows.forms.combobox.findstringexact?view=netframework-4.7.2

    希望这会有所帮助。

    【讨论】:

      【解决方案2】:

      将项目转换为字符串可以满足您的需求。项目作为 ObjectCollection 处理,它们的 IEnumerable 甚至不会尝试检查是否包含字符串。

      private void Button1_Click(object sender, EventArgs e)
      {
          if (!questionList.Items.Cast<string>().Contains(customQ.Text.Trim()))
          {
              dbconnect.addQ(customQ.Text);
              refreshBox();
          }
      }
      

      上面的代码在我的测试中运行正常,希望它对你有用。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2021-11-06
        • 2021-05-28
        • 2023-03-23
        • 1970-01-01
        • 1970-01-01
        • 2017-06-08
        • 2021-08-31
        • 1970-01-01
        相关资源
        最近更新 更多