[.NET 2.0+] Custom Typed Collections and Data-binding Support
C# version here.
If we want to use a standard collection in .NET 2.0 or later we use a generic List. If we want to create our own strongly-typed collection we used to have to inherit CollectionBase. That was a pain because, in the days before generics, we used to have to define all the type-specific members ourselves. We would inherit members like Clear and RemoveAt from CollectionBase because they didn't depend on the type of the items. Members like Item and Add though, whose return type or parameter type(s) depends on the type of the items, were left up to us. Since the introduction of generics, life has become much easier. To create a strongly typed collection with all the standard functionality we simply inherit the generic Collection class and that's it:
vb.net Code:
Public Class ThingCollection
Inherits System.Collections.ObjectModel.Collection(Of Thing)
End Class
All the standard functionality is inherited from the base class so we don't need to add any members of our own. That said, if we want to provide custom functionality then we can add our own members. The generic Collection class provides methods that you can override to process items as they are added and removed from the collection. One common use for those members is custom validation, e.g.
vb.net Code:
Public Class ThingCollection
Inherits System.Collections.ObjectModel.Collection(Of Thing)
Protected Overrides Sub InsertItem(ByVal index As Integer, ByVal item As Thing)
Dim duplicateID As Boolean = False
For Each existingItem As Thing In Me.Items
If item.ID = existingItem.ID Then
duplicateID = True
Exit For
End If
Next
If duplicateID Then
'Don't add an item with a duplicate ID.
Throw New ArgumentException("An item with the specified ID already exists")
Else
'Allow the item to be added.
MyBase.InsertItem(index, item)
End If
End Sub
Protected Overrides Sub SetItem(ByVal index As Integer, ByVal item As Thing)
Dim duplicateID As Boolean = False
For existingIndex As Integer = 0 To Me.Count - 1
'Ignore the existing item at the index being set because it is being replaced.
If existingIndex <> index AndAlso _
item.ID = Me.Items(existingIndex).ID Then
duplicateID = True
Exit For
End If
Next
If duplicateID Then
'Don't add an item with a duplicate ID.
Throw New ArgumentException("An item with the specified ID already exists")
Else
'Allow the item to be added.
MyBase.SetItem(index, item)
End If
End Sub
End Class
So, that's nice and easy. Now, with regards to data-binding, you can quite easily bind either a generic List or your own strongly-typed collection to controls in your UI and the data they contain will be displayed. That's because they all implement the IList interface, which is all data-binding requires. The problem is, if you intend to make changes to your collection in code, like adding or removing items or editing properties of the items, then you'll be disappointed if you expect to see those changes reflected in the UI.
That's because the bound control is not implicitly aware of any changes taking place in the data source. It must be explicitly notified of changes in order to know that it should update its display. In order to provide such notification your data source must implement the IBindingList interface, which neither the generic List nor generic Collection class does. The easy way out of this is to bind your data to a BindingSource and then bind that to the control(s). You can then call ResetCurrentItem, ResetItem or RestBindings on the BindingSource to raise its ListChanged event and thereby notify the bound control to update.
That's all well and good, but what if the changes to the collection are occurring in code that can't see the BindingSource, like a business logic layer? In that case you need your collection to implement IBindingList itself. You could do that from scratch but you don't actually need to. Instead of deriving your collection directly from the generic Collection class, you can instead inherit the generic BindingList class, which itself inherits Collection and adds an IBindingList implementation. Again, you don't have to add any code of your own if you only want the standard functionality:
vb.net Code:
Public Class ThingCollection
Inherits System.ComponentModel.BindingList(Of Thing)
End Class
Now your collection will raise its ListChanged event automatically whenever you add, insert, set or remove an item or clear the list. Any bound controls will automatically update as a result.
Now, that's fine for making changes to the list but what about if you make changes to items that are already in the list? Bound controls will not update automatically because the BindingList doesn't raise a ListChanged event automatically because it doesn't inherently know when an item changes. This is where you need to do a little bit of work.
What needs to happen is that your item class needs to raise an event when a property value changes, e.g.
vb.net Code:
Public Class Thing
Private _name As String
Public Property Name() As String
Get
Return Me._name
End Get
Set(ByVal value As String)
If Me._name <> value Then
Me._name = value
Me.OnNameChanged(EventArgs.Empty)
End If
End Set
End Property
Public Event NameChanged As EventHandler
Protected Overridable Sub OnNameChanged(ByVal e As EventArgs)
RaiseEvent NameChanged(Me, e)
End Sub
End Class
Your typed collection can now handle that event and raise its own ListChanged event to notify any bound controls of the change:
vb.net Code:
Public Class ThingCollection
Inherits System.ComponentModel.BindingList(Of Thing)
Private Sub HandleNameChanged(ByVal sender As Object, ByVal e As EventArgs)
Me.OnListChanged(New ListChangedEventArgs(ListChangedType.ItemChanged, _
Me.Items.IndexOf(DirectCast(sender, _
Thing))))
End Sub
End Class
Note that you specify ItemChanged as the change type.
Now, that method isn't going to handle any events on its own. We need to attach it to the NameChanged event of each item as it gets added to the list. We also need to make sure we detach when an item gets removed from the list. For that we need to override methods inherited from the Collection class, much as we did for the validation earlier:
vb.net Code:
Public Class ThingCollection
Inherits System.ComponentModel.BindingList(Of Thing)
Protected Overrides Sub InsertItem(ByVal index As Integer, ByVal item As Thing)
MyBase.InsertItem(index, item)
'Attach the event handler to the item being added.
AddHandler item.NameChanged, AddressOf HandleNameChanged
End Sub
Protected Overrides Sub SetItem(ByVal index As Integer, ByVal item As Thing)
'Remove the event handler from the item being removed.
RemoveHandler Me.Items(index).NameChanged, AddressOf HandleNameChanged
MyBase.SetItem(index, item)
'Attach the event handler to the item being added.
AddHandler item.NameChanged, AddressOf HandleNameChanged
End Sub
Protected Overrides Sub RemoveItem(ByVal index As Integer)
'Remove the event handler from the item being removed.
RemoveHandler Me.Items(index).NameChanged, AddressOf HandleNameChanged
MyBase.RemoveItem(index)
End Sub
Protected Overrides Sub ClearItems()
'Remove the event handler from all existing items.
For Each item As Thing In Me.Items
RemoveHandler item.NameChanged, AddressOf HandleNameChanged
Next
MyBase.ClearItems()
End Sub
Private Sub HandleNameChanged(ByVal sender As Object, ByVal e As EventArgs)
Me.OnListChanged(New ListChangedEventArgs(ListChangedType.ItemChanged, _
Me.Items.IndexOf(DirectCast(sender, _
Thing))))
End Sub
End Class
Another useful feature of the IBindingList interface is simple sorting support, i.e. sorting by a single column/property. By adding such support to your typed collection you enable, for instance, a user to click a column header in a DataGridView bound to your collection and have the data sorted automatically. I'll look at that in the next installment. Stay tuned!
1 Attachment(s)
Sorting Using a Custom BindingList
I've attached a test project containing the final Person and PersonCollection classes used in this example, but I'll post code snippets along the way to highlight certain points.
As I mentioned in the previous post, in order to support sorting when bound a collection must implement the IBindingList interface. As I also mentioned, the easiest way to implement the IBindingList interface is to inherit the BindingList class:
vb.net Code:
Public Class PersonCollection
Inherits System.ComponentModel.BindingList(Of Person)
End Class
Now, in order to support sorting in our collection we must do three things:
1. Override the SupportsSorting property and return True;
2. Override the ApplySortCore method and implement our sort; and
3. Override the RemoveSortCore method and remove our sort.
vb.net Code:
Imports System.ComponentModel
Public Class PersonCollection
Inherits System.ComponentModel.BindingList(Of Person)
Protected Overrides ReadOnly Property SupportsSortingCore() As Boolean
Get
Return True
End Get
End Property
Protected Overrides Sub ApplySortCore(ByVal prop As PropertyDescriptor, _
ByVal direction As ListSortDirection)
MyBase.ApplySortCore(prop, direction)
End Sub
Protected Overrides Sub RemoveSortCore()
MyBase.RemoveSortCore()
End Sub
End Class
Next, if we're going to sort the items in our collection, we need some way to compare them. If the item class is under your control then you can make it implement the IComparable interface and then items can be compared directly. That's not much good if we want to sort by different properties at different times though. In that case we need to define a new class that implements the IComparer interface. It does much the same job as IComparable but from outside the objects instead of from inside.
Data-binding makes heavy use of PropertyDescriptors. As the name suggests, A PropertyDescriptor is an object that describes a property, which is why only properties can be bound and not fields. As such, our IComparer implementation should also be based on PropertyDescriptors:
vb.net Code:
Private Class PersonComparer
Implements System.Collections.Generic.IComparer(Of Person)
Private prop As PropertyDescriptor
Private direction As ListSortDirection
Public Function Compare(ByVal x As Person, _
ByVal y As Person) As Integer Implements IComparer(Of Person).Compare
'Get a value that indicates the relative positions of the values of the specified property.
Dim result As Integer = DirectCast(Me.prop.GetValue(x), IComparable).CompareTo(Me.prop.GetValue(y))
'If the sort order is descending...
If Me.direction = ListSortDirection.Descending Then
'...reverse the relative positions.
result = -result
End If
Return result
End Function
Public Sub New(ByVal prop As PropertyDescriptor, ByVal direction As ListSortDirection)
Me.prop = prop
Me.direction = direction
End Sub
End Class
Note that this class is declared Private because, in the example, I've declared it inside the PersonCollection class. That's the only place it gets used so it makes sense.
Now, how does this class work? You create an instance by specifying the property you want to compare by, as a PropertyDescriptor, and a sort direction. Obviously the relative positions of the two objects will be reversed if the sort direction is reversed. You can pass any two Person objects to this instance's Compare method and it will provide a value that indicates their relative order.
Notice that I cast the first property value as type IComparable, which is done to access its CompareTo method in order to compare it to the other property value. This requires that the type of the property actually does implement IComparable. This will always be the case for primitive types like String and Integer, which are always directly comparable, but will not be the case for more complex types. For instance, you wouldn't sort a collection of DataTables by their Rows properties because it doesn't make sense to compare two DataRowCollections and get a relative order.
Now, when sorting a list of items, such comparisons are performed repeatedly in order to shuffle pairs of items into the correct order until all items are ordered as desired. Our ApplySortCore method must do just that:
vb.net Code:
Protected Overrides Sub ApplySortCore(ByVal prop As PropertyDescriptor, _
ByVal direction As ListSortDirection)
Dim upperBound As Integer = Me.Items.Count - 1
Dim items(upperBound) As Person
Me.Items.CopyTo(items, 0)
Array.Sort(items, _
New PersonComparer(prop, _
direction))
For index As Integer = 0 To upperBound
Me.Items(index) = items(index)
Next
Me.OnListChanged(New ListChangedEventArgs(ListChangedType.Reset, 0))
End Sub
In this method we create an array containing all our items, sort it using an instance of our IComparer, then replace the existing items with this sorted set. They are the same items but in a different order. There may well be more efficient ways to implement the sort but that will do for this example.
Note that this ApplySortCore method is what gets invoked when your collection is bound to a DataGridView and the user clicks a column header. This may seem a little strange because the method is declared Protected, so it should not be accessible outside the class. In fact, the ApplySortCore method is NOT accessible outside the class. ApplySortCore is an explicit implementation of the IBindingList.ApplySort method though. That means that you cannot call ApplySortCore on a PersonCollection object, but if you cast it as type IBindingList and call ApplySort then you will invoke that method. This is exactly what happens when your collection is bound.
This all allows you to sort your collection when bound to your UI. It does make sorting a collection in code somewhat cumbersome though. You'd have to create a PropertyDescriptor, cast the collection as type IBindingList and call ApplySort. To avoid this, I've added a Sort property to the PersonCollection class in the attached project. It works much like the Sort property of the BindingSource and DataView classes, but it only supports one property at a time.
When you run the attached project you'll see a small PersonCollection bound to a DataGridView. Try clicking the column headers and watch the data get sorted. Now try entering a sort clause in the TextBox and clicking the Sort button. You can specify any of the three property names and, optionally, a direction. If the direction is omitted then ascending is assumed. Note that the property name is case sensitive but the direction is not. Examples of valid clauses are "LastName", "FirstName ASC" and "ID DESC".
One final point to note. This implementation is not perfect. For instance, if you sort the collection and then add a new item it will not take into account the current sort order. This may be desirable but, in case it's not, I'll look at fixing that in the next installment. Stay tuned!