Use BindingList for data bound collections

I finished up another chapter on my book last night. This one was on creating data bound custom business objects and collections. I won’t try to reiterate the entire chapter here, but I will pass along one of the key take-aways: use BindingList for custom business object collections if you want to provide rich data binding capabilities in Windows Forms 2.0.

The BindingList generic type is defined in the System.ComponentModel.Collections.Generics namespace in Beta 1, but is getting refactored into System.ComponentModel in Beta 2. Basically this type allows you to create strongly typed collections that implement IBindingList (partially), IList, ICollection, and IEnumerable, with a single line of code:

BindingList CustomerCollection = new BindingList();

By doing just this, you get a collection that works fine with both Windows Forms and ASP.NET data binding mechanisms, including two-way data binding (presentation and editing) support in Windows Forms, and also will fire ListChanged events whenever items in the collection are added, removed, or replaced. If you want to support events when the contained objects are edited, you will need to implement the INotifyPropertyChanged interface on the object type definition itself (this interface is named IPropertyChanged in Beta 1).

Additionally, if you want to support sorting and searching on the collection, all it takes it to derive a class from your BindingList parameterized type, and override a few base class methods and properties. For example, you could declare a Customer collection and provide searching capability with something like the following:


publicclassCustomerCollection : BindingList<Customer>
{
protectedoverridebool SupportsSearchingCore { get { returntrue; } }
protectedoverrideint FindCore(PropertyDescriptor property, object key)
{
for (int i = 0; i < Count; i++)
{
Customer c = this[i];
if (property.GetValue(c) == key)
{
return i;
}
}
return -1; // Not found

}
}

Very powerful stuff. Sorting is a little more involved, but follows the same process. Override the sort related properties, and provide a sorting algorithm in the ApplySortCore override and you are off and running.

So much easier and more powerful than the old derive from CollectionBase approach. You get type safety, alot of additional functionality, and the efficiency of generic types.