Solved

DataGridView - Adding Label Controls

Posted on 2006-07-05
15
2,061 Views
Last Modified: 2013-04-11

Good Morning.

I have a DataGridView control on a form and need to do the following...

I have a dataset that I would like to add to the DataGridView, but need to display it with some color coding and boxing.

I would like to add each line of text to a cell as a lable, that way I can set the text color and put a border around the text if I need to.

I basically need this

24
GREG - Out of Office (color=red)
BOB - In Meeting (color=Green)
FRED - PAL Day(Color=blue)(border=1)

Can anyone tell me how to add label controls to a cell in a DataGridView or how to accomplish this another way?
0
Comment
Question by:Rowdyone52
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
  • 8
  • 7
15 Comments
 
LVL 96

Expert Comment

by:Bob Learned
ID: 17043959
You can define a custom cell, like DataGridViewRichTextCell + DataGridViewRichTextColumn.  I have accomplished something like that, but I don't have access to the code here.  Also, it is in a prototype form, so it would be necessary to polish it up some.

Bob
0
 

Author Comment

by:Rowdyone52
ID: 17045362
I would love to see your sample code when you get a chance.
0
 
LVL 96

Expert Comment

by:Bob Learned
ID: 17047210
DataGridViewRichTextCell:

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
0
Salesforce Has Never Been Easier

Improve and reinforce salesforce training & adoption using WalkMe's digital adoption platform. Start saving on costly employee training by creating fast intuitive Walk-Thrus for Salesforce. Claim your Free Account Now

 
LVL 96

Expert Comment

by:Bob Learned
ID: 17047212
DataGridViewRichTextColumn:

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

Bob
0
 
LVL 96

Expert Comment

by:Bob Learned
ID: 17047220
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

Bob
0
 

Author Comment

by:Rowdyone52
ID: 17050020
What dll should I reference in order to be able to import  - Imports VB6 = Microsoft.VisualBasic.Compatibility.VB6
0
 

Author Comment

by:Rowdyone52
ID: 17050061
Nevermind, I got it :)
0
 

Author Comment

by:Rowdyone52
ID: 17050108
OK I have your code working.  I cannot figure out how to change a line of text color, or how to add a border around a line of text.  I have tried several methods.
0
 
LVL 96

Expert Comment

by:Bob Learned
ID: 17051338
The text, in this case, needs to be rich text.  You can use a RichTextBox control to get the right Rtf text, and then set the cell value to that.  To get borders, you can specify a cell border.

Bob
0
 

Author Comment

by:Rowdyone52
ID: 17052621
I tried to set the value and it didnt work correctly.  Could you paste a sample code to achieve...

<GREEN>GREG R</GREEN>NEWLINE
<RED>BOB SMITH</RED>
0
 

Author Comment

by:Rowdyone52
ID: 17052744
"{\\rtf1\\ansi\\ansicpg1252\\deff0\\deflang1033{\\fonttbl{\\f0\\fnil\\fcharset0 Microsoft Sans Serif;}}\r\n{\\colortbl ;\\red0\\green0\\blue255;\\red255\\green255\\blue0;}\r\n\\viewkind4\\uc1\\pard\\f0\\fs17 dude we \\cf1 are\\cf0  \\cf2 working\\cf0\\par\r\n}\r\n"

shows as multicolored in a richtextbox, but doesnt format in the datagridview
0
 
LVL 96

Expert Comment

by:Bob Learned
ID: 17054569
I am going to have to review my code tonight when I get home.

Bob
0
 

Author Comment

by:Rowdyone52
ID: 17054609
Thanks Bob.  From my digging it appears that I need to inherit the RichTextBox control in a way to access the .rtf member, so that I may enter RTF code as above.  Ive tried to do that to no avail, but I'm still working on it.  Any information would be most helpful and I appreciate your time thus far.
0
 
LVL 96

Accepted Solution

by:
Bob Learned earned 500 total points
ID: 17055154
0
 

Author Comment

by:Rowdyone52
ID: 17055471
That is exactly what I needed.  BOB you are the MAN!

I owe you big time.

Thanks for all of your help and patience
0

Featured Post

Free Tool: IP Lookup

Get more info about an IP address or domain name, such as organization, abuse contacts and geolocation.

One of a set of tools we are providing to everyone as a way of saying thank you for being a part of the community.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

For those of you who don't follow the news, or just happen to live under rocks, Microsoft Research released a beta SDK (http://www.microsoft.com/en-us/download/details.aspx?id=27876) for the Xbox 360 Kinect. If you don't know what a Kinect is (http:…
A long time ago (May 2011), I have written an article showing you how to create a DLL using Visual Studio 2005 to be hosted in SQL Server 2005. That was valid at that time and it is still valid if you are still using these versions. You can still re…
How to Install VMware Tools in Red Hat Enterprise Linux 6.4 (RHEL 6.4) Step-by-Step Tutorial
Are you ready to implement Active Directory best practices without reading 300+ pages? You're in luck. In this webinar hosted by Skyport Systems, you gain insight into Microsoft's latest comprehensive guide, with tips on the best and easiest way…

710 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question