Background of cell in a DataGridView
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?
You should perform the coloring in the CellPainting
event, rather than CellFormatting
, which is intended for formatting the value of the cell
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();
}
精彩评论