alkampfer on October 12th, 2007

BindingList<T> is a great class to do binding to list of custom objects, it implements IBindingList for you, giving the ability to use the BindingList<T> as datasource for the BindingSource control. But when you cast the BindingList<T> to the IBindingList interface and try to call Find() Method you’ll get a NotImplementedException, how can it be possible?. The reason for this can be found here, but the real question is, it is possible to build a better BindingList that supports a generic Find() for properties of a business object?

The answer is “YES”, first of all you need a generic IComparer, and you can find a possible implementation on this post of my blog, it is quite optimized to cache the runtimeMethodHandle avoiding the need of reflection each time you need an IComparer. With the generic IComparer implementing a better BindingList Is a breeze.

class NablaBindingList<T> : BindingList<T> {
 
   
protected override bool SupportsSearchingCore {
      
get {
         
return true;
      }
   }
 
   
protected override int FindCore(PropertyDescriptor prop, object key) {
 
      
if (key is T) {
         
GenericComparer<T> comparer = GenericComparerFactory.GetComparer<T>(prop.Name, false);
         
for (Int32 index = 0; index < Items.Count; ++index) {
            
if (comparer.Compare(Items[index], (T) key) == 0)
               
return index;
         }
         
return -1;
      }
      
throw new NotSupportedException(“Cannot compare Apple With Orange”);
   }
}

Now I left to the reader the task to support Sorting :D

Alk.



kick it on DotNetKicks.com

One Response to “BindingList.Find and NotImplementedException”

Trackbacks/Pingbacks

  1. Extend BindingList with filter functionality

Leave a Reply