VB.NET  •  Color a DataGrid Cell

Listing 3. You can customize a DataGrid cell's look by overriding the Paint event to change the values of the cell's background and foreground colors.

Public Class DataGridColoredTextBoxColumn
   Inherits DataGridTextBoxColumn

   Public Sub New(ByVal prop As PropertyDescriptor, _
      ByVal format As String, ByVal isDefault As Boolean)
      MyBase.New(prop, format, isDefault)
   End Sub

   Protected Overloads Overrides Sub Paint(ByVal g As _
      Graphics, ByVal bounds As Rectangle, ByVal source As _
      CurrencyManager, ByVal rowNum As Integer, ByVal _
      backBrush As Brush, ByVal foreBrush As Brush, ByVal _
      alignToRight As Boolean)

      Dim obj As Object

      Try
         obj = Me.GetColumnValueAtRow(source, rowNum)
         If (Not (obj) Is Nothing) Then
            Dim i As Integer
            i = CType(obj, Integer)
            If i < 0 Then
               backBrush = New SolidBrush(Color.Red)
               foreBrush = New SolidBrush(Color.White)
            End If
         End If

      Catch ex As Exception

      Finally
         MyBase.Paint(g, bounds, source, rowNum, backBrush, _
            foreBrush, alignToRight)
      End Try
   End Sub
End Class