更改整个列的背景颜色
作为一个选项,您可以设置FlatStyle的财产DataGridViewButtonColumn
to Flat
并设置它的Style.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
基于单元格值的事件。
Note
如果您喜欢标准的外观和感觉Button
而不是平面样式,你可以处理CellPaint
event:
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;
}
}