ASP.NET GridView SortedAscendingHeaderStyle does not work

I don't have enough rep to comment on the accepted answer. When I tried applying the solution, it would sort properly, but did not apply the CSS class to what was eventually rendered.

In my case, invoking DataBind() on my grid AFTER sorting my DataSource (List) and assigning it as the grid's DataSource, but BEFORE setting the CssClass did the trick. Figured I'd share in case someone else encountered something similar.


I'm not sure if SortedDescendingHeaderStyle works without code if you're not using an asp:SQLDataSource as your GridView data source. But a little coding can get you there.

You need to apply the CSS style manually to the header cell. You can do it in the Sorting event.

protected void grdProducts_Sorting(object sender, GridViewSortEventArgs e)
{
   if ((string)ViewState["SortColumn"] == e.SortExpression)
   {
      ViewState["SortDirection"] = ((string)ViewState["SortDirection"] == "") ? " DESC" : "";
      grdProducts.HeaderRow.Cells[GetColumnIndex( e.SortExpression )].CssClass = "AscendingHeaderStyle";
   }
   else
   {
      ViewState["SortColumn"] = e.SortExpression;
      ViewState["SortDirection"] = "";
      grdProducts.HeaderRow.Cells[GetColumnIndex( e.SortExpression )].CssClass = "DescendingHeaderStyle";
   }
   BindGrid();
}




private int GetColumnIndex( string SortExpression )
{
    int i = 0;
    foreach( DataControlField c in gvwCustomers.Columns )
    {
        if( c.SortExpression == SortExpression )
            break;
        i++;
    }
    return i;
}