vb.net 中的打印预览为空

Posted

技术标签:

【中文标题】vb.net 中的打印预览为空【英文标题】:Print Preview in vb.net is empty 【发布时间】:2012-12-03 12:25:18 【问题描述】:

这是我的代码:

Imports System.Drawing
Imports System.Drawing.Printing
Imports System.Data
Imports System.Data.OleDb
Public Class Form3
Dim dgv As New DataGridView()
Dim print As New PrintDocument()
Dim preview As New PrintPreviewDialog()
Private Sub Form3_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
    Dim con As New OleDbConnection("Provider=Microsoft.Jet.Oledb.4.0;Data Source=C:\Users\user\Documents\Inventory\InventoryLogin\InventoryLogin\Supplies.mdb")
    Try
        con.Open()
        Dim sql As String
        sql = "SELECT * From [product info]"
        Dim adapter As New OleDbDataAdapter(sql, con)
        Dim dt As New DataTable("product info")
        adapter.Fill(dt)

        preview.PrintPreviewControl.Zoom = 1
        preview.Document = print
        preview.Show()

        AddHandler print.PrintPage, AddressOf print_PrintPage

    Catch Ex As Exception
        MessageBox.Show(Ex.Message)
    End Try

End Sub

Protected Sub print_PrintPage(ByVal sender As Object, ByVal e As PrintPageEventArgs)
    Dim ColumnCount As Integer = dgv.ColumnCount
    Dim RowCount As Integer = dgv.RowCount

    Dim CellTopPos As Integer = print.PrinterSettings.DefaultPageSettings.Margins.Top

    For Row = 0 To RowCount - 2

        Dim CellLeftPos As Integer = print.PrinterSettings.DefaultPageSettings.Margins.Left

        For Cell = 0 To ColumnCount - 1

            Dim CellValue As String = dgv.Rows(Row).Cells(Cell).Value.ToString()
            Dim CellWidth = dgv.Rows(Row).Cells(Cell).Size.Width + 10
            Dim CellHeight = dgv.Rows(Row).Cells(Cell).Size.Height

            Dim Brush As New SolidBrush(Color.Black)
            e.Graphics.DrawString(CellValue, New Font("tahoma", 10), Brush, CellLeftPos, CellTopPos)
            e.Graphics.DrawRectangle(Pens.Black, CellLeftPos, CellTopPos, CellWidth, CellHeight)

            CellLeftPos += CellWidth
        Next

        CellTopPos += dgv.Rows(Row).Cells(0).Size.Height
    Next

End Sub
End Class

我正在尝试在 vb.net 中预览和打印我的 datagridview 中的项目 用户需要在打印之前单击“打印预览”按钮来查看文档,但是当我单击该按钮时,它只显示一个空白页面。如何使 datagridview 中的记录出现在我的预览页面中?

【问题讨论】:

【参考方案1】:

我删除了 Dim dgv As New DataGridView 并替换为当前 DataGridView 的名称。

【讨论】:

以上是关于vb.net 中的打印预览为空的主要内容,如果未能解决你的问题,请参考以下文章

vb.net 中是不是有任何代码来检查打印机状态

来自访问数据库的 Vb.Net 预览报告

如何使用 vb.net 从查询创建访问报告

Chrome 打印预览与 DEVTools 中的不同

电脑怎么不能打印预览?

怎么在MindManager中查看打印预览