4

我一直在搜索这个问题的答案。这篇文章的答案:更改 DataGridView 单元格中按钮的颜色并没有回答我关于字体的问题。

我尝试了以下方法:

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 中单个按钮的背景颜色,请提供帮助。

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

4

2 回答 2

6

更改整列的背景颜色

作为一个选项,您可以设置to的FlatStyle属性并将其设置为您想要的颜色:DataGridViewButtonColumnFlatStyle.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;
    }
}
于 2016-10-27T07:26:40.137 回答
4

试试这个

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);
}
于 2016-10-27T07:38:43.883 回答