DataView for objects?

Posted on October 8, 2006

I’ve often wanted something like the DataView for a collection of my own data objects. DataView allows you to present a sorted, filtered subset of the rows in a DataTable, without actually changing the underlying table.  You can bind two DataViews of the same table to two different Windows Forms controls, using a different sort and filter in each.  Very groovy.

Unfortunately, DataView only provides this goodness for the DataTable class.  If your data happens to be in a DataTable, no problem.  The DataTable and containing DataSet are quite powerful.  Nevertheless, there are circumstances that lead me to want a view over arbitrary class objects:

  • Having an existing domain model of classes suitable for data binding.
    Typically, the systems I work with have a well-defined object model, and back-end data is represented in terms strongly-typed objects rather than as data rows.  Why should I have to use up memory to duplicate the data in the form of a DataSet, just so that I can bind it to a control?  There’s also a cost in performance and development time to do this.
  • Data that can’t be represented well in a DataColumn.
    Theoretically, any .NET type can be used in a column of DataRow.  In the DataSet designer, you can enter the name of your own type, and the generated code will properly support it.  I suspect this usage is rare in actual practice, though.  Typically a DataSet is used because it is designed to move data back and forth from a client application to a database.  A user type in a DataColumn would have to map to a UDT in the database, and this requires it’s own special handling. So, it can be done, but if you’re populating a DataRow with your own custom types, it begs the question as to why you’re using a DataRow at all.  Probably because you want to use the DataView.
  • Data that sorts in an unconventional way.
    I recently ran into a case where I was using a DataColumn to represent one of a few discrete text values that needed to be sorted in a special order (not A-Z or Z-A).  What I really wanted to do was have a column of my own type, and use it’s own IComparable implementation.
  • Complex filtering needs.
    I love the RowFilter property of the DataView.  It provides a very generalized set of operators that allow you to create a filter criteria expression. Wonderful. Sometimes I need more, though. I’d like to provide my own filtering predicate in code, rather than using the predefined expression operators.

In my next post, I’ll review the support that .NET already provides for a filtered, sorted view of a custom collection.  Suffice it to say that we have some work to do.


No Replies to "DataView for objects?"


    Got something to say?

    Some html is OK