Click here to Skip to main content
13,255,711 members (70,916 online)
Click here to Skip to main content
Add your own
alternative version

Tagged as

Stats

19.7K views
5 bookmarked
Posted 13 Oct 2011

Sorting a GridView bound to a DataTable

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

Balaji Birajdar (India)
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.

You may also be interested in...

Comments and Discussions

 
Questionstep 1:Populate the ViewState with the datasource of the gridview in the !Page.IsPostback event . Pin
Member 1038652614-Nov-13 5:02
professionalMember 1038652614-Nov-13 5: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.

Permalink | Advertise | Privacy | Terms of Use | Mobile
Web04 | 2.8.171114.1 | Last Updated 13 Oct 2011
Article Copyright 2011 by Balaji Birajdar (India)
Everything else Copyright © CodeProject, 1999-2017
Layout: fixed | fluid