动态更改datagridview单元格颜色

fif*_*c04 21 c# datagridview dynamic cell backcolor

我有一个填充了数据的dataGridView对象.我想点击一个按钮,让它改变单元格背景的颜色.这就是我现在拥有的

foreach(DataGridViewRow row in dataGridView1.Rows)
{
    foreach(DataGridViewColumn col in dataGridView1.Columns)
    {
            //row.Cells[col.Index].Style.BackColor = Color.Green; //doesn't work
            //col.Cells[row.Index].Style.BackColor = Color.Green; //doesn't work
        dataGridView1[col.Index, row.Index].Style.BackColor = Color.Green; //doesn't work
    }
} 
Run Code Online (Sandbox Code Playgroud)

所有这三个都会导致表格以重叠的方式重新绘制,并且尝试重新调整表格的大小变得一团糟.单击单元格时,值仍然突出显示,背景颜色不会更改.

问:如何在表存在后更改单个单元格的背景颜色?

Ehs*_*san 59

这适合我

dataGridView1.Rows[rowIndex].Cells[columnIndex].Style.BackColor = Color.Red;
Run Code Online (Sandbox Code Playgroud)

  • 如果您在窗体的构造函数中尝试此操作,则它不起作用.不过,它在OnLoad覆盖中对我有用. (4认同)

Pav*_*vel 6

实现您自己的 DataGridViewTextBoxCell 扩展并重写 Paint 方法,如下所示:

class MyDataGridViewTextBoxCell : DataGridViewTextBoxCell
{
    protected override void Paint(Graphics graphics, Rectangle clipBounds, Rectangle cellBounds, int rowIndex,
        DataGridViewElementStates cellState, object value, object formattedValue, string errorText,
        DataGridViewCellStyle cellStyle, DataGridViewAdvancedBorderStyle advancedBorderStyle, DataGridViewPaintParts paintParts)
    {
        if (value != null)
        {
            if ((bool) value)
            {
                cellStyle.BackColor = Color.LightGreen;
            }
            else
            {
                cellStyle.BackColor = Color.OrangeRed;
            }
        }
        base.Paint(graphics, clipBounds, cellBounds, rowIndex, cellState, value,
            formattedValue, errorText, cellStyle, advancedBorderStyle, paintParts);
}
Run Code Online (Sandbox Code Playgroud)

}

然后在代码中将列的 CellTemplate 属性设置为类的实例

columns.Add(new DataGridViewTextBoxColumn() {CellTemplate = new MyDataGridViewTextBoxCell()});
Run Code Online (Sandbox Code Playgroud)