css toolkit adapters- apply css style to gridview row in code (c#) RRS feed

  • Question

  • User1561948904 posted

    I was trying to change the colour of a row in a gridview depending on data contained within using MyGridView_RowDataBound, and found a nice little change to the css adapters to allow this. Thought I should share.

    Add the following code before "return className.Trim();" in the function GetRowClass(GridView gridView, GridViewRow row) in GridViewAdapter.cs. (I keep this in ~/App-Code/Adapters/)

    if ((row.RowState == DataControlRowState.Normal))
    className += row.CssClass; 

    In your gridview css file add the colors you need EG:

    .MyGridViewCSSselectorClass .AspNet-GridView table tbody tr.AspNet-GridView-Red td


    background: Red;


    .MyGridViewCSSselectorClass  .AspNet-GridView table tbody tr.AspNet-GridView-Green td


    background: Green;


    In your web page create a RowDataBound function. To over ride the alternate row style change the row state to normal on every row you wish to change, EG:

    protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e) 
    if (e.Row.RowType == DataControlRowType.DataRow)
    foreach (Row in the gridview)
    e.Row.RowState = DataControlRowState.Normal;
    if (somethingIsTrue)
    e.Row.CssClass = "AspNet-GridView-Red"; 
    else if (somethingElseIsTrue)
    e.Row.CssClass = "AspNet-GridView-Green";
    catch (Exception ex)
    throw ex;

    hope this makes sense!

    Wednesday, November 21, 2007 7:34 AM

All replies

  • User-1015649212 posted

    Nice.  One suggestion would be to provide semantic names rather than visual names, for instance


    This helps in the situation where someone decides they want non-error rows gray and error rows yellow.  Then you don't end up with this in your CSS file:

    tr.AspNet-GridView-Red td: { color: yellow; }
    tr.AspNet-GridView-Green td: { color: gray; }

    Just a thought.  I've seen this happen.  :-)


    Friday, December 14, 2007 3:45 PM
  • User1561948904 posted

    Yes good point.

    Colours should be assigned in the CSS not in the code. To further your point if another programmer creates another gridview he/she would have to assign the AspNet-GridView-Red class to colour the row yellow!

    What a mess!!

    Sunday, December 23, 2007 1:46 PM
  • User-2097060974 posted

    Error when attempting this:

    foreach statement cannot operate on variables of type 'System.Web.UI.WebControls.GridView' because 'System.Web.UI.WebControls.GridView' does not have a public definition for 'GetEnumerator'

    Thursday, February 23, 2012 2:58 AM