Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

BindingSource.Find throws NotSupportedException (DataSource is BindingList<T>)

I've got a BindingSource with a BindingList<Foo> attached as the data source. I'd like to work with the BindingSource's Find method to look up an element. However, a NotSupportedException is thrown when I do the following, even though my data source does implement IBindingList (and no such exception is documented in MSDN):

int pos = bindingSource1.Find("Bar", 5);

I attached a short example below (a ListBox, a Button and a BindingSource). Could anybody help me getting the Find invocation working?

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();
    }
}
like image 884
Matthias Meid Avatar asked Jun 13 '12 14:06

Matthias Meid


1 Answers

I was able to solve my similar problem using

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

this has the benefit of seeing the position as well as finding the object

like image 133
Kirsten Avatar answered Nov 17 '22 07:11

Kirsten