Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles
(untagged)

Change individual DataGridView row colors based on column value

0.00/5 (No votes)
8 Jan 2010 1  
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:

C#
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.

License

This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here