Rich Text Cell in a DataGridView

I needed to have more dynamic content in a datagridview cell with a custom cell provided to us in VS 2005 and up

. Here is a class I came up with to accomplish this. Hope it helps somebody!

Sample Usage:

Sample usage:
  Private Sub ConfigureGrid()
    Me.gridQuestion.AutoGenerateColumns = False
    Me.gridQuestion.Columns.Clear()
    Dim column As New DataGridViewRichTextColumn()
    column.ReadOnly = True
    column.Width = Me.gridQuestion.ClientSize.Width
    Me.gridQuestion.Columns.Add(column)
  End Sub

—————————-

Imports System.Runtime.InteropServices
Imports System.Drawing.Printing
Imports VB6 = Microsoft.VisualBasic.Compatibility.VB6
Public Class DataGridViewRichTextCell
  Inherits DataGridViewTextBoxCell
  Private m_rtfTemplate As New RichTextBox
  Protected Overrides Sub Paint(ByVal graphics As Graphics, _
  ByVal clipBounds As Rectangle, ByVal cellBounds As Rectangle, _
  ByVal rowIndex As Integer, ByVal cellState As DataGridViewElementStates, _
  ByVal value As Object, ByVal formattedValue As Object, _
  ByVal errorText As String, ByVal cellStyle As DataGridViewCellStyle, _
  ByVal advancedBorderStyle As DataGridViewAdvancedBorderStyle, _
  ByVal paintParts As DataGridViewPaintParts)
    Dim brush As New SolidBrush(cellStyle.BackColor)
    graphics.FillRectangle(brush, cellBounds)
    brush.Dispose()
    ‘ Convert the text to Rtf, and then transfer to the Graphics object.
    Me.PaintRtf(formattedValue, graphics, cellBounds, cellStyle.Font, cellStyle.BackColor)
    ‘ Paint the cell border after everything is done, or it will get
    ‘ overridden.
    MyBase.PaintBorder(graphics, clipBounds, cellBounds, cellStyle, advancedBorderStyle)
  End Sub
  Private Function GetSelectionLink(ByVal charIndex As Integer) As Boolean
    Const SCF_SELECTION As Int32 = &H1
    Const CFE_LINK As Int32 = &H20
    Dim cf As CHARFORMAT2_STRUCT = New CHARFORMAT2_STRUCT
    cf.cbSize = CType(Marshal.SizeOf(cf), UInt32)
    cf.szFaceName = New Char(32) {}
    Dim wParam As IntPtr = New IntPtr(SCF_SELECTION)
    Dim lParam As IntPtr = Marshal.AllocCoTaskMem(Marshal.SizeOf(cf))
    Marshal.StructureToPtr(cf, lParam, False)
    Dim res As IntPtr = SendMessage(m_rtfTemplate.Handle, EM_GETCHARFORMAT, wParam, lParam)
    cf = CType(Marshal.PtrToStructure(lParam, GetType(CHARFORMAT2_STRUCT)), CHARFORMAT2_STRUCT)
    Marshal.FreeCoTaskMem(lParam)
    Return (cf.dwEffects And CFE_LINK)
  End Function
  Public Overrides ReadOnly Property DefaultNewRowValue() As Object
    Get
      ‘ Use the current date and time as the default value.
      Return String.Empty
    End Get
  End Property
#Region "PaintRtf"
  <StructLayout(LayoutKind.Sequential)> _
  Private Structure CHARFORMAT2_STRUCT
    Public cbSize As UInt32
    Public dwMask As UInt32
    Public dwEffects As UInt32
    Public yHeight As Int32
    Public yOffset As Int32
    Public crTextColor As Int32
    Public bCharSet As Byte
    Public bPitchAndFamily As Byte
    <MarshalAs(UnmanagedType.ByValArray, SizeConst:=32)> _
    Public szFaceName As Char()
    Public wWeight As UInt16
    Public sSpacing As UInt16
    Public crBackColor As Integer
    Public lcid As Integer
    Public dwReserved As Integer
    Public sStyle As Int16
    Public wKerning As Int16
    Public bUnderlineType As Byte
    Public bAnimation As Byte
    Public bRevAuthor As Byte
    Public bReserved1 As Byte
  End Structure
  <StructLayout(LayoutKind.Sequential)> _
  Private Structure RECT
    Public Left As Integer
    Public Top As Integer
    Public Right As Integer
    Public Bottom As Integer
  End Structure
  <StructLayout(LayoutKind.Sequential)> _
  Private Structure CHARRANGE
    Public cpMin As Integer           ‘ First character of range (0 for start of doc)
    Public cpMax As Integer           ‘ Last character of range (-1 for end of doc)
  End Structure
  <StructLayout(LayoutKind.Sequential)> _
  Private Structure FORMATRANGE
    Public hdc As IntPtr             ‘ Actual DC to draw on
    Public hdcTarget As IntPtr       ‘ Target DC for determining text formatting
    Public rc As RECT                 ‘ Region of the DC to draw to (in twips)
    Public rcPage As RECT             ‘ Region of the whole DC (page size) (in twips)
    Public chrg As CHARRANGE         ‘ Range of text to draw (see above declaration)
  End Structure
  Private Const WM_USER As Int32 = &H400
  Private Const EM_FORMATRANGE As Int32 = WM_USER + 57
  Private Const EM_GETCHARFORMAT As Int32 = (WM_USER + 58)
  Private Declare Function SendMessage Lib "USER32" Alias "SendMessageA" _
   (ByVal hWnd As IntPtr, ByVal msg As Int32, ByVal wparam As IntPtr, _
   ByVal lparam As IntPtr) As IntPtr
  ‘ Render the contents of the RichTextBox for printing
  ‘  Return the last character printed + 1 (printing start from this point for next page)
  Private Sub PaintRtf(ByVal value As String, ByVal gr As Graphics, ByVal bounds As Rectangle, ByVal font As Font, ByVal backColor As Color)
    If value Is Nothing Then
      Exit Sub
    End If
    ‘ Use an internal RichTextBox to format the text according to the
    ‘ business rules.
    m_rtfTemplate.Font = font
    m_rtfTemplate.WordWrap = False
    m_rtfTemplate.Text = value
    m_rtfTemplate.BackColor = backColor
    m_rtfTemplate.DetectUrls = True
    ‘ Mark starting and ending character.
    Dim cRange As CHARRANGE
    cRange.cpMin = 0
    cRange.cpMax = value.Length
    ‘ Calculate the area to render and print.  The bounds need to
    ‘ be converted from pixels to twips (1/1440 of an inch).
    Dim rectCell As New RECT
    rectCell.Left = VB6.PixelsToTwipsX(bounds.Left) + 30
    rectCell.Top = VB6.PixelsToTwipsY(bounds.Top) + 30
    rectCell.Right = VB6.PixelsToTwipsX(bounds.Right)
    rectCell.Bottom = VB6.PixelsToTwipsY(bounds.Bottom)
    Dim rectPrint As RECT = rectCell
    ‘ Get the DC for the graphics object.
    Dim hdc As IntPtr = gr.GetHdc()
    ‘ Initialize the FORMATRANGE structure for the EM_FORMATRANGE message.
    Dim fmtRange As FORMATRANGE
    fmtRange.chrg = cRange                  ‘ Indicate character from to character to
    fmtRange.hdc = hdc                      ‘ Use the same DC for measuring and rendering
    fmtRange.hdcTarget = hdc                ‘ Point at printer hDC
    fmtRange.rc = rectPrint                  ‘ Indicate the area on page to print
    fmtRange.rcPage = rectCell              ‘ Indicate whole size of page
    Dim wParam As IntPtr = New IntPtr(1)
    ‘ Pass the FORMATRANGE structure to the lParam handle for the
    ‘ EM_FORMATRANGE message sent to the internal RichTextBox.
    Dim lParam As IntPtr = Marshal.AllocCoTaskMem(Marshal.SizeOf(fmtRange))
    Marshal.StructureToPtr(fmtRange, lParam, False)
    ‘ Tell the RichTextBox to paint on the DC.
    Dim res As IntPtr = SendMessage(m_rtfTemplate.Handle, EM_FORMATRANGE, wParam, lParam)
    ‘ Free the block of memory allocated.
    Marshal.FreeCoTaskMem(lParam)
    ‘ Release the device context handle obtained by a previous call.
    gr.ReleaseHdc(hdc)
  End Sub
#End Region
End Class

Public Class DataGridViewRichTextColumn
  Inherits DataGridViewColumn
  Public Sub New()
    MyBase.New(New DataGridViewRichTextCell)
  End Sub
  Public Overrides Property CellTemplate() As DataGridViewCell
    Get
      Return MyBase.CellTemplate
    End Get
    Set(ByVal value As DataGridViewCell)
      ‘ Ensure that the cell used for the template is a CalendarCell.
      If Not (value Is Nothing) AndAlso _
       Not value.GetType().IsAssignableFrom(GetType(DataGridViewRichTextCell)) _
       Then
        Throw New InvalidCastException("Must be a DataGridViewRichTextCell")
      End If
      MyBase.CellTemplate = value
    End Set
  End Property
End Class

 

About these ads
  1. Leave a comment

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

Follow

Get every new post delivered to your Inbox.

%d bloggers like this: