BindingSource.Find抛出NotSupportedException(DataSource是BindingList <T>)

Mat*_*eid 4 .net c# data-binding bindingsource winforms

BindingSource有一个BindingList<Foo>附加的数据源.我想用合作BindingSourceFind方法来查找的元素.但是,NotSupportedException当我执行以下操作时会抛出a ,即使我的数据源确实实现了IBindingList(并且MSDN中没有记录此类异常):

int pos = bindingSource1.Find("Bar", 5);
Run Code Online (Sandbox Code Playgroud)

我在下面附上了一个简短的例子(a ListBox,a Button和a BindingSource).有人可以帮我Find调用吗?

public partial class Form1 : Form
{
    public Form1() { InitializeComponent(); }

    private void Form1_Load(object sender, EventArgs e)
    {
        var src = new BindingList<Foo>();
        for(int i = 0; i < 10; i++)
        {
            src.Add(new Foo(i));
        }

        bindingSource1.DataSource = src;
    }

    private void button1_Click(object sender, EventArgs e)
    {
        int pos = bindingSource1.Find("Bar", 5);
    }
}

public sealed class Foo
{
    public Foo(int bar)
    {
        this.Bar = bar;
    }

    public int Bar { get; private set; }

    public override string ToString()
    {
        return this.Bar.ToString();
    }
}
Run Code Online (Sandbox Code Playgroud)

Kir*_*eed 17

我能够解决我的类似问题

var obj = bindingSource1.List.OfType<Foo>().ToList().Find(f=> f.Bar == 5);
var pos = bindingSource1.IndexOf(obj);
bindingSource1.Position = pos;
Run Code Online (Sandbox Code Playgroud)

这有利于查看位置以及找到对象


Han*_*s Z 0

BindingList<T>不支持搜索,按原样。事实上bindingSource1.SupportsSearching返回 false。该Find函数适用于其他想要实现IBindingList支持搜索的接口的类。

为了获得一个值,你应该这样做bindingSource1.ToList().Find("Bar",5);

  • 我想使用如上所述的查找方法,但是当我尝试它时,出现以下错误“System.Windows.Forms.BindingSource”不包含“ToList”的定义 (5认同)
  • 好的,“SupportsSearching”是“false”,谢谢。然而,我重建的代码有点不同:“bindingSource1.List.OfType&lt;Foo&gt;().First(f =&gt; f.Bar == 5);”确实正确返回了对象,这也很好。 (2认同)