Search code examples
c#cssgridviewcode-behind

How can I change the background color of a gridview cell, based on a conditional statement?


Okay I clearly haven't fed google the right query or I would've found out by now. I'm hoping someone on this forum can help me.

So I have a datatable that I'm adding rows to based on a datareader that's getting its info from an sql query executed over a database. So far, so good. Now, one of those columns is called 'analysis', and I need its background color to be green if the preceding two columns are matched, and red otherwise.

If I can't touch the background color, I'd like to insert a special character, any javascript that isn't interpreted as text.

Simply put, I'd like css control over a gridview from codebehind. I've looked and looked to no avail. I found this guy, but I haven't checked if his solution works on an ASP.Net/C# website. Any ideas?


Solution

  • In the GridView_RowDataBound event, get the cell you want to change the back-color, set the color of the cell if your condition is tested true.

    /// <summary>
    /// Handles gridview row data bound event.
    /// </summary>
    /// <param name="sender">Sender Object</param>
    /// <param name="e">Event Argument</param>
    protected void Gv_RowDataBound(object sender, GridViewRowEventArgs e)
    {
        // We don’t want to apply this to headers.
        if (e.Row.RowType == DataControlRowType.DataRow)
        {
            try
            {
                //your data-object that is rendered in this row, if at all required.
                //Object obj = e.Row.DataItem;
    
                //find the right color from condition
                string color = condition ? "#ff9900" : "some-other-color";
    
                //set the backcolor of the cell based on the condition
                e.Row.Cells[4].Attributes.Add("Style", "background-color: " + color + ";");
            }
            catch
            {
            }
        }
    }