Click here to Skip to main content
6,305,776 members and growing! (17,063 online)
Email Password   helpLost your password?
Web Development » ASP.NET » General     Beginner License: The Code Project Open License (CPOL)

Sortable GridView using jQuery's TableSorter

By Ponnurangam D

A client side sortable grid view using jQuery's plugin Tablesorter
C# (C# 3.0), Javascript, .NET (.NET 2.0, .NET 3.0, .NET 3.5), ASP.NET, Architect, Dev
Posted:8 Oct 2008
Views:14,498
Bookmarked:33 times
Unedited contribution
Announcements
Loading...
 
Search    
Advanced Search
printPrint   Broken Article?Report       add Share
  Discuss Discuss   Recommend Article Email
8 votes for this article.
Popularity: 4.06 Rating: 4.50 out of 5

1

2
1 vote, 12.5%
3
2 votes, 25.0%
4
5 votes, 62.5%
5

Introduction

This article explains how to use jQuery's plugin Tablesorter to implement client side sorting in ASP.Net Gridview. This comes in handy especially when object data source is used with grid view as gridview does not provide sorting out of the box

Implementation

To implement TableSorter, the rendered table should have THEAD in the markup. Gridview does not provide this by default but we could achieve it either by setting appropriate properties or by using a CSS friendly control adapter. We will do it by using the former method.

Sample

Client Side Sort in GridView using jQuery - Table Sorter

You could have a look at it online here http://ponnu.net/TableSorter

Using the code

We should get the table with THEAD tags for the gridview to implement the sorting. So, lets do that

protected void Page_Load(object sender, EventArgs e)
{ 
if (this.gvEmployees.Rows.Count > 0)
{
gvEmployees.UseAccessibleHeader = true;
gvEmployees.HeaderRow.TableSection = TableRowSection.TableHeader;
gvEmployees.FooterRow.TableSection = TableRowSection.TableFooter;
}
}

If you are using grid view in update panel and binding it in a call back, then it's better to put it in gridview's databound event,

protected void gvEmployees_DataBound(object sender, EventArgs e)
{ 
if (this.gvEmployees.Rows.Count > 0)
{
gvEmployees.UseAccessibleHeader = true;
gvEmployees.HeaderRow.TableSection = TableRowSection.TableHeader;
gvEmployees.FooterRow.TableSection = TableRowSection.TableFooter;
}
}

Now download and include the jQuery and TableSorter js files as follows

<script type="text/javascript" src="scripts/jquery-latest.js"></script>
<script type="text/javascript" src="scripts/jquery.tablesorter.js"></script>

Initialize the table for sorting when document is ready using the below code,

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

If you are using update panel, you need to consider using pageLoad function(javascript)

$("#gvEmployees").tablesorter(); 

At this point the sorting should work on client side, Now you would want to set ascending and descending icons for grid headers. You could easily do this by defining these styles in your style sheet.

.headerSortUp
{
background-position:top;
background-repeat: no-repeat;
background-image: url(../images/icons/sort_up.gif);
background-color: #e9e7d7;
}
.headerSortDown
{
background-position:top;
background-repeat: no-repeat;
background-image: url(../images/icons/sort_down.gif);
background-color: #e9e7d7;
}

Or you could use the styles that comes with Tablesorter as follows, just set the gridView cssclassname to tablesorter and include the stylesheet as follows

gvEmployees.CssClass = "tablesorter";
<link rel="stylesheet" type="text/css" href="themes/green/style.css" />

Tablesorter provides lots of config options, here are few important ones,

sortList: [0, 1] -- This instructs to sort by index 0 column in descending order.

dateFormat: "uk" -- if your format is dd/MM/yyyy, it does not seem to work by default for this format.

debug: true -- this options provides you information like how much time it took and how(what type) it considered the columns.

$("#gvEmployees").tablesorter(
{
debug: true, //provides debugging information
sortList: [[0, 1]], //sorts 0th column by descending order
dateFormat: "uk", //sets the date format to dd/MM/yyyy 
});

Now some interesting things, if you have columns that are formatted differently like having a thousand separator. We could use a customParser in this scenario, otherwise the data would be considered string and the sorting would not work as expected.

We should define a customParser with an id and then assign it to a column while initializing tablesorter.

//define a parser
$.tablesorter.addParser(
{
// set a unique id 
id: 'formattedNumbers',
is: function(s) 
{
// return false so this parser is not auto detected 
return false;
},
format: function(s) 
{
// format your data for normalization
return s.replace(/,/g, ''); //removes comma separator from formatted numbers
},
// set type, either numeric or text 
type: 'numeric'
});
//initialize table for sorting
$("#gvEmployees").tablesorter(
{
headers:
{
6: { sorter: 'formattedNumbers' }
}
});

There might be templated columns and checkbox bound fields in the gridview and if we need to do sorting for those columns, we could do so by using textExtraction. textExtraction is similar to customParser but this applies to the whole table and gets node instead of a string for processing. Here is some code that will process templated text columns and checkbox bound columns.

//define a function for extracting text from node
function extractValue(node)
{ 
var children = node.childNodes[0].childNodes.length
if (children == 0) //boundTextField or a templateColumn
{
if (node.childNodes[0].nodeType == 3)//boundTextField
{
return node.childNodes[0].data;
}
else //template column
{
var type = node.childNodes[0].type
switch (type) 
{
case "checkbox":
return node.childNodes[0].checked.toString()
case "radio":
return node.childNodes[0].checked.toString()
case "text":
return node.childNodes[0].value
default: return ""
}
}
}
else //boundCheckboxColumn or a templateLabelColumn
{
if (node.childNodes[0].childNodes[0].nodeType == 3)
{
return node.childNodes[0].childNodes[0].data; 
}
else
{
return node.childNodes[0].childNodes[0].checked.toString();
}
}
}
$("#gvEmployees").tablesorter(
{ 
textExtraction: extractValue
});

This covers most of things that one would do in gridview. The download contains all the above mentioned code.

Lastly I would like to thank John Resig and Christian Bach for providing such a wonderful framework.

Points of Interest

The Tablesorter is very good for the kind of functionality it provides with so much less code & effort. I am sure more and more people would be interested in this and would be using this as Microsoft recently announced it's support to jQuery

It's very simple to create an extended gridview control built with these functionalities. I will leave that to the user.

Feedback

This is my first article in codeproject and I would appreciate everyone's feedback.

History

Keep a running update of any changes or improvements you've made here.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

About the Author

Ponnurangam D


Member

Occupation: Software Developer
Company: GMS Ltd.
Location: United Kingdom United Kingdom

Other popular ASP.NET articles:

Article Top
You must Sign In to use this message board.
FAQ FAQ 
 
Noise Tolerance  Layout  Per page   
 Msgs 1 to 7 of 7 (Total in Forum: 7) (Refresh)FirstPrevNext
AnswerThousand Separator in GridView with IsNumeric function of C# PinmemberNitish.112723:17 4 Nov '08  
GeneralGreat and fast Pinmembercwp4221:29 17 Oct '08  
GeneralRe: Great and fast PinmemberPonnurangam D2:27 18 Oct '08  
GeneralFast sorting but only one page at a time PinmemberMR_SAM_PIPER15:52 14 Oct '08  
GeneralRe: Fast sorting but only one page at a time PinmemberGibbleCH7:34 17 Oct '08  
GeneralNice, and it works with suprisingly little code indeed but... Pinmembertec-goblin4:18 14 Oct '08  
GeneralRe: Nice, and it works with suprisingly little code indeed but... PinmemberPonnurangam D4:40 14 Oct '08  

General General    News News    Question Question    Answer Answer    Joke Joke    Rant Rant    Admin Admin   

PermaLink | Privacy | Terms of Use
Last Updated: 8 Oct 2008
Editor:
Copyright 2008 by Ponnurangam D
Everything else Copyright © CodeProject, 1999-2009
Web17 | Advertise on the Code Project