动态更改datagridview单元格颜色

时间:2013-07-18 15:40:00

标签: c# dynamic datagridview 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
    }
} 

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

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

5 个答案:

答案 0 :(得分:57)

这对我有用

dataGridView1.Rows[rowIndex].Cells[columnIndex].Style.BackColor = Color.Red;

答案 1 :(得分:3)

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

By.Xpath

}

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

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

答案 2 :(得分:1)

感谢它的工作

这里我通过qty字段完成此操作是零意味着它显示单元格为红色

        int count = 0;

        foreach (DataGridViewRow row in ItemDg.Rows)
        {
            int qtyEntered = Convert.ToInt16(row.Cells[1].Value);
            if (qtyEntered <= 0)
            {
                ItemDg[0, count].Style.BackColor = Color.Red;//to color the row
                ItemDg[1, count].Style.BackColor = Color.Red;

                ItemDg[0, count].ReadOnly = true;//qty should not be enter for 0 inventory                       
            }
            ItemDg[0, count].Value = "0";//assign a default value to quantity enter
            count++;
        }

    }

答案 3 :(得分:1)

如果您希望网格中的每个单元格都具有相同的背景色,则可以执行以下操作:

dataGridView1.DefaultCellStyle.BackColor = Color.Green;

答案 4 :(得分:0)

考虑使用DataBindingComplete事件来更新样式。接下来的代码更改单元格的样式:

    private void Grid_DataBindingComplete(object sender, DataGridViewBindingCompleteEventArgs e)
    {
        this.Grid.Rows[2].Cells[1].Style.BackColor = Color.Green;
    }