Click here to Skip to main content
15,883,809 members
Articles / Programming Languages / C#
Tip/Trick

How to Perform Sorting in Gridview in ASP.NET

Rate me:
Please Sign up or sign in to vote.
4.73/5 (19 votes)
6 Oct 2013CPOL2 min read 268.6K   12.3K   14   5
How to perform sorting on Gridview in ASP.NET

Introduction

I will demonstrate one of the ways of performing sorting on gridview.

Drag and drop gridview on your page.

ASP.NET
<asp:GridView ID="GridView1" runat="server"></asp:GridView> 

Set AllowSorting property to true, add OnSorting event to the gridview.

ASP.NET
<asp:GridView ID="GridView1" runat="server" AllowSorting="true" 
      OnSorting="GridView1_Sorting">
</asp:GridView>   

Create data table that you want to assign to the GridView. I am using the following data table to assign to gridview.

Table name: Students

Table columns:

  • Students Name
  • Students Div
  • Student Roll number
  • Student Class

Let assign the Data Table to Gridview. I will not demonstrate any database connectivity code. I will assume that we have connected to the database and fill the data table.

Let's assign to the GridView.

C#
GridView1.DataSource = dataTable;
GridView1.DataBind();

Now the magic begins to sorting the grid.

To do sorting, we just need to know what is the sort expression and sort direction property of the GridViewSortEventArgs.

SortDirection is sort the grid column using ascending and descending order.

SortExpression is nothing but the column name that you need to sort.

dataTable.DefaultView.Sort will sort the data table by assigning sort direction and sort expression to datatable.

C#
dataTable.DefaultView.Sort = e.SortExpression + " " +_sortDirection; 

As we are adding event OnSorting, let's put our sorting logic there.

C#
protected void GridView1_Sorting(object sender, GridViewSortEventArgs e)
{ 
    SetSortDirection(SortDireaction);
    if (dataTable != null)
    {
        //Sort the data.
        dataTable.DefaultView.Sort = e.SortExpression + " " +_sortDirection;
        GridView1.DataSource = dataTable;
        GridView1.DataBind();
        SortDireaction = _sortDirection;
    }
} 
protected void SetSortDirection(string sortDirection)
{
    if (sortDirection == "ASC")
    {
        _sortDirection = "DESC";
    }
    else
    {
        _sortDirection = "ASC";
    }
} 

After sorting the data table, let's assign back to the grid as we have the sorted data table. I have created SetSortDirection function that will accept the previous sort direction that I have sorted in view state and change the ASC to DESC or vice versa.

Let's add ascending and descending image to the column header to indicate column is sorted.

Create Image class object. Assign imageurl property of image class with ascending and descending image while deciding ascending and descending sort order.

C#
Image sortImage = new Image();
protected void SetSortDirection(string sortDirection)
{
    if (sortDirection == "ASC")
    {
        _sortDirection = "DESC";
        sortImage.ImageUrl = "view_sort_ascending.png";
    }
    else
    {
        _sortDirection = "ASC";
        sortImage.ImageUrl = "view_sort_descending.png";
    }
} 

Let's get index position of header cell that we are sorting.

We have sortexpression following code gives you index position of header cell based on sortexpression.

C#
int columnIndex=0;
foreach (DataControlFieldHeaderCell headerCell in GridView1.HeaderRow.Cells)
{
    if (headerCell.ContainingField.SortExpression==e.SortExpression)
    {
        columnIndex = GridView1.HeaderRow.Cells.GetCellIndex(headerCell);
    }
} 

We have index position of header cell on which we are performing sorting.

Let's insert image object in header of sorted column based on index position.

C#
GridView1.HeaderRow.Cells[columnIndex].Controls.Add(sortImage); 

This is our simple sorting demo.

License

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


Written By
Web Developer Lionbridge
India India
Amey K Bhatkar, a “Microsoft .Net” Web Developer.
I am programmer by will and profession.
I have completed my MCA in 2011 and join software industry.
Presently I am working with Lion Bridge Technologies in Mumbai - India

Comments and Discussions

 
QuestionGridView Sorting Pin
cjdg0817-Apr-17 15:38
cjdg0817-Apr-17 15:38 
QuestionMore Easy Way Custom Sorting Pin
Sunil_198825-Nov-16 2:25
Sunil_198825-Nov-16 2:25 
GeneralMy vote of 2 Pin
Labtec__00728-Sep-14 22:03
Labtec__00728-Sep-14 22:03 
QuestionGridView Sorting Using BoundFields Pin
Ranjeet patil28-Aug-14 8:12
Ranjeet patil28-Aug-14 8:12 
Suggestiondon't forget to add an OnSorting= assignment in the HTML Pin
JWSantora12-Jul-14 13:56
JWSantora12-Jul-14 13:56 

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.