更改整个列的背景颜色
作为一个选项,您可以设置to 的FlatStyle属性并将其设置为您想要的颜色:DataGdataridViewButtonColumnFlatStyle.BackColor
var C1 = new DataGridViewButtonColumn() { Name = “C1” };
C1.FlatStyle = FlatStyle.Flat;
C1.DefaultCellStyle.BackColor = Color.Red;
更改单个单元格的背景颜色
如果要为不同的单元格设置不同的颜色,将FlatStyle列或单元格设置为后,将不同的单元格设置为不同的颜色Flat就足够了Style.BackColor:
var cell = ((DataGridViewButtonCell)dataGridView1.Rows[1].Cells[0]);
cell.FlatStyle = FlatStyle.Flat;
dataGridView1.Rows[1].Cells[0].Style.BackColor = Color.Green;
如果要有条件地更改单元格的背景颜色,可以在CellFormatting基于单元格值的事件中进行。
笔记
如果您更喜欢标准外观而Button不是平面样式,您可以处理CellPaint事件:
void dataGridView1_CellPainting(object sender, DataGridViewCellPaintingEventArgs e)
{
if (e.RowIndex < 0 || e.ColumnIndex < 0)
return;
if (e.ColumnIndex == 0) // Also you can check for specific row by e.RowIndex
{
e.Paint(e.CellBounds, DataGridViewPaintParts.All
& ~( DataGridViewPaintParts.ContentForeground));
var r = e.CellBounds;
r.Inflate(-4, -4);
e.Graphics.FillRectangle(Brushes.Red, r);
e.Paint(e.CellBounds, DataGridViewPaintParts.ContentForeground);
e.Handled = true;
}
}