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.

3 Responses to “BindingList.Find and NotImplementedException”

  1. There’s a better way to do this now… Took me a lot of tinkering with solutions I wasn’t happy with before this solution finally hit me.

    using System;
    using System.Collections.Generic;
    using System.ComponentModel;

    namespace XYZ
    {
    public static class Extensions
    {
    public static T Find(this BindingList s, Predicate exp)
    {
    List list = new List(s);

    return list.Find(exp);
    }
    }
    }

  2. Overriding the FindCore is the right way of supporting find, because winform controls, like the gridview, does not pass predicate to find element. ;)

    alk.

Trackbacks/Pingbacks

  1. Extend BindingList with filter functionality

Leave a Reply