Code to create Sorting for a GridView in ASP.net in Code Behind?
Step 1: Add the Property in your Class
public string SortField {
get {
return (string) ViewState["_sortField"];
}
set {
ViewState["_sortField"] = value;
}
}
public string SortDir {
get {
return (string) ViewState["_sortDir"];
}
set {
ViewState["_sortDir"] = value;
}
}
setp 2 : Enable the Gridview Sorting using the Events
protected void GridView1_Sorting(object sender, GridViewSortEventArgs e) {
if (e.SortExpression == SortField && SortDir != "desc") {
SortDir = "desc";
}
else {
SortDir = "asc";
}
SortField = e.SortExpression;
DoDataBind();
}
step 3 : Enable the sorting expression in grid
<asp:BoundField DataField="FIRSTNAME" HeaderText="First Name" SortExpression="FIRSTNAME" />
step 4 : Bind the Data source As follows
DataTable dt = yourDataSet.Tables[0];
dt.DefaultView.Sort = SortField + " " + SortDir;
GridView1.DataSource = dt.DefaultView;
GridView1.DataBind();
step 5 : Add the property in Gridview
AllowSorting="true"
Comments
Post a Comment