Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles / Languages / C#

Colouring DataGridView Cells According to their Content in WinForms

5.00/5 (7 votes)
23 Apr 2018CPOL1 min read 11.2K  
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 Ups and Downs more easily.

Introduction

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":

C#
/// <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;
                    }
                else
                    {
                    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.

History

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

License

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