How to change the background color of a gridview cell based on a conditional statement?

Well, I obviously didn’t give the correct Google query, otherwise I would have known about it. I hope someone on this forum can help me.

So, I have a datatable that I am adding datareader based rows that get their information from an SQL query executed on the database. So far, so good. Now one of these columns is called “analysis”, and I need its background color to be green if the previous two columns match, and red otherwise.

If I cannot touch the background color, I would like to add a special character, any javascript that is not interpreted as text.

Simply put, I would like css to control the gridview from codebehind. I looked and looked to no avail. I found this guy, but I did not check if his solution worked on the ASP.Net/C# website. Any ideas?

+3
c # css gridview code-behind
Jun 30 '10 at 4:20
source share
2 answers

In the GridView_RowDataBound event, to get the cell that you want to change the background color, set the cell color if your condition is checked.

/// <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 { } } } 
+3
Jun 30 '10 at 4:23
source share
  protected void GVKeywordReport_RowDataBound(object sender, GridViewRowEventArgs e) { if (e.Row.RowType == DataControlRowType.DataRow) { DataRow pr = ((DataRowView)e.Row.DataItem).Row; int oldPos = Convert.ToInt32(pr["oldposition"]); int newPos = Convert.ToInt32(pr["newposition"]); GVKeywordReport.HeaderRow.Cells[3].Text = txtfrmdate.Text; GVKeywordReport.HeaderRow.Cells[4].Text = txtEndDate.Text; GVKeywordReport.HeaderRow.BackColor = ColorTranslator.FromHtml("#B3B300"); e.Row.Cells[0].BackColor = ColorTranslator.FromHtml("#B3B300"); e.Row.Cells[5].BackColor = ColorTranslator.FromHtml("#FFFFFF"); if (oldPos == newPos) { e.Row.BackColor = ColorTranslator.FromHtml("#FF950E"); e.Row.Cells[6].Text = "No Change"; } else if (oldPos > newPos) { e.Row.BackColor = ColorTranslator.FromHtml("#FFFFCC"); e.Row.Cells[6].Text = "Improved"; } else { e.Row.BackColor = ColorTranslator.FromHtml("#FF0000"); e.Row.Cells[6].Text = "Decreased"; } // e.Row.Cells[0].BackColor = ColorTranslator.FromHtml("#7DA647"); } } 
0
Jan 27 '15 at 8:08
source share



All Articles