Changing a datagridview row color at runtime

Rifu picture Rifu · Jun 15, 2012 · Viewed 11.8k times · Source

I'm inheriting the DataGridView control for a control I'm developing. My goal is to make each row color representing an object State that can change at runtime. My object implements the Observable design pattern. So I decided to develop my own DataGridViewRow class, implementing the Observer pattern and making my row observe the object. In this class, I have this method :

public void UpdateColors(int state)
{
    DefaultCellStyle.BackColor = m_ETBackColors[state];
    DefaultCellStyle.ForeColor = m_ETForeColors[state];
}

I can't observe my object for the moment, so, to test the color changing, I call my UpdateColors method upon selected rows on the SelectionChanged event.

And now is the moment it doesn't work! My previously selected rows stay blue (like when they were selected), cells texts are layered when I scroll. I tried calling DataGridView.Refresh(), but that doesn't work either.

I must add my datagridview is not bound to a datasource : I don't know how many columns I have before runtime, so I feed it by hand.

Can anyone say me what I'm doing wrong?

========== Update ==========

This works :

public void UpdateColors(int state)
{
    DefaultCellStyle.BackColor = System.Drawing.Color.Yellow;
    DefaultCellStyle.ForeColor = System.Drawing.Color.Black;
}

But this doesn't work :

public void UpdateColors(int state)
{
    DefaultCellStyle.BackColor = m_ETBackColors[nEtattech];
    DefaultCellStyle.ForeColor = m_ETForeColors[nEtattech];
}

with :

    System.Drawing.Color[] m_ETBackColors = new System.Drawing.Color[] { };
    System.Drawing.Color[] m_ETForeColors = new System.Drawing.Color[] { };

There is no array overflow : they are constructor parameters.

Answer

Rifu picture Rifu · Jun 18, 2012

Ok, found the mistake. The colors I use were created like that :

System.Drawing.Color.FromArgb(value)

The bad thing is that value is an integer representing a color with alpha set to 0.
Thanks to this post : MSDN social post, I learned that cell styles don't support ARGB colors, unless alpha is set to 255 (they only support RGB colors).

So I ended using this, which works, but there surely is a more elegant way :

System.Drawing.Color.FromArgb(255, System.Drawing.Color.FromArgb(value));