Change color datagridviewbutton


Good I'm doing a form in C #. When another window returns a dialog.result.OK I want to change the background color of the% button DataGridView , in this case to green some simple solution?

asked by Daniel Aparicio 10.07.2018 в 13:00

1 answer


According to MSDN (I regret that the MSDN documentation is in English, but I did not get the Spanish version)


When visual styles are enabled, the buttons on a   button column are painted using a ButtonRenderer, and the styles   of cell specified through properties such as DefaultCellStyle   They have no effect.

You have 2 options, one, it would be to eliminate from your Program.cs the line


that would cause a change like

row.Cells[2].Style.BackColor = System.Drawing.Color.Red;

be functional, but the rest would not look the best way, the other option would be to inherit from DataGridViewButtonCell overwriting the Paint() method, you can use the static DrawButton method the class ButtonRenderer to paint the button yourself, that implies, detect and paint what state it is in ( hover , clicked , etc), it is feasible, but it is a GIANT job

However, here I leave a code so you can start

 //Custom ButonCell
 public class MyButtonCell : DataGridViewButtonCell
        protected override void Paint(Graphics graphics, Rectangle clipBounds, Rectangle cellBounds, int rowIndex, DataGridViewElementStates elementState, object value, object formattedValue, string errorText, DataGridViewCellStyle cellStyle, DataGridViewAdvancedBorderStyle advancedBorderStyle, DataGridViewPaintParts paintParts)
            ButtonRenderer.DrawButton(graphics, cellBounds, formattedValue.ToString(), new Font("Comic Sans MS", 9.0f, FontStyle.Bold), true, System.Windows.Forms.VisualStyles.PushButtonState.Default);

This would be a DataGridView test

DataGridViewButtonColumn c = new DataGridViewButtonColumn();
            c.CellTemplate = new MyButtonColumn();
            this.dataGridView1.Rows.Add("Click Me");

What this example does, is to add a button with the Comic Sans MS font, regardless of whether it is in hover , clicked , etc

I clarify, that this answer is based on the BFree response a> in StackOverflow in English

Personal advice for your particular case, I would use DataGridViewImageColumn that has a slightly more user-friendly usability

Greetings and successes!

answered by 10.07.2018 / 13:24