Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Conditional formatting on cell value

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.

like image 637
Jake Avatar asked Apr 18 '11 19:04

Jake


People also ask

Can you use conditional formatting to format a cell based on its value?

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.


2 Answers

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

like image 160
Priyank Avatar answered Sep 22 '22 15:09

Priyank


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;
like image 37
Charles Lambert Avatar answered Sep 23 '22 15:09

Charles Lambert