Reputation: 811
I have a DataGridView that contains a DataGridViewButtonColumn. I want to change the color of the buttons inside this column. I've set the padding of the buttons inside the cells so that the buttons don't fill the cells. If I use this code:
newRow.Cells["Name"].Style.BackColor = Color.Yellow;
I get that the buttons and the cells are both yellow. I want only the button yellow. I've found on the web that to change the color of the button I should change the Backcolor of my button. I'm not able to retrieve the button from the grid. I've retrieved the cell in this way:
DataGridViewCell dataGridViewCell = newRow.Cells["Name"];
DataGridViewButtonCell dataGridViewButtonCell = dataGridViewCell as DataGridViewButtonCell;
How can I do to retrieve the button? Alternatively in this link Change Color of Button in DataGridView Cell there is a similar question but I'm not able to overraide the Paint method in order to change the backcolor of the button. How can I solve this problem? Thank you
Upvotes: 0
Views: 3793
Reputation: 54453
Here is a simplified way to do the necessary cellpainting. It makes use of the system methods to draw both the Cell's background, which will shine through in the Button and the content, which is the Button and its Text.
The trick is to simply overdraw the outside with four filled rectangles.
private void dataGridView1_CellPainting(object sender,
DataGridViewCellPaintingEventArgs e)
{
if (e.CellStyle.BackColor == Color.Yellow)
{
int pl = 12; // padding left & right
int pt = 2; // padding top & bottom
int cw = e.CellBounds.Width;
int ch = e.CellBounds.Height;
int x = e.CellBounds.X;
int y = e.CellBounds.Y;
e.PaintBackground(e.ClipBounds, true);
e.PaintContent(e.CellBounds);
Brush brush = SystemBrushes.Window;
e.Graphics.FillRectangle(brush, x, y, pl + 1 , ch - 1);
e.Graphics.FillRectangle(brush, x + cw - pl - 2, y, pl + 1, ch - 1);
e.Graphics.FillRectangle(brush, x, y, cw -1 , pt + 1 );
e.Graphics.FillRectangle(brush, x, y + ch - pt - 2 , cw -1 , pt + 1 );
e.Handled = true;
}
}
You will want to:
I have assumed your padding is symmetrical..
Here is how it looks here:
Upvotes: 2