gpt4 book ai didi

c# - BindingSource.查找多个列

转载 作者:太空宇宙 更新时间:2023-11-03 20:43:24 24 4
gpt4 key购买 nike

是否可以在多个列上使用 BindingSource 的 Find 方法?

例如,假设我有一个显示当前宠物的 GridView ;两个组合框,cboPetType 和 cboGender;以及一个用于根据这两个组合框的值在 Pet 表中创建新记录的按钮。

现在,假设我只想要每种 PetType/Gender 组合中的一种(狗 - M、猫 - F 等)。因此,如果我的 BindingSource 中有 Dog - M 宠物,并且用户从组合框中选择 Dog 和 M,我想阻止用户通知他们组合已经存在。

过去,我使用 BindingSource.Find 方法来做类似的事情,但据我所知,这只适用于搜索一列(即 BindingSource.Find("PetType", cboPetType.SelectedValue );).

是否可以基于多列搜索绑定(bind)源?如果没有,有什么建议可以达到我想要的结果吗?非常感谢任何建议!

最佳答案

不,很遗憾,这是不可能的。虽然给定一个特定数据源,这样的搜索可能会相当简单,但以更通用的方式(如 BindingSource 会做的那样)做起来不太透明.一方面,语法不太明显。这是一个有点人为的解决方案:

public class Key
{
public string PropertyName {get; set;}
public object Value {get; set;}
}

public static int Find(this BindingSource source, params Key[] keys)
{
PropertyDescriptor[] properties = new PropertyDescriptor[keys.Length];

ITypedList typedList = source as ITypedList;

if(source.Count <= 0) return -1;

PropertyDescriptorCollection props;

if(typedList != null) // obtain the PropertyDescriptors from the list
{
props = typedList.GetItemProperties(null);
}
else // use the TypeDescriptor on the first element of the list
{
props = TypeDescriptor.GetProperties(source[0]);
}

for(int i = 0; i < keys.Length; i++)
{
properties[i] = props.Find(keys[i].PropertyName, true, true); // will throw if the property isn't found
}

for(int i = 0; i < source.Count; i++)
{
object row = source[i];
bool match = true;

for(int p = 0; p < keys.Count; p++)
{
if(properties[p].GetValue(row) != keys[p].Value))
{
match = false;
break;
}
}

if(match) return i;
}

return -1;
}

你可以这样调用它:

BindingSource source = // your BindingSource, obviously 

int index = source.Find(
new Key { PropertyName = "PetType", Value = "Dog" },
new Key { PropertyName = "Gender", Value = "M" });

请记住,要使其可用,您确实需要一种更智能的比较算法,但我会将其作为练习留给读者。检查 IComparable 的实现将是一个好的开始。尽管如此,无论具体实现点如何,该概念都应该贯彻始终。

请注意,这不会利用底层数据源可能实现的任何可能的性能优化,而单列 Find 会。

关于c# - BindingSource.查找多个列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1767018/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com