使用数据源时无法更改datagridview单元格颜色

我有一个有趣的问题。 我正在尝试使用数据表作为datagridview的数据源。 我想为表中的一些单元格着色以指示各种事物,但由于某种原因,颜色将不会显示。 因此,以下代码显示了一个未着色的单元格。

dataGridView1.DataSource = table; dataGridView1.Rows[0].Cells[0].Style.BackColor = Color.Yellow; 

我只能在初始表单加载后显示一种颜色(例如在OnClick事件上设置单元格颜色)。 但是,如果我在下面的代码中显式创建视图的行和列,则着色有效。

 foreach (DataColumn col in table.Columns) dataGridView1.Columns.Add(col.ColumnName, col.ColumnName); for (int i = 0; i < table.Rows.Count; i++) { var row = table.Rows[i]; object[] values = new object[table.Columns.Count]; for (int x = 0; x < table.Columns.Count; x++) values[x] = row[x].ToString(); dataGridView1.Rows.Add(values); } dataGridView1.Rows[0].Cells[0].Style.BackColor = Color.Yellow; 

我不想以这种方式获得代码。 有谁知道这里发生了什么阻止我着色细胞?

如果您尝试在数据绑定完成之前在表单的构造函数中设置单元格颜色,那么单元格的更改不会粘连(不要问我原因,只是其中一个与DataGridView

对此最直接的解决方法是稍后设置颜色 – 通常在DataBindingComplete事件处理程序中:

 void dataGridView1_DataBindingComplete(object sender, DataGridViewBindingCompleteEventArgs e) { dataGridView1.Rows[0].Cells[0].Style.BackColor = Color.Yellow; } 

这适用于网格的静态着色 – 如果您希望颜色根据网格内的更改而更改,则使用CellFormatting事件更改单元格。

这是我最近实施的,我不知道它是否会有所帮助?

 private void dgvOutstandingReports_CellFormatting(object sender, DataGridViewCellFormattingEventArgs e) { int colIndex = e.ColumnIndex; int rowIndex = e.RowIndex; if (rowIndex >= 0 && colIndex >= 0) { DataGridViewRow theRow = dgvOutstandingReports.Rows[rowIndex]; if (theRow.Cells[colIndex].Value.ToString() == "Daily Report") { theRow.DefaultCellStyle.BackColor = Color.LightYellow; } else if (theRow.Cells[colIndex].Value.ToString() == "Monthly Report") { theRow.DefaultCellStyle.BackColor = Color.LightGray; } else if (theRow.Cells[colIndex].Value.ToString() == "SMP Report") { theRow.DefaultCellStyle.BackColor = Color.Snow; } else if (theRow.Cells[colIndex].Value.ToString() == "Weekly Report") { theRow.DefaultCellStyle.BackColor = Color.Pink; } else if (theRow.Cells[colIndex].Value.ToString() == "Hourly Report") { theRow.DefaultCellStyle.BackColor = Color.LightSteelBlue; } } }