65.9K
CodeProject is changing. Read more.
Home

Change individual DataGridView row colors based on column value

starIconstarIconstarIcon
emptyStarIcon
starIcon
emptyStarIcon

3.76/5 (16 votes)

Jan 8, 2010

CPOL
viewsIcon

170123

Below is an example of changing the individual row colors based on one of the DataGridView's columns.While this is not hard to do, the property isn't always where you think it should be, its hidden within the rows DefaultCellStyle property.Here's the example:foreach (DataGridViewRow...

Below is an example of changing the individual row colors based on one of the DataGridView's columns. While this is not hard to do, the property isn't always where you think it should be, its hidden within the rows DefaultCellStyle property. Here's the example:
foreach (DataGridViewRow row in mydataGridView.Rows)
{
    string RowType = row.Cells[0].Value.ToString();

    if (RowType == "Type A")
    {
        row.DefaultCellStyle.BackColor = Color.Red;
        row.DefaultCellStyle.ForeColor = Color.White;
    }
    else if (RowType == "Type B")
    {
        row.DefaultCellStyle.BackColor = Color.Yellow;
        row.DefaultCellStyle.ForeColor = Color.Black;
    }
}
A Good thing to do is add this piece of code in a method like UpdateDataGridViewRowColors() and call it every time your DataGridView is bound or rebound to a piece of data.