C#/.NET how to highlight certain rows in DataGridView

12,216

Solution 1

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.

Solution 2

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

Solution 3

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;
        }

    }
Share:
12,216
clamp
Author by

clamp

hello

Updated on June 24, 2022

Comments

  • clamp
    clamp almost 2 years

    I have a DataGridView that is filled by setting its DataSource to a DataBinding.

    Now I want to have certain rows in the DataGridView having different Backgroundcolor according to some value in the row itself.

    How can I possibly accomplish this?

  • Kleinux
    Kleinux over 14 years
    -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.
  • Andy
    Andy over 14 years
    @Kleinux: That is an interesting comment about maintaining duplicate row records. Could you explain why this is so? Thanks
  • Kleinux
    Kleinux over 14 years
    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 msdn.microsoft.com/en-us/library/ha5xt0d9.aspx
  • Mez
    Mez over 14 years
    Fair enough, I changed my example.