Live Chat Icon For mobile
Live Chat Icon

How can I specially color only the currentcell of my readonly datagrid

Platform: WinForms| Category: Datagrid

You can use the first technique listed in this FAQ: How do I color an individual cell depending upon its value or some external method?

The idea is to derive a custom columnstyle. override its Paint method to specially color the background of the currentcell. Also, override the Edit to avoid the current cell becoming active. Below is a code snippet showing how you can do this. You can also download samples(C#, VB).

Public Class DataGridColoredTextBoxColumn
   Inherits DataGridTextBoxColumn
   
   Private column As Integer ’ column where this columnstyle is located...
   Public Sub New()
      column = -2
   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)

    Try
      Dim grid As DataGrid = Me.DataGridTableStyle.DataGrid

      ’first time set the column properly
      If column = -2 Then
        Dim i As Integer
        i = Me.DataGridTableStyle.GridColumnStyles.IndexOf(Me)
        If i > -1 Then
          column = i
        End If
      End If

      If grid.CurrentRowIndex = rowNum And grid.CurrentCell.ColumnNumber = column Then
        backBrush = New LinearGradientBrush(bounds, Color.FromArgb(255, 200, 200), Color.FromArgb(128, 20, 20), LinearGradientMode.BackwardDiagonal)
        foreBrush = New SolidBrush(Color.White)
      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

   Protected Overloads Overrides Sub Edit(ByVal source As System.Windows.Forms.CurrencyManager, ByVal rowNum As Integer, ByVal bounds As System.Drawing.Rectangle, ByVal [readOnly] As Boolean, ByVal instantText As String, ByVal cellIsVisible As Boolean)
      ’do nothing... don’t call the basecalss
   End Sub
End Class

Share with

Related FAQs

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

Please submit your question and answer.