Apply CSS Style to Gridview Sorted Column

20. July 2009
I needed a way to style a column that was being sorted in a gridview.  I see that in .NET 4.0 this is already built in and can be accomplished with a few style tags within the gridview itself.  Since this is not coded in 4.0 and it's coded in 2.0 here is the concept to accomplish this.  You will need the following:

Set your gridview to allow sorting
Set your SortExpressions for your columns in your GridView
Handle the GridView Sorting Method (onsorting)
Handle the RowDataBound method for the gridview
Have two css classes in your style sheet named sortedHeader and sortedHeader
  style these how you please. For me I just changed the background color and color


Note: I am not using any DataSource object to bind the gridview (ObjectdataSource, SQLDataSource, etc...).  I am just using a DataSet I create. Hence why I have to handle the sorting on my own.

I stripped out all of the code on this page and trimmed it down to what you will need to accomplish this.

//variable and property (could probably just be two variables)
int _sortCellIndex = -1; //keep track of sorted column in gvFreeze
private string SortColumn { get; set; }


Page_Init Method

{
    this.SortColumn = "DefaultSortColumnExpression";    

    //any other code
}

Page_PreRender Method

{
     DataView dv = ds.Tables[0].DefaultView;
     dv.Sort = this.SortColumn + " " + ViewState["SortDirection"].ToString();

     GridView1.DataSource = dv;
     GridView1.DataBind();  

}

GridView1_RowDataBound Method

//to handle changing the color of which column is being sorted
if (e.Row.RowType == DataControlRowType.Header)
{
    for (int i = 0; i < e.Row.Cells.Count; i++)
    {
        DataControlFieldHeaderCell obj = (DataControlFieldHeaderCell)e.Row.Cells[i];
       if (!String.IsNullOrEmpty(this.SortColumn) && obj.ContainingField.SortExpression == this.SortColumn)
       {
           obj.Attributes.Add("class", "sortedHeader");
           _sortCellIndex = i;
           break;
       }
    }                  
                
}


if (e.Row.RowType == DataControlRowType.DataRow)
{
    if (_sortCellIndex != -1)
    {
        //to handle changing the color of which column is being sorted
        e.Row.Cells[_sortCellIndex].Attributes.Add("class", "sortedCell");
    }
}


GridView1_Sorting Method

{
     this.SortColumn = e.SortExpression;
     //any other code you may need

}

Good luck!
Digg It!DZone It!StumbleUponTechnoratiRedditDel.icio.usNewsVineFurlBlinkList

ASP.NET

blog comments powered by Disqus