Brian Noyes' Blog

Use BindingList<T> for data bound collections

10 Jan 2005

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:

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.