简体   繁体   中英

C# Winforms DatagridView conditional color for negative cell in named column

On the web, there are plenty of things and their contrary about the topic.

I have a datagridview and I simply want to apply a green/red forecolor in function of the cell's value of a particular column called "YTD". Here is my code:

dataGridViewEquity.Columns["YTD"].DefaultCellStyle.Format = "[Green]0.00;[Red]-0.00;[Blue]zero";

UPDATE

Here is the first part of the Event handler I'm trying to build:

public void DataGridViewEquity_CellFormatting(object sender,DataGridViewCellFormattingEventArgs e)
    {

        if (dataGridViewEquity.Columns[e.ColumnIndex].Name.Equals("YTD"))
        {
            Decimal intValue;
            if (intValue < 0)
            {
                e.CellStyle.ForeColor = Color.Red;
            }
        }

    }

output:

[Red]-3,90

instead of -3,90 in red

Try like this:

You have to add some checks:

  • The current Row Index is >= 0 and is not [DataGridView].NewRowIndex : you get an exceptions if you try to set a Cell value when these conditions are not met (the Row Index check here may not be needed, let's add it anyway).

  • Since you have a DataSource, also check for both null and DBNull.Value : you get an exception if you try to cast the Cell value in this case (and of course there's nothing to format).


private void DataGridViewEquity_CellFormatting(object sender, DataGridViewCellFormattingEventArgs  e)
{
    var dgv = sender as DataGridView;
    if (e.RowIndex < 0 || e.RowIndex == dgv.NewRowIndex) return;

    var cell = dgv["YTD", e.RowIndex];
    if (cell.Value == null || cell.Value == DBNull.Value) return;

    decimal value = (decimal)cell.Value;
    cell.Style.ForeColor = value == 0 ? Color.Blue : value < 0 ? Color.Red : Color.Green;
}

If the Cell's Value is numeric, you could also write:

var value = (dynamic)cell.Value;

You should also set the Format of the YTD Column to 2 decimal places, in case you haven't done this yet. Add this right after the DataGridViewEquity.DataSource has been set:

DataGridViewEquity.Columns["YTD"].DefaultCellStyle.Format = "N2";

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM