views:

204

answers:

2

I've been playing around with datagridviews for a bit and a question has came up. -> Doesn't changing a cells background work out of the CellFormatting event. I've tried this:

private void dataGridView1_CellFormatting(object sender, dataGridViewCellFormattingEventArgs e)
{
    if (dataGridView1.Columns[e.ColumnIndex].Name.Equals(dnsList.First<String>()))
    {
        DataGridViewRow row = dataGridView1.Rows[e.RowIndex];
        DataGridViewCell cell = row.Cells[e.ColumnIndex];
        cell.Style.BackColor = Color.FromArgb(194, 235, 211);
    }
}

Which works perfectly, whereas this:

private void ApplyColoring()
{
    if (dataGridView1.DataSource != null)
    {
        foreach (DataGridViewRow dataGridRow in dataGridView1.Rows)
        {
            DataGridViewCell cell = dataGridRow.Cells[dnsList.First<String>()];
            cell.Style.BackColor = Color.FromArgb(194, 235, 211);
        }
    }
}

Debugging tells me everything is sound, null-reference-or-whatever-exception-wise... Any tips?

A: 

I suggest calling your method from grid's DataBindingComplete event. Call from BackgroundWorker is probably too early and DataGridView.Rows are not initialized yet.


private void dataGridView1_DataBindingComplete(object sender, DataGridViewBindingCompleteEventArgs e)
{
      ApplyColoring();
}

Petr Havlicek
Nah, that way it keeps getting triggered 5000million times, I solved it using a delegate :)
Oxymoron
Delegate called from where? Maybe you could edit your answer and explain your solution? :)
Petr Havlicek
A delegate from the RunWorkerCompleted event; this.Invoke((Action)delegate { ApplyColoring(); });
Oxymoron
Interesting. This event is called from the same thread as main form so I see no difference when calling using Invoke.
Petr Havlicek
+1  A: 

You should perform the coloring in the CellPainting event, rather than CellFormatting, which is intended for formatting the value of the cell

Thomas Levesque
Ah, that would be much better indeed :)
Oxymoron