Published articles on other web sites*

Published articles on other web sites*

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.

No comments:

Post a Comment

Related Posts Plugin for WordPress, Blogger...