Click here to Skip to main content
15,884,912 members
Please Sign up or sign in to vote.
4.00/5 (2 votes)
Hello frnds,

am working on asp.net c# and SqlDatabase.

I want to Sort a gridview columns. Total I have 8 columns in my gridview, only i want to sort 6 columns when column header click.

It must sort the column in ascending order when column header clicks.

Please can you help me, how to do this.

Thanks
Posted

ADD SortExpression to the fields you need to sort
for example
ASP.NET
<asp:boundfield datafield="ProductCode" headertext="Product Code" xmlns:asp="#unknown">SortExpression="ProductCode" /></asp:boundfield>

i have taken my gridview id =Productlist
THEN IN C#
C#
//sorting Populate and load GridView on Page_Load Event
       private DataTable BindGridView()
       {

           DataTable dtGrid = new DataTable();
           string strSelect = "YOUR SELECT QUERY";
           OleDbCommand cmd = new OleDbCommand(strSelect, con);
           OleDbDataAdapter dAdapter = new OleDbDataAdapter(cmd);
           dAdapter.Fill(dtGrid);
           return dtGrid;

       }

       //Create Public Property of SortDirection type and store direction in ViewState.
       public SortDirection dir
       {

           get
           {
               if (ViewState["dirState"] == null)
               {

                   ViewState["dirState"] = SortDirection.Ascending;
               }

               return (SortDirection)ViewState["dirState"];

           }
           set
           {
               ViewState["dirState"] = value;
           }

       }
       //Check Gridview's current direction from ViewState and set new sort direction in Sorting Event.

       protected void gvDetails_Sorting(object sender, GridViewSortEventArgs e)
       {

           string sortingDirection = string.Empty;
           if (dir == SortDirection.Ascending)
           {
               dir = SortDirection.Descending;
               sortingDirection = "Desc";
           }

           else
           {
               dir = SortDirection.Ascending;
               sortingDirection = "Asc";
           }
           DataView sortedView = new DataView(BindGridView());
           sortedView.Sort = e.SortExpression + " " + sortingDirection;
           Productlist.DataSource = sortedView;
           Productlist.DataBind();
       }


Happy Coding!!:)
 
Share this answer
 
v2
following Link will Help you to resolve your problem.................


http://msdn.microsoft.com/en-us/library/ms745786.aspx[^]
 
Share this answer
 

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



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900