# C# Tip : Dynamic DataGridView Row Colors



## Kreij (Jan 21, 2010)

After getting a request to make the ERP program I wrote change a DataGridView row's background color based on values in the row, I thought I would post it here as a tip in case any of you ever had to do this.

There are a few ways of accomplishing this, but the best way I found was to use the DataGridView's RowPrePaint event. It does it's job nicely whenever the rows need to be redrawn.

This code assumes that you have a DataGridView named MyDataGridView, and a checkbox column named "IsColored". 

Create an event handler for the RowPrePaint event, and put your code in there.


```
MYDataGridView.RowPrePaint += 
    [color="Blue"]new[/color] [color="Teal"]DataGridViewRowPrePaintEventHandler[/color](MyDataGridView_RowPrePaint);

[color="Blue"]private void[/color] MyDataGridView_RowPrePaint([color="Blue"]object[/color] sender, 
    [color="Teal"]DataGridViewRowPrePaintEventArgs[/color] e)
{
    [color="Blue"]if[/color](([color="Blue"]bool[/color])MyDataGridView[[color="Red"]"IsColored"[/color], e.RowIndex].Value)
        MyDataGridView.Rows[e.RowIndex].DefaultCellStyle.BackColor = [color="Teal"]Color[/color].Red;
}
```

What the above code does, is prior to painting any row, it checks to see if the "IsColored" column value is true. If so, it sets the background color of all of the cells in the row to the color red.

You can adjust this to check for any value in any column and act accordingly. For instance if you had a column that contained a salary or something, you could change the if statement to read "if (MyDataGridView["Salary"] > 50000)". This would cause the row to highlight on anyone making over 50K. You can also do this based on the values of multiple columns, column values in another DataGridView, or the state or value of any other control on the form.

Well that's my tip for today. I hope someone finds it useful.
Happy Coding!


----------



## carlospc (Feb 1, 2013)

It's amazing that nobody has noticed that there is a bug in this code:



> MyDataGridView.Rows[e.RowIndex.DefaultCellStyle.BackColor = Color.Red;



shoud be:



> MyDataGridView.Rows[e.RowIndex].DefaultCellStyle.BackColor = Color.Red;



Thanks!!


----------



## Kreij (Feb 1, 2013)

A three year old thread brought back to life to fix a typo.
I'm good with that. Original post update, and thanks carlos.


----------

