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.
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
Tweet
4 comments:
Good job.
can you help me to sort it invertly
can we do it with double header and if yes then please send me the example or link.
I applied the code, but it did not effect, my grid is dynamic grid, not a static grid, can u u help me?
Post a Comment