Grid view Sorting In asp .net
Step ONE
Add grid view to your page edit the source code by adding allow sorting true and initiating an event by on sorting
<asp:GridView ID="GridView1" AllowSorting="true" OnSorting="GridView1_Sorting" runat="server">
</asp:GridView>
Step Two
In the code behind page..we need to handle this event "GridView1_Sorting" and the data table binding.
On page load we will bind the datatable with the gridview
dt = Class1.getDataSet().Tables[0]; // here dt is the datatable object declared Globally.
GridView1.DataSource = dt;
GridView1.DataBind();
so now if we run our code the grid view will be visible but no sorting.
Step Three
Next we need to handle the Gridview Sorting Event.
First of all we need to declare one static string SortDirection.
protected void SetSortDirection(string sortDirection)
{
if (sortDirection == "ASC")
{
_sortDirection = "DESC";
}
else
{
_sortDirection = "ASC";
}
}
so the sortDirection is a static string...This function we used to switch between ascendin and descending...
Step 4
protected void GridView1_Sorting(object sender, GridViewSortEventArgs e)
{
SetSortDirection(SortDirection);
if (dt != null)
{
//Sort the data.
dt.DefaultView.Sort = e.SortExpression + " " + _sortDirection;
GridView1.DataSource = dt;
GridView1.DataBind();
SortDireaction = _sortDirection;
}
}
so we have completed our sorting.... sortExpression is nothing but the column name...