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

I have a BindingSource with a BindingList<Foo> as the data source. I would like to work with the BindingSource Find method to find an element. However, a NotSupportedException is NotSupportedException when I do the following, although my data source implements an IBindingList (and such an exception is not registered in MSDN):

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

I have attached a short example below (a ListBox , a Button and a BindingSource ). Can someone help me get a Find call?

 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(); } } 
+4
source share
2 answers

BindingList<T> does not support searching as it is. In fact, bindingSource1.SupportsSearching returns false. The Find function exists for other classes that want to implement the IBindingList interface that supports the search.

To get the value, you must do bindingSource1.ToList().Find("Bar",5);

0
source

I managed 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 allows you to see the position, as well as find an object

+13
source

All Articles