Client side sorting with ASP.NET GridView and jQuery TableSorter

UPDATE If you are looking for a more complete solution including filtering, search, paging, and server side sorting, look at my post on using the datatables plugin with ASP.NET.

Doing some quick data prototyping, I employed the use of the ASP.NET GridView to quickly report on my data objects. As is common, the prototypes quickly took on a life of their own and were asked to be matured into a full on reporting application.

For client-side sorting, I have been using the jQuery Tablesorter plugin. To integrate this plugin, you need simply call the initializing function.

  

  $(document).ready( function(){
    $(".tablesorter").tablesorter();
  });

Out of the box, however, the plugin will not work with the <table> node generated by the ASP.NET Gridview. Comparing the generated output from the GridView with the demo table I realized that the vanilla GridView doesn’t generate the <thead> nodes for the table’s header. To get the proper output, the following changes need to be made in the code behind.

...
gv.Datasource = myDataSource;
gv.DataBind();

//Here's the required code to add
gv.UseAccessibleHeader = true;
if (gv.HeaderRow != null)
{
   //This will tell ASP.NET to render the <thead> for the header row 
   //using instead of the simple <tr>
   gv.HeaderRow.TableSection = TableRowSection.TableHeader; 
} 
...