I have searched high and low for an answer to this question.The answer on this post: Change Color of Button in DataGridView Cell does not answer my question as it regards font.
I have tried the following:
DataGridViewRow r = dataGridView.Rows[0];
r.Cells[1].Style.BackColor = Color.Red;
I have also tried:
DataGridViewButtonColumn btnCOl = new DataGridViewButtonColumn();
btnCOl.FlatStyle = FlatStyle.Popup;
DataGridViewRow r = dataGridView.Rows[0];
r.Cells[1].Style = new DataGridViewCellStyle { BackColor = Color.LightBlue };
Still to no avail.
I also commented out this line:
// Application.EnableVisualStyles();
If there is anyone who knows how to change the background color of a single button in a DataGridViewButtonColumn, please help.
EDIT: I want to set different colors for the cells in the column e.g. some will be red while others will be green. I don't want to set the color for the whole column.
Change BackColor of the whole Column
As an option you can set FlatStyle
property of the DataGridViewButtonColumn
to Flat
and set it's Style.BackColor
to the color you want:
var C1 = new DataGridViewButtonColumn() { Name = "C1" };
C1.FlatStyle = FlatStyle.Flat;
C1.DefaultCellStyle.BackColor = Color.Red;
Change BackColor of a Single Cell
If you want to set different colors for different cells, after setting FlatStyle
of column or cell to Flat
, it's enough to set Style.BackColor
of different cells to different colors:
var cell = ((DataGridViewButtonCell)dataGridView1.Rows[1].Cells[0]);
cell.FlatStyle = FlatStyle.Flat;
dataGridView1.Rows[1].Cells[0].Style.BackColor = Color.Green;
If you want to change back color of a cell conditionally, you can do it in a CellFormatting
event based on cell value.
Note
If you prefer standard look and feel of a Button
instead of flat style, you can handle 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;
}
}