Sort the ASP.NET GridView Columns using jQuery TableSorter plugin

Continuing my ASP.NET GridView Tips and Tricks series, this post shows how to use a jQuery plugin to sort ASP.NET GridView columns that are bound to custom classes.

Create an ASP.NET website and add a GridView to it. Here I am assuming that we have an Employee class and the GridView is bound to this custom class. See an example here if you are not familiar with binding a GridView to custom classes.

Now download the tablesorter plugin from tablesorter.com and keep it in a Scripts folder. I have also added the jQuery script file but you can always use the jQuery script from the CDN.

The tablesorter plugin requires the THEAD and TBODY tags to work on. The ASP.NET GridView by default, does not generate the <thead>, <tbody> and <tfoot> tags but it does provide a few properties specifically designed for accessibility. Use the following code to make it generate these accessibility tags

protected override void OnPreRender(EventArgs e)
{
base.OnPreRender(e);
if (gvCustom.Rows.Count > 0)
{
//To render header in accessible format
gvCustom.UseAccessibleHeader = true;

//Add the <thead> element
gvCustom.HeaderRow.TableSection = TableRowSection.TableHeader;

//Add the <tfoot> element
gvCustom.FooterRow.TableSection = TableRowSection.TableFooter;

if (gvCustom.TopPagerRow != null)
{
gvCustom.TopPagerRow.TableSection = TableRowSection.TableHeader;
}
if (gvCustom.BottomPagerRow != null)
{
gvCustom.BottomPagerRow.TableSection = TableRowSection.TableFooter;
}
}
}

That’s it. Now add the following code to call the tablesorter plugin on the GridView.

Note: If paging is enabled on the GridView, only the current page will be sorted. Hence turn paging off if you have to use this plugin. This plugin works well for Grid’s with lesser amount of rows.

gridview table sorter

You should now be able to click the header of any column and sort it. See a Live Demo here.

Note: If you want to sort using an Image, check my article ASP.NET GridView Sorting with Image






About The Author

Suprotim Agarwal
Suprotim Agarwal, Developer Technologies MVP (Microsoft Most Valuable Professional) is the founder and contributor for DevCurry, DotNetCurry and SQLServerCurry. He is the Chief Editor of a Developer Magazine called DNC Magazine. He has also authored two Books - 51 Recipes using jQuery with ASP.NET Controls. and The Absolutely Awesome jQuery CookBook.

Follow him on twitter @suprotimagarwal.

4 comments:

Anonymous said...

Good job.

Dali à Hediya said...

can you help me to sort it invertly

Manoj Batra said...

can we do it with double header and if yes then please send me the example or link.

Unknown said...

I applied the code, but it did not effect, my grid is dynamic grid, not a static grid, can u u help me?