OnCustomDrawCell

June 18, 2010

Ever need to change the color of a row in a grid? Here’s how to do it (via Spragg).

Double-click on the grid control’s Event tab to create a stub for the OnCustomDrawCell event. Fill that stub with code like the following:

Sub dgServicesCustomDrawCell(Sender, ByRef Node, _
    ByRef Column, IsSelected, IsFocused, ByRef Text, _
    ByRef Color, ByRef Alignment, ByRef Font, _
    ByRef FontColor) 

    Dim sFieldName
    Dim vStatus
    Dim lColumnIndex

    sFieldName = UCase(Column.FieldName)
    ' Field you want to look for

    Select Case sFieldName
        Case "A2_STATUS"   ' ALIAS name of the column in QB
            lColumnIndex = _
                GetColumnIndexByFieldName(dgServices, _
                "A2_STATUS") ' Used so that grid can
                ' be sorted/grouped
            vStatus = Node.Values(lColumnIndex) 
            ' Gets the actual value
    End Select

    If Not IsNull (vStatus) Then 
        ' Ensure you check for Nulls
        Select Case vStatus
                 Case "Open"
                    FontColor = &H00000000  
                    ' in v7.x - you can use enum of
                    ' clBlack, clGreen etc
                 Case "Lost"
                    FontColor = &H000000FF
                 Case "Won"
                    FontColor = &H00800000
                    Font.Bold = True
        End Select
    End If

End Sub

'==========================================================================================
Function GetColumnIndexByFieldName (ByRef Grid, _
    ByVal FieldName)

    Dim i
    Dim lColumnIndex

    lColumnIndex = -1
    For i = 0 To Grid.Columns.Count - 1
        If UCase(Grid.Columns(i).FieldName) = _
          UCase(FieldName) Then
            lColumnIndex = i
            Exit For
        End If
    Next
    GetColumnIndexByFieldName = lColumnIndex

End Function

The OnCustomDrawCell event fires every time the cell calling it is redrawn—when the grid first gets rendered, whenever you mouse-over it, etc.

Bonus: How not to do it.