1

In my C# Application I get a DataSet that looks like this:

enter image description here

Then I'm going to create that table in a PDF and I was requeted to paint it just like Excel paints using Color Scale (Conditional Formatting):

enter image description here

I will add foreach DataRow cell a new Column to store the desired color, I just want to know how I can create such scales?

Any clue?

VAAA
  • 14,531
  • 28
  • 130
  • 253

3 Answers3

1

You can use a color picker to get the RGB values of the colors, then you can create that same color using the Color.FromRgb method.

Youssef Lourayad
  • 337
  • 3
  • 14
1

What you are looking for is linear interpolation of colors. Check out this thread for a code example and an explanation of how to do it.

Community
  • 1
  • 1
Timo Salomäki
  • 7,099
  • 3
  • 25
  • 40
1

It can be simplified a bit, but the colors will be very bright and you have to find the highest value in the data before the data binding:

static int maxValue = 2401;

private void dataGridView1_CellPainting(object sender, DataGridViewCellPaintingEventArgs e)
{
    if (e.RowIndex < 0 || e.ColumnIndex < 2) return; // skip header cells, userid and year

    int value = 0;
    var cell = dataGridView1[e.ColumnIndex, e.RowIndex];
    if (!int.TryParse(cell.Value + "", out value)) return; // skip non 

    int red = value *  511 / maxValue;
    int green =  511 - red;

    red = Math.Min(red, 255);
    green = Math.Min(green, 255);

    var color = Color.FromArgb(red, green, 0);
    e.CellStyle.BackColor = color;
}
Slai
  • 22,144
  • 5
  • 45
  • 53