Display Ascending and Descending Image in Header for Sorting

 

In GridView control we can sort columns ascending and descending, when we click header column. But the problem is that you can’t figure out how the column is sorted.  To give end-users an indication whether column is sorted ascending or descending, it could be useful to add arrows to the columns that will indicate how the column  is sorted.  We can use GridView RowDataBound event to manipulate the header of GridView .  I had added an image next to column when header column has been clicked. The current row’s RowType property is checked to verify that the row is a header row.

Download Source Code here

 

protected void gvSorting_RowDataBound(object sender, GridViewRowEventArgs e)

{

  if (e.Row.RowType == DataControlRowType.Header)

  {

     foreach (TableCell cell in e.Row.Cells)

     {

        LinkButton lbSorting = (LinkButton)cell.Controls[0] as LinkButton ;

        Image sortImage = new Image();

 

        if (lbSorting.Text == gvSorting.SortExpression)

        {

           if (gvSorting.SortDirection == SortDirection.Ascending)

           {

              sortImage.ImageUrl = "Images/asc.gif";

              sortImage.ToolTip = "Ascending Order";

           }

           else

           {

              sortImage.ImageUrl = "Images/desc.gif";

              sortImage.ToolTip = "Descending Order";

           }

           cell.Controls.Add(sortImage);

         }

       }

    }

}

 

The LinkButton that is used to sort the column has the name of the column that should be sorted. The text of link button is the value of the specified SortExpression on a BoundField column, The GridView’s SortDirection property determines whether the sort direction is ascending or descending. Based on the direction, different images are added to the sorted column’s header. When you mouse over an Image, it will display which order image has been sorted, if end-user get confused.

 

Output looks like below check GridView’s header click :-

 

Sorted

 

Hope you like this small trick to show end-user which sorted has been done. Full source code can be downloaded from link mention above.

4 Comments

Comments have been disabled for this content.