C# DataGridView Row Coloring

本文关键字:Coloring Row DataGridView | 更新日期: 2023-09-27 18:16:12

我有一个问题与我的DataGridView,在那里我使用CellFormatting方法根据其内容重新着色一行。在大多数情况下,这似乎工作得很好,直到DGV中的第一行返回true -在这种情况下,DGV中的每一行都是红色的。

下面是我的代码:

private void MyData_CellFormatting(object sender, DataGridViewCellFormattingEventArgs e)
{
    DataGridViewRow theRow = MyData.Rows[e.RowIndex];
        if (theRow.Cells[4].Value.ToString() == "1")
        {
            ChangeRowColor(theRow, Color.PaleVioletRed);
        }
}
private void ChangeRowColor(DataGridViewRow r, Color c)
{
    r.DefaultCellStyle.BackColor = c;
}

编辑:解决方案:

private void MyData_CellFormatting(object sender, DataGridViewCellFormattingEventArgs e)
    {
        DataGridViewRow theRow = MyData.Rows[e.RowIndex];
        if ((int)theRow.Cells[4].Value == 1)
        {
            e.CellStyle.BackColor = Color.PaleVioletRed;
        }
}

C# DataGridView Row Coloring

你应该为事件中的CellStyle指定背景色