简体   繁体   中英

Formatted text inside cell on datagridview

How can i display the text value of a cell with format in a datagridview?

By example, actually mi text value is displayed like this:

Date: 05/12/2015
User: Username
Weight: 5.0

But i need it like this in the same cell:

Date: 05/12/2015
User: Username
Weight: 5.0

Maybe with labels inside the cell?

Thanks!

Example:

Public Class Form1
    Private Sub Form1_Load(sender As System.Object, e As System.EventArgs) Handles MyBase.Load
        'The grid would normally be setup in the designer...
        Dim grid = New DataGridView
        grid.SetBounds(40, 40, 400, 200)
        grid.RowHeadersVisible = False
        grid.AllowUserToAddRows = False

        Dim column1 = New DataGridViewTextBoxColumn()
        column1.HeaderText = "Name"
        column1.Width = 100

        Dim column2 = New DataGridViewRTFColumn
        column2.HeaderText = "Text"
        column2.AutoSizeMode = DataGridViewAutoSizeColumnMode.Fill

        grid.Columns.AddRange({column1, column2})
        Controls.Add(grid)

        'Add rows
        Dim rtfBase = "{\rtf1\ansi\ansicpg1252\deff0\deflang2057{\fonttbl{\f0\fnil\fcharset0 Microsoft Sans Serif;}{\f1\fnil Microsoft Sans Serif;}}\viewkind4\uc1\pard\f0\fs17 "
        grid.Rows.Add("1", rtfBase & "The \b\f1 quick \b0\f0 brown fox\par}")
        grid.Rows.Add("2", rtfBase & "\b\f1  jumps\b0\f0  over\b\f1  the \b0\f0 lazy dog.\par}")
    End Sub
End Class

RTF Grid Cell:

Public Class DataGridViewRTFColumn
    Inherits DataGridViewColumn

    Public Sub New()
        Me.celltemplate = New DataGridViewRTFCell
    End Sub

    Public Overrides Property CellTemplate As System.Windows.Forms.DataGridViewCell
        Get
            Return MyBase.CellTemplate
        End Get
        Set(value As System.Windows.Forms.DataGridViewCell)
            If value IsNot Nothing AndAlso Not value.GetType.IsAssignableFrom(GetType(DataGridViewRTFCell)) Then
                Throw New InvalidCastException("Must be a DataGridViewRTFCell")
            End If

            MyBase.CellTemplate = value
        End Set
    End Property
End Class

Public Class DataGridViewRTFCell
    Inherits DataGridViewCell

    Public Overrides ReadOnly Property FormattedValueType As System.Type
        Get
            Return GetType(String)
        End Get
    End Property

    Protected Overrides Sub Paint(graphics As System.Drawing.Graphics, clipBounds As System.Drawing.Rectangle, cellBounds As System.Drawing.Rectangle, rowIndex As Integer, cellState As System.Windows.Forms.DataGridViewElementStates, value As Object, formattedValue As Object, errorText As String, cellStyle As System.Windows.Forms.DataGridViewCellStyle, advancedBorderStyle As System.Windows.Forms.DataGridViewAdvancedBorderStyle, paintParts As System.Windows.Forms.DataGridViewPaintParts)
        Dim isSelected = (cellState And DataGridViewElementStates.Selected) <> 0

        If (paintParts And (DataGridViewPaintParts.Background Or DataGridViewPaintParts.SelectionBackground)) <> 0 Then
            graphics.FillRectangle(If(isSelected, New SolidBrush(cellStyle.SelectionBackColor), New SolidBrush(cellStyle.BackColor)), cellBounds)
        End If

        If (paintParts And DataGridViewPaintParts.Border) <> 0 Then
            PaintBorder(graphics, clipBounds, cellBounds, cellStyle, advancedBorderStyle)
        End If

        If (paintParts And DataGridViewPaintParts.ContentForeground) <> 0 Then
            Dim contentBounds = Rectangle.Inflate(cellBounds, -3, -3)
            RTFRenderer.DrawRTF(graphics, String.Concat(value), contentBounds, If(isSelected, cellStyle.SelectionBackColor, cellStyle.BackColor))
        End If
    End Sub
End Class

RTF Renderer:

Imports System
Imports System.Drawing
Imports System.Runtime.InteropServices
Imports System.Windows.Forms

Public Class RTFRenderer
    'Converted to vb.net from http://andrewvos.com/2008/05/23/draw-rtf-text-on-a-graphics-object-in-c/
    Public Shared Sub DrawRTF(g As Graphics, rtf As String, layoutArea As Rectangle, backColor As Color)
        Static rtfDrawer As New RichTextBoxRenderer
        rtfDrawer.Rtf = rtf
        rtfDrawer.BackColor = backColor
        rtfDrawer.Draw(g, layoutArea)
    End Sub

    Private Class RichTextBoxRenderer
        Inherits RichTextBox

        'Code converted from code found here: http://support.microsoft.com/kb/812425/en-us
        Public Sub Draw(g As Graphics, layoutArea As Rectangle)
            Dim xFrac = 1440 / g.DpiX
            Dim yFrac = 1440 / g.DpiY

            'Convert the layoutArea from pixels to twips
            Dim rectLayoutArea As SafeNativeMethods.RECT
            rectLayoutArea.Top = CInt(layoutArea.Top * yFrac)
            rectLayoutArea.Bottom = CInt(layoutArea.Bottom * yFrac)
            rectLayoutArea.Left = CInt(layoutArea.Left * xFrac)
            rectLayoutArea.Right = CInt(layoutArea.Right * xFrac)

            Dim hdc = g.GetHdc

            Dim fmtRange As SafeNativeMethods.FORMATRANGE
            fmtRange.chrg.cpMax = -1         'Indicate character from to character to 
            fmtRange.chrg.cpMin = 0
            fmtRange.hdc = hdc               'Use the same DC for measuring and rendering
            fmtRange.hdcTarget = hdc         'Point at printer hDC
            fmtRange.rc = rectLayoutArea     'Indicate the area on page to print
            fmtRange.rcPage = rectLayoutArea 'Indicate size of page

            'Get the pointer to the FORMATRANGE structure in memory
            Dim lParam = Marshal.AllocCoTaskMem(Marshal.SizeOf(fmtRange))
            Marshal.StructureToPtr(fmtRange, lParam, False)

            Dim wParam = New IntPtr(1) 'Non-zero = Render the text, zero = measure the text
            SafeNativeMethods.SendMessage(Me.Handle, SafeNativeMethods.EM_FORMATRANGE, wParam, lParam)

            'Free the block of memory allocated
            Marshal.FreeCoTaskMem(lParam)

            'Release the device context handle obtained by a previous call
            g.ReleaseHdc(hdc)
        End Sub

        Private Class SafeNativeMethods
            <DllImport("user32.dll", SetLastError:=True, CharSet:=CharSet.Auto)> _
            Public Shared Function SendMessage(ByVal hWnd As IntPtr, ByVal Msg As UInteger, ByVal wParam As IntPtr, ByVal lParam As IntPtr) As IntPtr
            End Function

            <DllImport("kernel32.dll", SetLastError:=True, CharSet:=CharSet.Ansi)> _
            Public Shared Function LoadLibrary(ByVal lpFileName As String) As IntPtr
            End Function

            <StructLayout(LayoutKind.Sequential)> _
            Public Structure RECT
                Public Left As Integer
                Public Top As Integer
                Public Right As Integer
                Public Bottom As Integer
            End Structure

            <StructLayout(LayoutKind.Sequential)> _
            Public 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)> _
            Public 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 earlier declaration)
            End Structure

            Public Const WM_USER = &H400
            Public Const EM_FORMATRANGE = WM_USER + 57
        End Class
    End Class
End Class

You can do:

Grid.Columns("Concept").DefaultCellStyle.Font = New Font(Grid.Font, FontStyle.Bold)

Where "Grid" is the control DataGridView, "Concept" is the columName. If you want use another colour:

 Grid.Columns("Concepto").DefaultCellStyle.ForeColor = Color.Maroon

If you want change the row's default style:

Grid.Rows(7).DefaultCellStyle.BackColor = Color.WhiteSmoke
Grid.Rows(7).DefaultCellStyle.Font = New Font(Grid.Font, FontStyle.Bold)
Grid.Rows(7).DefaultCellStyle.ForeColor = Color.DarkSlateGray

Or you can change the cell's format:

Grid.Rows(7).Cells("Concept").Style.BackColor = Color.AliceBlue

You can see MSDN - example .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM