Click here to Skip to main content
15,867,985 members
Articles / Web Development / ASP.NET

Sorting Table Columns with jQuery

Rate me:
Please Sign up or sign in to vote.
4.72/5 (8 votes)
10 Sep 2010CPOL3 min read 97.8K   22   11
This code consists of GridView which shows Employee Name as Column along with some data. Now when user presses sort button, column will be sorted in ascending order along with data.

Background

I always heard about sorting table data and read a lot of articles that explain how to achieve it using jquery. You will also find lots of plugins available for sorting table data like Table sorter, Flexigrid, jqGrid, ExtJs Grid and many more. Along with sorting feature, it also supports many more features like paging, resizable columns, cool themes, search and many more...

But I feel that there must be one more feature in this library to sort table columns so that user will have full flexibility by playing with table arrangement along with column data.

It might be possible that some of the library supports these features or if not, then they are planning to add it in their upcoming releases..

Using the Code

This code consist of GridView which shows Employee Name as Column along with some data. Now when user presses the sort button, column will be sorted in ascending order along with data.

Here, I have tried to achieve these features using some of the jQuery code without the need of any library. The only thing we need here is jQuery library.

Step 1

Add jQuery file Reference inside the <Head> tag of the page.

HTML
<script src="Js/jquery-1.4.2.js" type="text/javascript"></script>

Step 2

Next, we need to drag and drop gridview on the page & set AutoGenerateColumns property to false. Specify the ID of the grid "gvEmployees".

ASP.NET
<asp:GridView ID="gvEmployees" runat="server" AutoGenerateColumns="false" Width="500">
   <Columns>
      <asp:BoundField DataField="Sandeep" HeaderText="Sandeep" />
      <asp:BoundField DataField="Nishar" HeaderText="Nishar" />
      <asp:BoundField DataField="Dharmik" HeaderText="Dharmik" />
      <asp:BoundField DataField="Ravi" HeaderText="Ravi" />
      <asp:BoundField DataField="Jigish" HeaderText="Jigish" />
      <asp:BoundField DataField="Kapil" HeaderText="Kapil" />
   </Columns>
</asp:GridView> 

Step 3

Drag and drop one button on the page and give its ID="btnSortColumn" and Text="Sort Column".

HTML
<asp:Button ID="btnSortColumn" runat="server" Text="Sort Column" />

Step 4

Write jQuery script for the button click event, which will sort table column along with data.

JavaScript
$('#btnSortColumn').click(function() {

            //Get all the rows of employee grid
            var rows = $('#gvEmployees tr');

            //Start sorting column along with data
            rows.eq(0).find('th').sort(function(a, b) {

                return $.text([a]) > $.text([b]) ? 1 : -1;

            }).each(function(new_Index) {

                //Original Index
                var original_Index = $(this).index();

                //Reorder Header Text
                rows.each(function() {
                    var th = $(this).find('th');
                    if (original_Index !== new_Index)
                        th.eq(original_Index).insertAfter(th.eq(new_Index));
                });
                
                //Reorder Column Data
                rows.each(function() {
                    var td = $(this).find('td');
                    if (original_Index !== new_Index)
                        td.eq(original_Index).insertAfter(td.eq(new_Index));
                });

            });
            return false;
        });

The code itself explains a lot of things.

Here 'rows' variable contains a collection of Employee rows. Next, we find out the column name using header tag (th) and call the sort function of JavaScript to call the sorting mechanism.

JavaScript
rows.eq(0).find('th').sort(function(a, b) 
{
    return $.text([a]) > $.text([b]) ? 1 : -1;
})

When such a function is passed into array.sort(), the array elements are sorted based on the relationship between each pair of elements "a" and "b" and the function's return value. The three possible return numbers are: <0 (less than 0), 0, or >0 (greater than 0):

  • Less than 0: Sort "a" to be a lower index than "b"
  • Zero: "a" and "b" should be considered equal, and no sorting performed
  • Greater than 0: Sort "b" to be a lower index than "a"

To sort an array numerically and ascending for example, the body of your function would look like this:

JavaScript
function sortfunction(a, b){
return (a - b) //causes an array to be sorted numerically and ascending
}
JavaScript
th.eq(original_Index).insertAfter(th.eq(new_Index));

will insert every table header element (th) from the original place to the new place.

JavaScript
td.eq(original_Index).insertAfter(td.eq(new_Index));

will insert every table data element (td) from the original place to the new place.

Step 5

Now we are only done with aspx page coding, but what about data filling logic. Here it goes. Call data biding function of the gridview in Page Load event.

C#
protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            BindGridData();
        }
    }

    private void BindGridData()
    {
        DataTable table = new DataTable();
        table.Columns.Add("Sandeep");
        table.Columns.Add("Nishar");
        table.Columns.Add("Dharmik");
        table.Columns.Add("Ravi");
        table.Columns.Add("Jigish");
        table.Columns.Add("Kapil");
        table.Rows.Add("20", "25", "45", "33", "22", "12");
        table.Rows.Add("40", "15", "15", "13", "12", "40");

        gvEmployees.DataSource = table;
        gvEmployees.DataBind();
    }

Here, I have created dynamic datatable and filled some data rather than making database connection & fetch data. But you can do whatever you want to bind grid.

Step 6

Everything is set up, now just press F5 & see the output of the page.

Before Sorting Column

SortingTableColumnsJQuery/Sorttable-1.JPG

After Sorting Column

SortingTableColumnsJQuery/Sorttable-2.JPG

Browser Support

I have tested this code on Firefox 3.6.8 & Internet Explore 8. You can also test it on any browser. I am sure that this code will run on all the latest browsers.

Hope this will help !!!
Jay Ganesh.

References

Readymade Library for Sorting Table Data

History

  • 10th September, 2010: Initial post

License

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


Written By
Technical Lead
India India
I write software using Microsoft web technologies since 2008. I have successfully delivered software products for Fortune 500 companies and startups.

Microsoft Certified Technologies Specialist - Web Applications Development with Microsoft .NET Framework 4.

Awarded as Microsoft Community Contributor of the year 2011.

Received several awards at various forums and my various articles got listed as "Article of the day" at ASP.NET Microsoft Official Website https://www.asp.net/

Visit My Blog:
https://ramanisandeep.wordpress.com/


Area of Expertise:
C#, ASP.NET, Web Services, WCF, ASP.NET MVC, SQL Server, WEB API, AngularJS, jQuery

Comments and Discussions

 
QuestionYou should make it on the page Pin
nuaaydh21-Jan-16 18:52
nuaaydh21-Jan-16 18:52 
I don't think it is useful,You should make it on the page
GeneralMy vote of 5 Pin
Manjunath Shrikantiah21-Mar-12 1:54
Manjunath Shrikantiah21-Mar-12 1:54 
GeneralGood Try.. Keep it up Pin
Hiren solanki10-Sep-10 20:11
Hiren solanki10-Sep-10 20:11 
GeneralRe: Good Try.. Keep it up Pin
Sandeepkumar Ramani12-Sep-10 19:03
Sandeepkumar Ramani12-Sep-10 19:03 
GeneralMy vote of 3 Pin
marisks10-Sep-10 4:17
marisks10-Sep-10 4:17 
GeneralRe: My vote of 3 Pin
Sandeepkumar Ramani12-Sep-10 19:02
Sandeepkumar Ramani12-Sep-10 19:02 
GeneralComposing Mode Pin
Kunal Chowdhury «IN»9-Sep-10 5:30
professionalKunal Chowdhury «IN»9-Sep-10 5:30 
GeneralRe: Composing Mode Pin
Sandeepkumar Ramani9-Sep-10 19:52
Sandeepkumar Ramani9-Sep-10 19:52 
GeneralRe: Composing Mode Pin
Kunal Chowdhury «IN»9-Sep-10 20:00
professionalKunal Chowdhury «IN»9-Sep-10 20:00 
GeneralFormatting... Pin
Sandeep Mewara9-Sep-10 4:00
mveSandeep Mewara9-Sep-10 4:00 
GeneralRe: Formatting... Pin
Sandeepkumar Ramani9-Sep-10 19:51
Sandeepkumar Ramani9-Sep-10 19:51 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.