C#DataGridView行着色

时间:2016-11-03 12:02:56

标签: c# datagridview colors row cell-formatting

我的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;
        }
}

1 个答案:

答案 0 :(得分:0)

您应该在事件中将背景颜色指定给CellStyle。