Link to home
Start Free TrialLog in
Avatar of Tom Sage
Tom SageFlag for United States of America

asked on

DataGridView RowPrePaint - Paint rows based on Cell value

How can I color a row based on a cell value on that row using DataGridView RowPrePaint event?

Thank you
Avatar of Birky
Birky
Flag of Australia image

Hi,

I have been doing this in the Datasource Changed sub of a datagrid. I am changing the background color based on the parents value. It shouldnt be hard to convert to what you are after.

Hope this helps
Private Sub dgvNodes_DataSourceChanged(ByVal sender As Object, ByVal e As System.EventArgs) Handles dgvNodes.DataSourceChanged
        ' This changes the colour of a row.
        ' Changes colours when new powersource is used and lightens the colours when they are down the tree from the parent
        Dim CurrentRow As DataGridViewRow
        Dim ParentCell As DataGridViewTextBoxCell
        Dim LightenedColour As Color
        SourceColourIndex = 0
        ' Loops through all the rows in the datagrid
        For Each CurrentRow In dgvNodes.Rows
            ParentCell = dgvNodes(clnNodeFeedsFrom.Index, CurrentRow.Index)
            ' If the current node has no parent then it is a power source
            If ParentCell.Value = "" Then
                ' Assign each cell in that row to one of the colours in the list
                CurrentRow.DefaultCellStyle.BackColor = SourceColourList(SourceColourIndex)
                ' Increment the colour index by one so no two consective rows have the same colour
                SourceColourIndex = SourceColourIndex + 1
                If SourceColourIndex > SourceColourList.Length - 1 Then
                    SourceColourIndex = 0
                End If
            Else
                ' The current row is not a power supply so find its parent and lighten the colour
                LightenedColour = Lighten(FindParentColour(ParentCell.Value))
                ' Assign each cell in that row to the new colour
                CurrentRow.DefaultCellStyle.BackColor = LightenedColour
            End If
        Next
    End Sub

Open in new window

ASKER CERTIFIED SOLUTION
Avatar of mohd_haq
mohd_haq
Flag of India image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of Tom Sage

ASKER

Your example was very helpful.  I was able to make the code in my program work as I wanted.

Thank you !