When using sorting with the ASP.NET gridview, the header cell of a column contains a link (generated internally by .NET using a LinkButton).

Everything else in the gridview is easily styled by readily accessable CssClass tags. This is not quite so easy to accomplish for the sort link in the header of a column.

To acheive this, we need to catch the RowCreated event and manually find the header we are looking for, by comparing the SortExpression of each column’s header link with the SortExpression of the gridview which gets set when you sort the gridview.

Once you have found the LinkButton associated with the column, it is an easy matter to set the class using the LinkButton‘s CssClass property.

protected void GridView1_RowCreated(object sender, GridViewRowEventArgs e)
{
    if (e.Row.RowType == DataControlRowType.Header)
    {
        foreach (TableCell tc in e.Row.Cells)
        {
            if (tc.HasControls())
            {
                LinkButton headerLink = (LinkButton)tc.Controls[0];
                if (GridView1.SortExpression == headerLink.CommandArgument)
                    headerLink.CssClass = "sorted";

                if (SortDirection == SortDirection.Descending)
                    headerLink.CssClass += " desc";
                else
                    headerLink.CssClass += " asc";
            }
        }
    }
}
Share