如何查看值是否在组合框中

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


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


    private void Button1_Click(object sender, EventArgs e)

    {

        if (!questionList.Items.Contains(customQ.Text.Trim()))

        {

            dbconnect.addQ(customQ.Text);

            refreshBox();

        }

    }

我试过使用 contain,但它总是返回 false,即使数据不在组合框中,也欢迎任何反馈:)


慕尼黑8549860
浏览 144回答 2
2回答

长风秋雁

您应该能够使用 FindStringExact 方法来确定某个项目是否已存在于 ComboBox 中。if (questionList.FindStringExact(customQ.Text.Trim()) < 0){&nbsp; &nbsp; // The item was not found to already exist}您可以在 .NET 文档中阅读有关 FindStringExact 方法的更多信息:https://learn.microsoft.com/en-us/dotnet/api/system.windows.forms.combobox.findstringexact?view=netframework-4.7.2希望这可以帮助。

明月笑刀无情

将 Items 转换为字符串将适用于您想要的。项目作为 ObjectCollection 处理,它们的 IEnumerable 甚至不会尝试检查是否包含字符串。private void Button1_Click(object sender, EventArgs e){&nbsp; &nbsp; if (!questionList.Items.Cast<string>().Contains(customQ.Text.Trim()))&nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; dbconnect.addQ(customQ.Text);&nbsp; &nbsp; &nbsp; &nbsp; refreshBox();&nbsp; &nbsp; }}上面的代码在我的测试中正常工作,希望它对你有用。
打开App,查看更多内容
随时随地看视频慕课网APP