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

Step 2: In Gridview set AllowSorting="true"

Step: 3: Add the 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();
}

Thanks Justin for his post and VB.NET code on

http://geekswithblogs.net/phoenix/archive/2009/07/02/gridview-sorting-with-datatables.aspx

Advertisements