1. First we need to create two variables in ViewState to store current direction and expression:
<br />
public string CurrentSortExpression<br />
{<br />
get<br />
{<br />
if (ViewState["sortExpression"] != null)<br />
{<br />
return ViewState["sortExpression"].ToString();<br />
}<br />
else<br />
{<br />
ViewState["sortExpression"] = string.Empty;<br />
return string.Empty;<br />
}<br />
}<br />
set<br />
{<br />
ViewState["sortExpression"] = value;<br />
}<br />
}<br />
<br />
public string CurrentSortDirection<br />
{<br />
get<br />
{<br />
if (ViewState["sortDirection"] != null)<br />
{<br />
return ViewState["sortDirection"].ToString();<br />
}<br />
return string.Empty;<br />
}<br />
set<br />
{<br />
ViewState["sortDirection"] = value;<br />
}<br />
}<br />
2. Then we have to implement handler to attach sort icons to header rows:
<br />
protected void GridViewSortImages(object sender, GridViewRowEventArgs e)<br />
{<br />
GridView senderGridView = (GridView)sender;<br />
Literal space = new Literal();<br />
space.Text = " ";<br />
if (e.Row != null && e.Row.RowType == DataControlRowType.Header)<br />
{<br />
for(int i=0;i<gvusers.columns.count;i++)><br />
{<br />
TableCell cell = e.Row.Cells[i];<br />
DataControlField column=gvUsers.Columns[i];<br />
<br />
if (cell.HasControls())<br />
{<br />
LinkButton button = cell.Controls[0] as LinkButton;<br />
if (button != null)<br />
{<br />
Image image = new Image();<br />
image.ImageUrl = "~/AdminUI/Images/icon-sort_default.gif";<br />
if (CurrentSortExpression==column.SortExpression)<br />
{<br />
if (CurrentSortDirection=="asc")<br />
image.ImageUrl = "~/AdminUI/Images/icon-sort1.gif";<br />
else if (CurrentSortDirection=="desc")<br />
image.ImageUrl = "~/AdminUI/Images/icon-sort2.gif";<br />
}<br />
cell.Controls.Add(image);<br />
}<br />
}<br />
}<br />
}<br />
}<br />
3. Farther let's make some logic in Sorting handler for our GridView:
<br />
protected void gvUsers_Sorting(object sender, GridViewSortEventArgs e)<br />
{<br />
if (CurrentSortExpression == e.SortExpression.ToString())<br />
{<br />
if (CurrentSortDirection == "asc")<br />
CurrentSortDirection = "desc";<br />
else<br />
CurrentSortDirection = "asc";<br />
}<br />
else<br />
{<br />
CurrentSortExpression = e.SortExpression.ToString();<br />
CurrentSortDirection = "asc";<br />
}<br />
<br />
BindUsers(0, CurrentSortExpression, (CurrentSortDirection == "asc")?true:false);<br />
}<br />
4. And at last lets use GridViewSortImages in RowCreated event:
<br />
protected void gvUsers_RowCreated(object sender, GridViewRowEventArgs e)<br />
{<br />
GridViewSortImages(sender, e);<br />
}<br />