c# - 更改 DataGridView 中按钮的颜色

标签 c# .net winforms datagridview datagridviewbuttoncolumn

我到处搜索这个问题的答案。这篇文章的答案: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 中单个按钮的背景颜色,请帮忙。

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

最佳答案

改变整列的BackColor

作为一个选项,您可以设置 FlatStyle DataGridViewButtonColumn 的属性(property)至 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;
    }
}

关于c# - 更改 DataGridView 中按钮的颜色,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40278350/

相关文章:

c# - RDLC 表 - 垂直和水平合并单元格

c# - 用户控制允许删除

c# - 消息循环正在阻塞应用程序

c# - 如何在 toolstripbutton 上使用工具提示

c# - 命令行参数参数限制

javascript - AJAX UpdatePanel 回发后滚动到 SharePoint Visual Web 部件上的位置

c# - 如何在 C# 中解密在 Delphi 中加密的字符串

c# - 为什么将更改保存到数据库失败?

c# - TPL 数据流 SendAsync 结果

c# - 桌面上方的 float 图标