Click here to Skip to main content
11,925,730 members (62,327 online)
Click here to Skip to main content
Add your own
alternative version

Tagged as


5 bookmarked

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;


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


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.

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 
Could you please display the code for:

step 1:Populate the ViewState with the datasource of the gridview in the !Page.IsPostback event .

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.

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