DataGridView更改单元格背景颜色

我有以下代码:

private void dgvStatus_DataBindingComplete(object sender, DataGridViewBindingCompleteEventArgs e) { foreach (DataGridViewRow row in dgvStatus.Rows) { row.Cells[color.Index].Style.BackColor = Color.FromArgb(((GesTest.dsEssais.FMstatusAnomalieRow)row.DataBoundItem).iColor); } } 

我尝试从背景颜色列设置每个单元格的背景颜色。 这不起作用颜色永远不会改变。 知道为什么吗?

我一直在环顾四周,但没有找到任何有用的东西

只需创建一个新的DataGridViewCellStyle对象,设置其背景颜色,然后为其指定单元格的样式:

  DataGridViewCellStyle style = new DataGridViewCellStyle(); style.BackColor = Color.FromArgb(((GesTest.dsEssais.FMstatusAnomalieRow)row.DataBoundItem).iColor); style.ForeColor = Color.Black; row.Cells[color.Index].Style = style; 

我终于成功了。 这里的代码:

 private void dgvStatus_CellFormatting(object sender, DataGridViewCellFormattingEventArgs e) { if (e.ColumnIndex != color.Index) return; e.CellStyle.BackColor = Color.FromArgb(int.Parse(((DataRowView)dgvStatus.Rows[e.RowIndex].DataBoundItem).Row[4].ToString())); } 

如果有人知道这样做更好,请不要犹豫发布。 我愿意接受建议

如果您仍然感兴趣, 为什么这对您起初不起作用:

您没有看到对单元格样式所做的更改的原因是您显示表单之前进行了这些更改,因此它们被忽略。

在这里建议的事件中更改单元格样式将完成这项工作,但它们被多次调用,导致您的样式更改发生的次数超出您的预期,因此效率不高。

要解决此问题,请在显示表单的代码中的点之后更改样式,或者订阅Shown事件,并将更改放在那里(这个事件的调用明显少于建议的其他事件)。

 dataGridView1.Rows[i].Cells[7].Style.BackColor = Color.LightGreen; 
 int rowscount = dataGridView1.Rows.Count; for (int i = 0; i < rowscount; i++) { if (!(dataGridView1.Rows[i].Cells[8].Value == null)) { dataGridView1.Rows[i].Cells[8].Style.BackColor = Color.LightGoldenrodYellow; } } 

尝试以下(在GridView的RowDataBound方法中):

 protected void GridViewUsers_RowDataBound(object sender, GridViewRowEventArgs e) { // this will only change the rows backgound not the column header if (e.Row.RowType == DataControlRowType.DataRow) { e.Row.Cells[0].BackColor = System.Drawing.Color.LightCyan; //first col e.Row.Cells[1].BackColor = System.Drawing.Color.Black; // second col } } 
 protected void grdDataListeDetay_RowDataBound(object sender, GridViewRowEventArgs e) { if (e.Row.RowType == DataControlRowType.DataRow) { if (e.Row.Cells[3].Text != "0") { for (int i = 0; i <= e.Row.Cells.Count - 1; i++) { e.Row.Cells[i].BackColor = System.Drawing.Color.Beige; } } } } 
 dataGridView1[row, col].Style.BackColor = System.Drawing.Color.Red;