Change color of Button in DataGridView

吃可爱长大的小学妹 提交于 2019-12-01 21:15:46

Try This

DataGridViewButtonCell bc = new DataGridViewButtonCell();
bc.FlatStyle = FlatStyle.Flat;
bc.Style.BackColor = Color.AliceBlue;

You can than assign this cell to the row you need

Here is a small example with a DataGridView dgvSample Already inserted in form

for (int i = 0; i <= 10; i++)
{
    DataGridViewRow fr = new DataGridViewRow();
    fr.CreateCells(dgvSample);

    DataGridViewButtonCell bc = new DataGridViewButtonCell();
    bc.FlatStyle = FlatStyle.Flat;

    if (i % 2 == 0)
    {
        bc.Style.BackColor = Color.Red;
    }   
    else
    {
        bc.Style.BackColor = Color.Green;
    }

    fr.Cells[0] = bc;
    dgvSample.Rows.Add(fr);
}

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;
    }
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!