Click here to Skip to main content
Click here to Skip to main content

Tagged as

Sorting a GridView bound to a DataTable

, 13 Oct 2011 CPOL
Rate this:
Please Sign up or sign in to vote.
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:
  • 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)

Share

About the Author

aspnet -i
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 . PinprofessionalMember 1038652614-Nov-13 5:02 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.

| Advertise | Privacy | Terms of Use | Mobile
Web03 | 2.8.141223.1 | Last Updated 13 Oct 2011
Article Copyright 2011 by aspnet -i
Everything else Copyright © CodeProject, 1999-2014
Layout: fixed | fluid