• Welcome to TechPowerUp Forums, Guest! Please check out our forum guidelines for info related to our community.

C# Tip : Dynamic DataGridView Row Colors

Kreij

Senior Monkey Moderator
Joined
Feb 6, 2007
Messages
13,817 (2.20/day)
Location
Cheeseland (Wisconsin, USA)
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.

Code:
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! :toast:
 
Last edited:

carlospc

New Member
Joined
Feb 1, 2013
Messages
1 (0.00/day)
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

Senior Monkey Moderator
Joined
Feb 6, 2007
Messages
13,817 (2.20/day)
Location
Cheeseland (Wisconsin, USA)
A three year old thread brought back to life to fix a typo.
I'm good with that. Original post update, and thanks carlos.
 
Top