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":
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 "vanilla
" Color.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