动态更改datagridview单元格颜色

我有一个填充了数据的dataGridView对象。 我想单击一个按钮,让它更改单元格背景的颜色。 这就是我现在拥有的

foreach(DataGridViewRow row in dataGridView1.Rows) { foreach(DataGridViewColumn col in dataGridView1.Columns) { //row.Cells[col.Index].Style.BackColor = Color.Green; //doesn't work //col.Cells[row.Index].Style.BackColor = Color.Green; //doesn't work dataGridView1[col.Index, row.Index].Style.BackColor = Color.Green; //doesn't work } } 

所有这三个都会导致表格以重叠的方式重新绘制,并且尝试重新调整表格的大小变得一团糟。 单击单元格时,值仍然突出显示,背景颜色不会更改。

问:如何在表存在后更改单个单元格的背景颜色?

这对我有用

 dataGridView1.Rows[rowIndex].Cells[columnIndex].Style.BackColor = Color.Red; 

实现自己的DataGridViewTextBoxCell扩展并覆盖Paint方法,如下所示:

 class MyDataGridViewTextBoxCell : DataGridViewTextBoxCell { protected override void Paint(Graphics graphics, Rectangle clipBounds, Rectangle cellBounds, int rowIndex, DataGridViewElementStates cellState, object value, object formattedValue, string errorText, DataGridViewCellStyle cellStyle, DataGridViewAdvancedBorderStyle advancedBorderStyle, DataGridViewPaintParts paintParts) { if (value != null) { if ((bool) value) { cellStyle.BackColor = Color.LightGreen; } else { cellStyle.BackColor = Color.OrangeRed; } } base.Paint(graphics, clipBounds, cellBounds, rowIndex, cellState, value, formattedValue, errorText, cellStyle, advancedBorderStyle, paintParts); } 

}

然后在代码中将列的CellTemplate属性设置为类的实例

 columns.Add(new DataGridViewTextBoxColumn() {CellTemplate = new MyDataGridViewTextBoxCell()}); 

谢谢它的工作

在这里我完成了这个由qty字段为零意味着它显示细胞是红色的

  int count = 0; foreach (DataGridViewRow row in ItemDg.Rows) { int qtyEntered = Convert.ToInt16(row.Cells[1].Value); if (qtyEntered <= 0) { ItemDg[0, count].Style.BackColor = Color.Red;//to color the row ItemDg[1, count].Style.BackColor = Color.Red; ItemDg[0, count].ReadOnly = true;//qty should not be enter for 0 inventory } ItemDg[0, count].Value = "0";//assign a default value to quantity enter count++; } } 

考虑使用DataBindingComplete事件来更新样式。 下一个代码会更改单元格的样式:

  private void Grid_DataBindingComplete(object sender, DataGridViewBindingCompleteEventArgs e) { this.Grid.Rows[2].Cells[1].Style.BackColor = Color.Green; }