Code-Based Filtering in ObjectListView

Posted on December 17, 2006

Note: You can download the complete implementation here.

In previous posts, I presented ObjectListView, my implementation of a DataView-like class for arbitrary business objects. It allows you to bind a DataGridView (and other controls) to an IList of your choice. As an IBindingListView implementation, ObjectListView supports the Filter property, which allows you to filter the underlying list to present only the items that match the filter expression.

The Filter property allows you to specify simple expressions of the form

propertyName op value

such as "CustomerName = 'Jones'" or "LastVisit > 12/1/2006".

This is all well and good, except for properties that don’t lend themselves easily to IComparable-style comparison. How would one compare a byte array in a meaningful way, for example? What if you want to filter on a property type that doesn’t implement IComparable?

To overcome these obstacles, I’ve added the FilterPredicate property to ObjectListView. FilterPredicate is simply a delegate of type ObjectListView.ListItemFilter, which looks like this:

public delegate bool ListItemFilter(object listItem);

The method referred to by the delegate takes a list item, and returns true if the item should be presented, and false if it should not. This allows you to apply a code-based filter very easily:

string[] states = { "WA", "OR", "CA" };
List westernStates = new List();
westernStates.AddRange(states);

view.FilterPredicate = delegate(object listItem)
{
    Customer c = (Customer)listItem;
    return westernStates.Contains(c.Region);
};

The Filter property can still be used as well, if it is more convenient. If both Filter and FilterPredicate are applied, the last one specified wins. To remove a filter, set either Filter or FilterPredicate to null.

Enjoy!


No Replies to "Code-Based Filtering in ObjectListView"


    Got something to say?

    Some html is OK