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();
}
}
BindingList<T>does not support searching, as is. In factbindingSource1.SupportsSearchingreturns false. TheFindfunction is there for other classes that want to implement theIBindingListinterface that do support searching.To get a value, you should do
bindingSource1.ToList().Find("Bar",5);