DataGridView row's background color is not changing

One of the problems with using either the cellformatting, databindingcomplete or even paint events is that they get fired multiple times. From what I've gathered, there is an issue with the datagridview control in that you cannot change the color of any of the cells until AFTER the form has been shown. Thus methods that run, or events that fire before Shown() is called will not change the color. The events that are sited as the solution to the problem usually work, but since they're called many times, may not be the most efficient answer.

Probably the simplest solution to the issue is to put your code to fill/color your grids in the Shown() method of your form instead of the constructor. Below is a link to a post in the msdn forums that tipped me off to the solution, it's marked as the answer about 3/4 of the way down the page.

MSDN forums post with the Solution


I think the best place would be to set the BackColor in the CellFormatting event of the DataGridView, something on these lines.

private void grid1_CellFormatting(object sender, DataGridViewCellFormattingEventArgs e)
{
    DataGridViewRow row = grid1.Rows[e.RowIndex];// get you required index
    // check the cell value under your specific column and then you can toggle your colors
    row.DefaultCellStyle.BackColor = Color.Green;
}

King_Rob is correct. I had the same issue so I will just post my implementation since the other suggestions here are far from optimal.

Add the events handlers (in designer or constructor):

this.Load += UserControl_Load; // or form or any control that is parent of the datagridview
dataGridView1.VisibleChanged += DataGridView1_VisibleChanged;

In the load event hander method add a flag

private bool _firstLoaded;
private void UserControl_Load(object sender, EventArgs e)
{
    _firstLoaded = true;
}

And finally in the visible event handler method:

private void DataGridView1_VisibleChanged(object sender, EventArgs e)
{
    if (_firstLoaded && dataGridView1.Visible)
    {
        _firstLoaded = false;
        // your code
    }
}