I've been researching conditional formatting for GridViews all over the place, but I am new to ASP.Net and having a hard time. This is the code that I've found that makes the most sense to me:
protected void GridviewRowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
int CellValue = Convert.ToInt32(e.Row.Cells[2].Text);
if (CellValue >= 0)
{
e.Row.Cells[2].BackColor = System.Drawing.Color.Green;
}
if (CellValue < 0)
{
e.Row.Cells[2].BackColor = System.Drawing.Color.Red;
}
}
}
The GridView is incredibly simple: a header row and three columns with one row under the header with a currency amount in each column. I just need the data cell on that second row, third column to be green if >=0 and red if <0.
I am getting an incorrect format on the int CellValue = line.
Conditional formatting makes it easy to highlight certain values or make particular cells easy to identify. This changes the appearance of a cell range based on a condition (or criteria). You can use conditional formatting to highlight cells that contain values which meet a certain condition.
Try replacing your int CellValue =
line with below one
int CellValue = Convert.ToInt32(DataBinder.Eval(e.Row.DataItem, "Difference"));
Ref: http://www.johnchapman.name/asp-net-c-change-gridview-cell-background-color-based-on-value/
http://msdn.microsoft.com/en-us/library/4hx47hfe.aspx
I would use int.TryParse instead of Convert.ToInt32, and verify that your text is actually numeric. If it looks correct, a likely candidate is that the text contains spaces.
Since your negative numbers are formatted like so ($1,000.00). Check your string for the existance of parenthesis, and you can format the color based on that
if (e.Row.Cells[2].Text.Contains(")")) {
e.Row.Cells[2].BackColor = System.Drawing.Color.Red;
} else {
e.Row.Cells[2].BackColor = System.Drawing.Color.Green;
}
or better yet
e.Row.Cells[2].BackColor = e.Row.Cells[2].Text.Contains(")") ? System.Drawing.Color.Red : System.Drawing.Color.Green;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With