Click here to Skip to main content
15,867,771 members
Articles / Web Development / ASP.NET
Tip/Trick

Sorting a GridView bound to a DataTable

Rate me:
Please Sign up or sign in to vote.
5.00/5 (2 votes)
13 Oct 2011CPOL 29.6K   5   1
How to sor a GridView bound to a DataTable.

  • Step 1: Populate the ViewState with the datasource of the GridView in the !Page.IsPostback event.
  • Step 2: In the GridView, set AllowSorting="true".
  • Step 3: Add sortexpression="ColumnName".
  • Step 4: Handle the OnSorting event of the grid on the server side as follows:
  • C#
    protected void grdRoomTypeMaster_OnSorting(object sender, GridViewSortEventArgs e)
    {
     DataTable dtGridData = ViewState["grdDataSource"] as DataTable;
     DataView dvGridDataView = dtGridData.DefaultView;
     string strSortOrder = "";
     if (ViewState["SortOrder"]==null)
     {
     ViewState["SortOrder"] = "asc";
     }
     if (ViewState["SortOrder"].ToString() == "asc")
     {
     ViewState["SortOrder"] = "desc";
     strSortOrder = "desc";
     }
     else if (ViewState["SortOrder"].ToString() == "desc")
     {
     ViewState["SortOrder"] = "asc";
     strSortOrder = "asc";
     }
     dvGridDataView.Sort = e.SortExpression + " " + strSortOrder;
     dtGridData = dvGridDataView.ToTable();
     
     grdRoomTypeMaster.DataSource = dtGridData;
     grdRoomTypeMaster.DataBind();
    }

License

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


Written By
Web Developer
India India
Software developer by profession, working for a service and product based organisation in India.

Career graph:
Software Programmer since 2002.
Web Developer in ASP.NET since 2004.

Interests:
I love reading the blogs and articles of technology experts. I love codeproject and stackoverflow .

I love to share knowledge and help the programmers. I appreciate if some body corrects my code or my concepts which helps me learn.

Comments and Discussions

 
Questionstep 1:Populate the ViewState with the datasource of the gridview in the !Page.IsPostback event . Pin
Commish1314-Nov-13 4:02
professionalCommish1314-Nov-13 4:02 

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.