打印datagridview

时间:2016-06-13 08:17:14

标签: vb.net datagridview

我正在尝试打印一个datagridview,它将从数据库中获取值,我能够做到这一点,但我不知道为什么列名称在打印后没有显示出来。以下是我目前使用的代码:

这个是用于printdocument:

Private Sub PrintDocument1_PrintPage(sender As Object, e As Printing.PrintPageEventArgs) Handles PrintDocument1.PrintPage
        With DataGridView3
            Dim fmt As StringFormat = New StringFormat(StringFormatFlags.LineLimit)
            Dim text As String = ("TrashCollection - Estatísticas")
            fmt.LineAlignment = StringAlignment.Center
            fmt.Trimming = StringTrimming.EllipsisCharacter
            e.Graphics.DrawString(text, New Font("Verdana", 10, FontStyle.Bold), Brushes.Black, 350, 30)
            Dim y As Single = e.MarginBounds.Top
            Do While mRow < DataGridView3.RowCount
                Dim row As DataGridViewRow = .Rows(mRow)
                Dim x As Single = e.MarginBounds.Left
                Dim h As Single = 0
                For Each cell As DataGridViewCell In row.Cells
                    Dim rc As RectangleF = New RectangleF(x, y, cell.Size.Width, cell.Size.Height)
                    e.Graphics.DrawRectangle(Pens.Black, rc.Left, rc.Top, rc.Width, rc.Height)
                    If (newpage) Then
                        e.Graphics.DrawString(DataGridView3.Columns(cell.ColumnIndex).HeaderText, .Font, Brushes.Black, rc, fmt)
                    Else
                        e.Graphics.DrawString(DataGridView3.Rows(cell.RowIndex).Cells(cell.ColumnIndex).FormattedValue.ToString(), .Font, Brushes.Black, rc, fmt)
                    End If
                    x += rc.Width
                    h = Math.Max(h, rc.Height)
                Next
                newpage = False
                y += h
                mRow += 1
                If y + h > e.MarginBounds.Bottom Then
                    e.HasMorePages = True
                    mRow -= 0
                    newpage = True
                    Exit Sub
                End If
            Loop
            mRow = 0
        End With
    End Sub

然后进入打印按钮我有这行代码:

Private Sub cmdPrintDetailed_Click(sender As Object, e As EventArgs) Handles cmdPrintDetailed.Click
        PrintDocument1.DefaultPageSettings.Landscape = True
        PrintPreviewDialog1.Document = PrintDocument1
        PrintPreviewDialog1.ShowDialog()
    End Sub

所以,基本上我希望能够打印列名而不仅仅是行。几乎忘了,在打印预览中,我能够看到所有带有列的datagridview

1 个答案:

答案 0 :(得分:0)

这是我找到的最好的打印示例,我将其用于数据网格打印。可能这将帮助您asit addesses也列标题。 https://code.msdn.microsoft.com/VBNet-Printing-Example-bc3b0176