c# - 如何检查文本值是否在包含 DataRowView 的控件的数据源中?

标签 c# .net winforms data-binding

在验证 ComboBox 时,我尝试检查 ComboBox 中的值是否位于与所述 ComboBox 数据绑定(bind)的值列表中。
数据源是 BindingSource,底层项是 DataRowView 类型。
所以我不知道如何将组合框的值与数据源的 DataRowView 的“Person”字段进行比较

此外,在有人建议将 DropDownStyle 设置为 DropDownList 之前,这不是本例的一个选项。

我尝试过的:

private void ddPerson_Validating(object sender, CancelEventArgs e)
    {
        ComboBox cmbo = sender as ComboBox;
        if (!string.IsNullOrWhiteSpace(ddPerson.Text))
        {
            if (cmbo.Items.Contains(ddPerson.Text))
            {
                errorProvider1.SetError(cmbo, "");
            }
            else
            {
                errorProvider1.SetError(cmbo, "\"" + person.Text + "\" is not in the list of accepted values");
            }
        }
        else
        {
            errorProvider1.SetError(cmbo, cmbo.DisplayMember + " is required");
        }
    }

我也尝试过

if (personBindingSource.Contains(ddPerson.Text))
我尝试的上述两个解决方案不起作用,因为 personBindingSource 和 cmbo.Items 只是 DataRowView 对象的列表。

从这里开始https://stackoverflow.com/a/24126821/3490417 我试过
if (cmbo.Items.Cast<DataRowView>().Select(x => Convert.ToString(x["Person"]).Contains(ddPerson.Text))
编译时不会出现错误“无法将类型‘System.Collections.Generic.IEnumerable’隐式转换为‘bool’

编辑:
我找到了另一种方法来检查组合框的值是否在组合框的绑定(bind)源中。虽然我最终使用了 mm8's解决方案,因为它更干净。

int found = personBindingSource.Find("Person", ddPerson.Text);
if (found < 0)
{ errorProvider1.SetError(cmbo, "\"" + person.Text + "\" 
  is not in the list of accepted values"); }           

最佳答案

试试这个:

if (cmbo.Items.OfType<DataRowView>().Any(x => x["Person"]?.ToString() == ddPerson.Text))

关于c# - 如何检查文本值是否在包含 DataRowView 的控件的数据源中?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54201643/

相关文章:

c# - 要求用户更新 .NET

vb.net - WinForm 上的阴影会扭曲界面

asp.net - ConfigureAwait(false) 如何防止 Ui 死锁

c# - [ClassCleanup]和[TestCleanup]在什么情况下不运行

c# - 类型对象的 .NET MVC Action 参数

c# - 使用 modelstate.addmodelerror 的 MVC 自定义验证

c# - 应用程序显示两个菜单条而不是一个

c# - 无法加载类型 - 自定义 ViewPage 类基类

c# - 在 C# 中有什么区别 : string vs String

asp.net - Webapi、Webhost 和 Owin 之间的关系