在验证 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/