65.9K
CodeProject is changing. Read more.
Home

Sorting a GridView bound to a DataTable

starIconstarIconstarIconstarIconstarIcon

5.00/5 (2 votes)

Oct 13, 2011

CPOL
viewsIcon

30391

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();
    }