Microsoft Communities

Welcome to WindowsClient.net | Sign in | Join

Here are some frequently asked questions about Windows Forms and their answers.

Windows Forms FAQs

How do I specially color only the current cell of a read-only 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 = DataGridTableStyle.DataGrid

      'first time set the column properly
      If column = -2 Then
        Dim i As Integer
        i = 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 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 base class
  End Sub
End Class

Contributed from George Shepherd's Windows Forms FAQ



Page view counter