views:

1531

answers:

3

hello, i have a datagridview that is filled by setting its DataSource to a DataBinding.

now i want that certain rows in the datagridview have a different backgroundcolor according to some value in the row itself.

how can i accomplish this easily?

thanks!

+2  A: 

There's a great example here.

The concept is that you subscribe to events from the grid. When a cell is filled, an event is fired and based upon the value you can format the cell etc.

Paul Sasik
A: 

In the CellFormatting event handler of your datagridview you can set the default backcolor for any row you want.

private void MyDataGridView_CellFormatting(object sender, DataGridViewCellFormattingEventArgs e)
    {

        if (e.RowIndex == rowIndexToHighlight)
        {
            e.CellStyle.BackColor = Color.Green;
        }

    }
Mez
-1 because this example has really poor performance implications. If using databinding then the data grid will need to maintain duplicate row records. Psasik's example avoids un-sharing rows.
Kleinux
@Kleinux: That is an interesting comment about maintaining duplicate row records. Could you explain why this is so? Thanks
Andy
If you look in the docs you will there is mention of shared vs unshared rows. The code above forces the grid view to make actual DataGridViewRow records for every row in your data source. These rows are not duplicates in the sense of the cell values, it can still read the data source for that, but they would otherwise not have to exists because of the now required style info. Hopefully I have made my comment a little clearer. This is a good tutorial http://msdn.microsoft.com/en-us/library/ha5xt0d9.aspx
Kleinux
Fair enough, I changed my example.
Mez
Thanks Kleinux, good comment. +1
Andy
A: 

You can use the RowPrePaint to change the color or style of the whole row

Thomas Levesque