Search code examples
c#datagridviewcolorsrowcell-formatting

C# DataGridView Row Coloring


I'm having an issue with my DataGridView, where I'm using the CellFormatting method to re-color a row based on its contents. This seems to work fine in most cases, until the first row in the DGV returns true - in this case every row in the DGV is colored red.

Here's my code:

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

Edit: Solution:

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

Solution

  • You should assign the backcolor to the CellStyle in the event.