How to sort GridView in Asp.Net?

In this article I will discuss how to sort columns in grid and more. At the end it will help answer some very frequently asked questions like following.

  • How to sort DataGird in ASP.Net?
  • How to sort GridView?
  • How to show sort direction image in column header of GridView or DataGrid?
  • How to keep track of sorting direction and sort expression while sorting GridView?

Along with getting answers to these question I will also discuss some of the issues with implementation of sorting in GridView. And one of the very frequently brought up issue is that SortDirection property of GridViewSortEventArgs is always set to Ascending.

Specifying Sorting Attributes For GridView

To enable sorting for GridView set Sorting attribute for the control to True and if you are specifying event handlers for controls on page itself then set the event handler function for OnSort event of the control. The following code snippet from ASPX page shows how these attributes are set.

<sp:GridView ID="ctlGridView" runat="server" autogeneratecolumns=False 
    OnRowCreated="OnRowCreated" allowpaging="True"
    allowsorting="True" onsorting="OnSort">
        <asp:boundfield datafield="ProductID" sortexpression="ProductID" />
        <asp:boundfield datafield="Name" headertext="Name" sortexpression="Name" />
        <asp:boundfield datafield="ProductNumber" headertext="Product Number" sortexpression="ProductNumber" />

OnSort Event Handler

Now when grid is loaded and user clicks on column header, OnSort event gets fired and your handler will get called. Second parameter for event handler is GridViewSortEventArgs which has two properties that specify sort direction and sort expression for the column which was clicked by user. These properties are SortExpression and SortDirection. Unfortunately in all my attempts I have always seen value of SortDirection property set to Ascending. So only piece of useful information we have is SortExpression. You can use this property for multiple purposes. One basic purpose is to sort the data table with this sort expression. You can append ASC or DESC to sort expression to sort data as per user's click action. And then you can save this sort expression in ViewState to decide if SortDirection needs to be reversed on next click on header. You can compare SortExpression from the event argument with the one stored in ViewState. If they are different that means a new sort command needs to be executed otherwise you simply need to change SortDirection.

Showing Image In Column To Indicate Sort Direction

Displaying an image indicator along side the column header to show sort direction gives a very cleat indication to user about which column is sorted and in what direction. Header is nothing more than a collection of controls. To display an indicator image you simply need to insert appropriate image at desired location. If you look at the image shown at the top of the article, you will notice that "Name" column has been sorted in ascending order an arrow image is shown right next to column header. Following code snippet shows the implementation included in the sample project of this article.

protected void OnSort(object sender, GridViewSortEventArgs e)
    // There seems to be a bug in GridView sorting implementation. Value of
    // SortDirection is always set to "Ascending". Now we will have to play
    // little trick here to switch the direction ourselves.
    if (String.Empty != m_strSortExp)
        if (String.Compare(e.SortExpression, m_strSortExp, true) == 0)
            m_SortDirection = 
                (m_SortDirection == SortDirection.Ascending) ? SortDirection.Descending : SortDirection.Ascending;
    ViewState["_Direction_"] = m_SortDirection;
    ViewState["_SortExp_"] = m_strSortExp = e.SortExpression;
protected void OnRowCreated(object sender, GridViewRowEventArgs e)
    if (e.Row.RowType == DataControlRowType.Header)
        if (String.Empty != m_strSortExp)
void AddSortImage(GridViewRow headerRow)
    Int32 iCol = GetSortColumnIndex(m_strSortExp);
    if (-1 == iCol)
    // Create the sorting image based on the sort direction.
    Image sortImage = new Image();
    if (SortDirection.Ascending == m_SortDirection)
        sortImage.ImageUrl = "~/dwn.gif";
        sortImage.AlternateText = "Ascending Order";
        sortImage.ImageUrl = "~/up.gif";
        sortImage.AlternateText = "Descending Order";

    // Add the image to the appropriate header cell.
comments powered by Disqus




7.2 °C / 44.9 °F

weather conditions Clouds

Monthly Posts

Blog Tags