I am trying to change the colour of the row of a gridview depending on a value in one of the cells. However it only partially works. Here is the code:
protected void attn_list_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.Cells[4].Text == "P") //change the colour of rows
{
e.Row.BackColor = Color.FromName("#CCDDCC");
}
else if (e.Row.Cells[4].Text == "L")
{
e.Row.BackColor = Color.FromName("#C5DAFC");
}
else if (e.Row.Cells[4].Text == "E")
{
e.Row.BackColor = Color.FromName("#FFCC66");
}
else if (e.Row.Cells[4].Text == "U")
{
e.Row.BackColor = Color.FromName("FFCECE");
}
else if (e.Row.Cells[4].Text == "N")
{
e.Row.BackColor = Color.FromName("EDC9FF");
}
if (e.Row.Cells[5].Text == "Yes")
{
e.Row.Cells[5].ForeColor = Color.FromKnownColor(KnownColor.Red); //if EL, set colour of font as red
}
}
I tried to test the conditions by putting in System.Diagnostic.Debug.Writeline("A")
into the else if (e.Row.Cells[4].Text=="N")
statement, and turns out it printed "A", meaning it actually met the conditions. Just that I don't know why the colour won't get changed...
Thanks in advance
CodePudding user response:
Well, the more code, the more we glance over it!
so, converting above to this:
if (e.Row.RowType == DataControlRowType.DataRow)
{
string sColor = "";
switch(e.Row.Cells[4].Text)
{
case "P": sColor = "#CCDDCC"; break;
case "L": sColor = "#C5DAFC"; break;
case "E": sColor = "#FFCC66"; break;
case "U": sColor = "FFCC66"; break;
case "N": sColor = "EDC9FF"; break;
}
if (sColor != "")
e.Row.BackColor = Color.FromName(sColor);
if (e.Row.Cells[5].Text == "Yes")
{
e.Row.Cells[5].ForeColor = Color.FromKnownColor(KnownColor.Red); //if EL, set colour of font as red
}
}
Hum, sure looks like you missing the "#" for some of your colors.
Also, note how we check if data bound is actually procssing a data row, the header and other types of "rows" are tossed to that routine, so we should (need) a check for the row type also.
but, so far, it looks like the "# is missing.