更改 DataGridView 中按钮的颜色

Mun*_*she 4 .net c# datagridview winforms datagridviewbuttoncolumn

我已经搜索了很多关于这个问题的答案。这篇文章的答案:更改 DataGridView 单元格按钮的颜色没有回答我的问题,因为它与字体有关。

我尝试了以下方法:

DataGridViewRow r = dataGridView.Rows[0];
r.Cells[1].Style.BackColor = Color.Red;
Run Code Online (Sandbox Code Playgroud)

我也试过:

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

还是无济于事。

我还注释掉了这一行:

// Application.EnableVisualStyles();
Run Code Online (Sandbox Code Playgroud)

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

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

Rez*_*aei 6

更改整个列的背景颜色

作为一个选项,您可以设置to 的FlatStyle属性并将其设置为您想要的颜色:DataGridViewButtonColumnFlatStyle.BackColor

var C1 = new DataGridViewButtonColumn() { Name = "C1" };
C1.FlatStyle = FlatStyle.Flat;
C1.DefaultCellStyle.BackColor = Color.Red;
Run Code Online (Sandbox Code Playgroud)

更改单个单元格的背景颜色

如果要为不同的单元格设置不同的颜色,将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;
Run Code Online (Sandbox Code Playgroud)

如果要有条件地更改单元格的背景颜色,可以在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;
    }
}
Run Code Online (Sandbox Code Playgroud)


Pra*_*nth 5

尝试这个

DataGridViewButtonCell bc = new DataGridViewButtonCell();
bc.FlatStyle = FlatStyle.Flat;
bc.Style.BackColor = Color.AliceBlue;
Run Code Online (Sandbox Code Playgroud)

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

这是一个小示例,其中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);
}
Run Code Online (Sandbox Code Playgroud)

  • .NET 肯定知道如何带来痛苦。为什么他们甚至添加了一个勉强起作用的 DataGridViewButtonColumn 类?现在我必须重写一切。 (2认同)