Saturday, 21 August 2010

ASP.NET: Sorting a DataTable

I was pulling out a DataTable from my database and applying some sorting to it in the Stored Procedure, which of course worked as expected.

But I needed the user to be able to pull a row out from a GridView, edit its fields and then reinsert it to the GridView, all the time preserving the sort order.

As usual, I went round the houses looking at all the usual crappy solutions that others who also forget to read the documentation come up with, until I found a simple solution that worked for me:

dataTable.DefaultView.Sort = "date_of_birth asc"


Here's the MSDN documentation.