Live Chat Icon For mobile
Live Chat Icon

How do I color a individual cell depending upon its value or some external method

Platform: WinForms| Category: Datagrid

We give three different methods for doing this.

  • The first one overrides Paint in a derived columnstyle and sets the backcolor there.
  • The second uses a delegate to set the color in the Paint override.
  • The third method adds an event to the derived column style to allow you to set the color in an event handler.
  • Method 1
    You can do this by deriving from DataGridTextBoxColumn and overriding the Paint method to conditionally set the backColor and foreColor. The sample code below colors any cell that starts with a letter higher than ’F’.
    You can download a project (C#, VB) using this class.

    [C#]
      public class DataGridColoredTextBoxColumn : DataGridTextBoxColumn
      {
        protected override void Paint(System.Drawing.Graphics g,
          System.Drawing.Rectangle bounds, System.Windows.Forms.CurrencyManager
          source, int rowNum, System.Drawing.Brush backBrush, System.Drawing.Brush
          foreBrush, bool alignToRight)
        {
          // the idea is to conditionally set the foreBrush and/or backbrush
          // depending upon some criteria on the cell value
          // Here, we color anything that begins with a letter higher than ’F’
            try{
               object o = this.GetColumnValueAtRow(source, rowNum);
               if( o!= null)
               {
                  char c = ((string)o)[0];
                  if( c > ’F’)
                  {
                   // could be as simple as
                   // backBrush = new SolidBrush(Color.Pink);
                   // or something fancier...
                     backBrush = new LinearGradientBrush(bounds,
                        Color.FromArgb(255, 200, 200),
                        Color.FromArgb(128, 20, 20),
                         LinearGradientMode.BackwardDiagonal);
                     foreBrush = new SolidBrush(Color.White);
                  }
               }
            }
            catch(Exception ex){ /* empty catch */ }
            finally{
               // make sure the base class gets called to do the drawing with
               // the possibly changed brushes
               base.Paint(g, bounds, source, rowNum, backBrush, foreBrush, alignToRight);
            }
         }
      }
    
    [VB.NET}
    Public Class DataGridColoredTextBoxColumn
      Inherits DataGridTextBoxColumn
    
      Public Sub New()
      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)
    
      ’ the idea is to conditionally set the foreBrush and/or backbrush
      ’ depending upon some crireria on the cell value
      ’ Here, we color anything that begins with a letter higher than ’F’
      Try
        Dim o As Object
        o = Me.GetColumnValueAtRow(source, rowNum)
        If (Not (o) Is Nothing) Then
          Dim c As Char
          c = CType(o, String).Substring(0, 1)
          If (c > ''F'') Then
             ’ could be as simple as
            ’ backBrush = new SolidBrush(Color.Pink);
            ’ or something fancier...
            backBrush = New LinearGradientBrush(bounds, Color.FromArgb(255, 200, 200), Color.FromArgb(128, 20, 20), LinearGradientMode.BackwardDiagonal)
            foreBrush = New SolidBrush(Color.White)
          End If
        End If
        Catch ex As Exception
          ’ empty catch 
        Finally
          ’ make sure the base class gets called to do the drawing with
           ’ the possibly changed brushes
          MyBase.Paint(g, bounds, source, rowNum, backBrush, foreBrush, alignToRight)
        End Try
    
      End Sub
    End Class
    

    Method 2
    To use some method to provide the cell color, you can use a similar technique as discussed above. But instead of setting the color based on cell value, call a delegate method instead. This delegate can be passed in using the constructor for the custom column style. You can download a sample that shows how this can be done.

    Method 3
    If you want a more flexible solution, you could expose an event as part of your derived columnstyle that fires in the Paint override. This would allow the handler of the event to set the color value depending upon the row and column parameters that are passed as part of the event args. You can download a sample (C#, VB) that implements this technique. The sample actually handles allowing a cell to be editable on a cell by cell basis through an event. This sample colors the back ground of the disabled cell gray. You could modify the eventargs to include a backcolor, and use this event to color cells based on row and column values removing the event call in the Edit override.

    Share with

    Related FAQs

    Couldn't find the FAQs you're looking for?

    Please submit your question and answer.