C# .NET - Sorting columns in a grid view in ascending and descending order

Asked By dinesh on 28-Jun-12 02:44 AM
Hi ,

My requirement is i have a gridview in which i am showing some 6 columns such as employee name, id etc. What i have to do is to sort the column in the grid in ascending and descending order. How to add up and down arrow icons beside header text in the grid view and it should work like when i click up icon the column should be sorted in ascending order and when a click down icon it should be sorted in descending order. This should be done using c# code for all columns in the grid seperately.

Thanks ,
Neha Garg replied to dinesh on 28-Jun-12 02:55 AM

Hello Dinesh,


You need to add the OnSorting="GridView1_Sorting"

OnRowDataBound=" GridView1_RowDataBound"


Add the below code:



protected void GridView1_Sorting(object sender, GridViewSortEventArgs e)


        //here dsUsers is the SqlDataSource ID for Binding the GridView


        GridView1.DataSourceID = "dsUsers";






Add the below code in RowDataBound for sorting:



protected void gvCust_RowDataBound(object sender, GridViewRowEventArgs e)



        GridView gridView = (GridView)sender;


        if (gridView.SortExpression.Length > 0)


          int cellIndex = -1;

          foreach (DataControlField field in gridView.Columns)


            if (field.SortExpression == gridView.SortExpression)


              cellIndex = gridView.Columns.IndexOf(field);





          if (cellIndex > -1)


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


              //  this is a header row,

              //  set the sort style

              e.Row.Cells[cellIndex].CssClass +=

                (gridView.SortDirection == SortDirection.Ascending

                ? " sortasc" : " sortdesc");








Raman S V replied to dinesh on 28-Jun-12 03:28 AM
Try the below :

<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False"

        AllowSorting="True" AllowPaging="True" DataSourceID="SqlDataSource1" >


            <asp:BoundField HeaderText="SubMenu" DataField="SubMenu"


            <asp:BoundField HeaderText="Products" DataField="Products"

            SortExpression="Products" />



The sort expression attribute should be used for the columns and Allowsorting property of the grid should be set to true.

Raman S V
dipa ahuja replied to dinesh on 28-Jun-12 04:11 AM
Try this :
protected void Page_Load(object sender, EventArgs e)
  SqlDataAdapter da = new SqlDataAdapter("select * from tabl1", "ConnString");
  //fill the DataSet
  DataSet ds = new DataSet();
  //Create DataView using the data in my DataSet.
  DataView myView = new DataView();
  myView = ds.Tables[0].DefaultView;
  //sort in DESC order with ColumnName
  myView.Sort = "Column1 DESC";
dinesh replied to dipa ahuja on 28-Jun-12 04:19 AM
what i need is all columns sorting in a grid when any column is clicked