datagridview

时间:2015-09-30 13:00:48

标签: .net vb.net datagridview

如何在datagridview中显示格式的单元格的文本值?

例如,实际上mi文本值显示如下:

  

日期:2015年5月5日     用户:用户名
    重量:5.0

但是我需要在同一个单元格中这样做:

  

日期: 05/12/2015
    用户:用户名
    体重: 5.0

也许在单元格内有标签?

谢谢!

2 个答案:

答案 0 :(得分:1)

示例:

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网格单元格:

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渲染器:

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

答案 1 :(得分:0)

你可以这样做:

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

哪里&#34;网格&#34;是控件DataGridView,&#34; Concept&#34;是columName。如果你想使用另一种颜色:

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

如果您想更改行的默认样式:

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

或者您可以更改单元格的格式:

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

您可以看到MSDN - example