Sorting a GridView bound to a DataTable
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
, setAllowSorting="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();
}