Question

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.

Was it helpful?

Solution

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));

OTHER TIPS

use CellFormatting event to do it:

private void dataGridView1_CellFormatting(object sender, DataGridViewCellFormattingEventArgs e)
{
  if (this.dataGridView1.Rows[e.RowIndex].Cells["SomeStuff"].Value.ToString()=="YourCondition")
    this.dataGridView1.Rows[e.RowIndex].DefaultCellStyle.BackColor = Color.Red;
  else
    this.dataGridView1.Rows[e.RowIndex].DefaultCellStyle.BackColor = Color.White;
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top