Winforms 如何更改windows.forms.datagrid中单个单元格的背景色?

Winforms 如何更改windows.forms.datagrid中单个单元格的背景色?,winforms,datagrid,coding-style,cell,Winforms,Datagrid,Coding Style,Cell,我拼命想弄清楚如何在winforms dataGridView中更改单个单元格的背景色。我有两列:如果我更改第二列中的内容,我希望此行第一列中的单元格相应地更改背景 private void dataGridView1_CellPainting(object sender, DataGridViewCellPaintingEventArgs e) { if (e.ColumnIndex != 0 || e.RowIndex == -1) r

我拼命想弄清楚如何在winforms dataGridView中更改单个单元格的背景色。我有两列:如果我更改第二列中的内容,我希望此行第一列中的单元格相应地更改背景

    private void dataGridView1_CellPainting(object sender, DataGridViewCellPaintingEventArgs e)
    {
        if (e.ColumnIndex != 0 || e.RowIndex == -1)
            return;
        if (dataGridView1.Rows[e.RowIndex].Cells[1].Value.ToString() == "Red")
            e.CellStyle.BackColor = Color.Red;
        else
            e.CellStyle.BackColor = Color.White;
    }

    private void dataGridView1_CellValueChanged(object sender, DataGridViewCellEventArgs e)
    {
        if (e.ColumnIndex != 1 || e.RowIndex == -1)
            return;
        // dataGridView1.Rows[e.RowIndex].Cells[0]. ???
    }
如果绘制了第一列中的单元格,则第一个事件处理程序将设置其背景色。如果值发生更改,则第二个事件处理程序应通知第一个单元格进行绘制。如果我更改列宽,它将绘制正确的颜色,因此第一个处理程序将执行此操作。但是如何触发细胞绘画呢


Thanx寻求帮助。

好的,下面是一个糟糕的黑客:

如果我插入

var x = dataGridView1.Columns[0].DefaultCellStyle;
dataGridView1.Columns[0].DefaultCellStyle = null;
dataGridView1.Columns[0].DefaultCellStyle = x;

在CellValueChanged事件处理程序中,将重新绘制整个第一列。所以我的手机也被重新粉刷过。但这不是脏的,不是吗?

您必须创建一个新的单元格样式对象,将其设置为所需的颜色,然后将其应用于当前单元格

私有DataGridViewCellStyle CellStyleGreenBackgnd

CellStyleGreenBackgnd.BackColor=Color.LightGreen


dataGridView.CurrentCell.Style.ApplyStyle(CellStyleGreenBackgnd)

我本以为编辑会触发重新绘制,但如果编辑后未运行该事件,则您应该能够通过以下方式强制解决该问题:

dataGridView1.InvalidateCell(e.RowIndex, 1);
试试这个

dataGridView1.Rows[indexhere].Cells[indexhere].Style.ForeColor = Color.Yellow;

这正是我想要的。塔克斯。