【问题标题】:How to check if text value is in a control's DataSource which contains DataRowViews?如何检查文本值是否在包含 DataRowViews 的控件的 DataSource 中?
【发布时间】:2019-01-15 15:10:28
【问题描述】:

在验证 ComboBox 时,我试图检查 ComboBox 中的值是否在数据绑定到所述 ComboBox 的值列表中。
数据源是 BindingSource,基础项的类型是 DataRowView。
所以我不知道如何将组合框的值与 DataSource 的 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'

编辑:
我找到了另一种检查组合框的值是否在组合框的绑定源中的方法。虽然我最终使用了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"); }           

【问题讨论】:

  • 对不起,我的意思是说,你能显示 ddPerson 的 DataSource 吗?
  • 并非如此,因为它是数据绑定到数据集表的。但我可以告诉你,该表中唯一的字段是“ID”和“Person”
  • 如果您将 ValueMember 设置为“ID”,您只需检查if (ddPerson.SelectedValue == null),那么您的列表中就没有任何内容。

标签: c# .net winforms data-binding


【解决方案1】:

试试这个:

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

【讨论】:

    【解决方案2】:

    无论数据绑定项类型和显示成员属性如何,以下代码都将起作用:

    var isValid = cmbo.Items.Cast<Object>().Any(x=>cmbo.GetItemText(x) == ddPerson.Text);
    

    【讨论】:

    • 要获取项目的显示值,使用GetItemText几乎总是更好。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2023-03-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-04-10
    • 2022-11-26
    • 1970-01-01
    相关资源
    最近更新 更多