Click here to Skip to main content
14,304,543 members

Colouring DataGridView Cells According to their Content in WinForms

Rate this:
5.00 (6 votes)
Please Sign up or sign in to vote.
5.00 (6 votes)
23 Apr 2018CPOL
How to colour the individual cells of a DataGridView according to their content. For example, negative values can be Red, positive values Green to show "Up"s and "Down"s more easily.


I have a data analysis tool which displays a fair amount of data; probably too much if I'm honest, but the data view isn't used much and is ordered so the recent stuff is immediately visible. It's just a "quick check" thing to show the details to back up the graphs which show the trends and so forth. Anyway, it was a pain to see quickly any anomalous values, so I thought I'd colour code them - and it's really easy to do.

Using the Code

Just hook up the CellPainting event handler to your DataGridView, and decide on the criteria and colours.

Here, I've used "negative is red", "zero is 'normal', and "positive is green":

/// <summary>
/// Set the cell background colour to make the ups and downs more visible.
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void dgvData_CellPainting(object sender, DataGridViewCellPaintingEventArgs e)
    DataGridView dgv = sender as DataGridView;
    if (dgv != null && e.RowIndex >= 0)
        if (e.ColumnIndex > 0)
            Color c;
            if (e.Value != null && e.Value is Int32)
                int value = (int) e.Value;
                if (value > 0)
                    c = Color.LightGreen;
                else if (value < 0)
                    c = Color.Salmon;
                    c = dgv.DefaultCellStyle.BackColor;
                e.CellStyle.BackColor = c;

And I selected "LightGreen" and "Salmon" as they are more subtle and less intrusive than "vanillaColor.Green and Color.Red. The check for the column index being nonzero just skips a date column which will never be coloured.

The grid view then takes care of itself: if the values change, they are always painted correctly without your code having to be concerned about them - and since they are only checked when they are painted, only the "visible" cells are involved at any time.


  • 2018-04-23: First version
  • 2018-04-23: Minor typos


This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


About the Author

Wales Wales
Born at an early age, he grew older. At the same time, his hair grew longer, and was tied up behind his head.
Has problems spelling the word "the".
Invented the portable cat-flap.
Currently, has not died yet. Or has he?

Comments and Discussions

-- There are no messages in this forum --
Posted 23 Apr 2018

Tagged as


8 bookmarked