【问题标题】:Change color of Button in DataGridView更改 DataGridView 中按钮的颜色
【发布时间】:2026-02-21 11:15:01
【问题描述】:

我已经搜索了这个问题的答案。这个帖子的答案:Change Color of Button in DataGridView Cell 没有回答我关于字体的问题。

我尝试了以下方法:

DataGridViewRow r = dataGridView.Rows[0];
r.Cells[1].Style.BackColor = Color.Red;

我也试过了:

DataGridViewButtonColumn btnCOl = new DataGridViewButtonColumn();
btnCOl.FlatStyle = FlatStyle.Popup;
DataGridViewRow r = dataGridView.Rows[0];
r.Cells[1].Style = new DataGridViewCellStyle { BackColor = Color.LightBlue };

还是没用。

我也注释掉了这一行:

// Application.EnableVisualStyles();

如果有人知道如何更改 DataGridViewButtonColumn 中单个按钮的背景颜色,请提供帮助。

编辑: 我想为列中的单元格设置不同的颜色,例如有些是红色的,有些是绿色的。我不想为整列设置颜色。

【问题讨论】:

  • 你可以简单地使用 btnCOl.Style.BackColor = Color.LightBlue;

标签: c# .net winforms datagridview datagridviewbuttoncolumn


【解决方案1】:

改变整列的背景颜色

作为一个选项,您可以将DataGridViewButtonColumnFlatStyle 属性设置为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 事件中执行此操作。

注意

如果您更喜欢Button 的标准外观而不是平面样式,您可以处理CellPaint 事件:

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;
    }
}

【讨论】:

  • Aghael,我只想为列中的不同单元格设置颜色,而不是整个列
  • 确保阅读最后的代码部分,它使您能够使用按钮的标准外观而不是平面样式。还要记住,使用 CellFormatting 事件比 for 循环要好得多。
【解决方案2】:

试试这个

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

您可以将此单元格分配给您需要的行

这是一个小例子,其中 DataGridView dgvSample 已经插入到表单中

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);
}

【讨论】:

  • .NET 肯定知道如何带来痛苦。为什么他们甚至添加了一个几乎没有功能的 DataGridViewButtonColumn 类?现在我必须重写所有内容。
  • 是 bc.DefaultCellStyle.BackColor 而不是 bc.Style.BackColor