KnowDotNet

Sort Your Data with the DataView

by William Ryan

It's no secret that I think ADO.NET is one of the coolest things about the .NET framework.  And the more I play with it, the more I love it.  One of my favorite objects is the DataView becuase it allows you to do some really cool things with little or no effort.

Typically, when you query a database, you may include an Order By statment which sorts your data.  However, many times the order you need the data in changes once you have it at the client.  Since ADO.NET holds things in memory via objects like the DataView , there should be an easy way to change that order.  After all, how much sense would it make to make a whole trip to the database, execute a query against it with a different order by clause and bring the EXACT SAME Data back, then throw out the old copy of the data, just to sort it differently?  If there's a better way to needlessly waste resources I don't know of it.

So how do you do it?

Assume that you have a DataTable named dtEmployees which has all of your company's employees in it.  By Defualt, it's returned sorted on employee last name.  Now, you need to have it sorted by DateOfHire.  I'm going to assume that the table is already populated with the default data.  First, create the DataView and in its constructor, pass in the datatable

VB.NET

Dim dvEmpolyees as New DataView(dtEmployees)


C#

DataView dvEmployees = new DataView(dtEmployees);

Next, Sort it by calling the DataView's Sort Property:

VB.NET

dvEmployees.Sort = "DateOfHire"

C#

dvEmployees.Sort = "DateOfHire";

Compare using 2 lines of code with the effort it would take to requery the database and then refill a table?  Few things are so cleear cut.

Now, what if you wanted to sort it by multiple fields, say DateOfHire and Department

VB.NET

dvEmployees.Sort = "DateOfHire, Department"

C#

dvEmployees.Sort = "DataOfHire, Department";

Just as simple, right?

Now, lets say that you wanted DateOfHire sorted by normally, but you wanted department sorted in Descending Order.  Piece of cake.

VB.NET

dvEmployees.Sort = "DateOfHire, Department DESC"

C#

dvEmployees.Sort = "DateOfHire, Department DESC";

There's one other thing you might want to be aware of.  Every now and then, you might be confronted with a case where you have Spaces in your field names or Reserved words.  Typically, the 'correct' approach is to go back and change them in the database ASAP.  There is so much downside to having fields named like this, but I know, there are a lot of people who are in love with their naming conventions even if there's a ridiculously high cost associated with such terrible habits.  Anyway, if you can't change the names of the column, you can use the "[]" to get it to work.

VB.NET

dvEmployees.Sort = "[Date Of Hire], Deparment"

C#

dvEmployees.Sort = "[Date Of Hire], Department"