This Link will help you a lot
http://highoncoding.com/Articles/176_Sorting_GridView_Manually_.aspx[
^]
Add this code to your code
//declare global variables
private const string ASCENDING = " ASC";
private const string DESCENDING = " DESC";
public SortDirection GridViewSortDirection
{
get
{
if (ViewState["sortDirection"] == null)
ViewState["sortDirection"] = SortDirection.Ascending;
return (SortDirection) ViewState["sortDirection"];
}
set { ViewState["sortDirection"] = value; }
}
The GridViewSortDirection is a simple property which returns the new sort direction for the GridView control. Since, the header of the column triggers a postback that is why I am saving the last sort direction into the ViewState object. Once, I know the last direction I can give the user the new sort direction. This means that if the column was sorted in ascending order then the new direction has to be descending.
Now, let's take a look at the GridView_OnSorting event which is fired when you click the header of the column to sort it.
protected void GridView1_Sorting(object sender, GridViewSortEventArgs e)
{
string sortExpression = e.SortExpression;
if (GridViewSortDirection == SortDirection.Ascending)
{
GridViewSortDirection = SortDirection.Descending;
SortGridView(sortExpression, DESCENDING);
}
else
{
GridViewSortDirection = SortDirection.Ascending;
SortGridView(sortExpression, ASCENDING);
}
}
The first line gets the name of the column that is clicked. This means that if you clicked on the CategoryName column the e.SortExpression will contain "CategoryName". The code is pretty simple, I check that if the last sort direction is ascending if so, then I sort the data in descending order and vice versa. The SortGridView method is responsible for the actual sort. Take a look at the SortGridView method given below:
private void SortGridView(string sortExpression,string direction)
{
DataTable dt = GetData().Tables[0];
DataView dv = new DataView(dt);
dv.Sort = sortExpression + direction;
GridView1.DataSource = dv;
GridView1.DataBind();
}