如何打印datagridview的内容 [英] How to Print The Contents of a datagridview
问题描述
大家好,我将向您展示一个示例程序,该程序可以打印datagridview的内容,尽管在打印完成之前发生了一个小错误,该程序仍能正常工作,但 OBJECT REFERENCE NOT设置为对象的实例 ,尽管它不会阻止程序达到目的。我想与您分享,至少我们可以讨论如何删除该错误。
该程序基于Northwind数据库的customers表。
在我的表格上有一个名为 Mydatagridview 的数据网格视图,一个名为 btnPrint的打印按钮
以下是VB代码..............
Hi everybody, am going to show you a sample program which enables to print the contents of a datagridview, the program works properly despite a minor error which occurs before the printing is done it says OBJECT REFERENCE NOT SET TO AN INSTANCE OF AN OBJECT, although it does not prevent the program from meeting the purpose. i would like to share it with you, and atleast we can discus on how to remove that error.
The program is based on the customers table of the Northwind Database.
On my form there is a datagridview named Mydatagridview, A print button called btnPrint
Below is the VB code ..............
Imports System.Data.OleDb
Imports System.Drawing.Printing
Imports System
Imports System.Collections
Imports System.ComponentModel
Imports System.Data
Imports System.Text
Imports System.Windows.Forms
Imports System.Drawing
Public Class Form1
Private WithEvents printDocument1 As New PrintDocument
'Used to save left coordinates of columns
Dim arrColumnLefts = New ArrayList()
'Used to save column widths
Dim arrColumnWidths = New ArrayList()
'Used to get and set the datagridview cell height
Dim iCellHeight As Integer = 0
Dim iTotalWidth As Integer = 0
'Used as counter
Dim iCount As Integer = 0
Dim iRow As Integer = 0
'Used to check whether we are printing first page
Dim bFirstPage As Boolean = False
'Used to check whether we are printing a new page
Dim bNewPage As Boolean = False
'Used for the header height
Dim iHeaderHeight As Integer = 0
Dim strFormat = New StringFormat()
Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
Dim con As New OleDb.OleDbConnection
con.ConnectionString = "provider=microsoft.jet.oledb.4.0; Data source= " & Application.StartupPath & "\Customers.mdb"
Dim ds As DataSet = New DataSet()
Dim dt As New DataTable
Dim da As OleDbDataAdapter = New OleDbDataAdapter("SELECT CompanyName,ContactName,Address,PostalCode,Phone from Customers2", con)
Me.WindowState = FormWindowState.Maximized
Try
da.Fill(ds, "dt")
da.Fill(ds, "Customers2")
MyDataGridView.DataSource = ds
MyDataGridView.DataMember = "dt"
Catch ex As Exception
MessageBox.Show("Operation failed: " + ex.ToString(), Application.ProductName + " - Error", MessageBoxButtons.OK, MessageBoxIcon.[Error])
Return
End Try
End Sub
Private Sub btnPrint_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnPrint.Click
'Open the print dialogue
Dim MyPrintDialog = New PrintDialog()
MyPrintDialog.Document = printDocument1
MyPrintDialog.UseEXDialog = True
'Get the document
If Windows.Forms.DialogResult.OK = MyPrintDialog.ShowDialog() Then
printDocument1.DocumentName = "Test page print"
printDocument1.Print()
End If
End Sub
Private Sub printDocument1_BeginPrint(ByVal sender As System.Object, ByVal e As System.Drawing.Printing.PrintEventArgs) Handles _
printDocument1.BeginPrint
' MsgBox("starting printpage")
Try
strFormat.Alignment = StringAlignment.Near
strFormat.LineAlignment = StringAlignment.Center
strFormat.Trimming = StringTrimming.EllipsisCharacter
arrColumnLefts.Clear()
arrColumnWidths.Clear()
iCellHeight = 0
bFirstPage = True
bNewPage = True
'Calculating Total Widths
iTotalWidth = 0
For Each dgvGridCol As DataGridViewColumn In MyDataGridView.Columns
iTotalWidth = iTotalWidth + dgvGridCol.Width
Next
Catch ex As Exception
MessageBox.Show(ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error)
End Try
End Sub
Private Sub printDocument1_PrintPage(ByVal sender As System.Object, ByVal e As System.Drawing.Printing.PrintPageEventArgs) Handles _
printDocument1.PrintPage
Try
'Set the left margin
Dim iLeftMargin As Integer = e.MarginBounds.Left
'Set the top margin
Dim iTopMargin As Integer = e.MarginBounds.Top
'Whether more pages have to print or not
Dim bMorePagesToPrint As Boolean = False
Dim iTmpWidth As Integer = 0
'For the first page to print set the cell width and header height
If bFirstPage = True Then
For Each Gridcol As DataGridViewColumn In MyDataGridView.Columns
iTmpWidth = CType(Math.Floor(CType(CType(Gridcol.Width, Double) / CType(iTotalWidth, Double) * CType(iTotalWidth, Double) * (CType(e.MarginBounds.Width, Double) / CType(iTotalWidth, Double)), Double)), Integer)
iHeaderHeight = CType((e.Graphics.MeasureString(Gridcol.HeaderText, Gridcol.InheritedStyle.Font, iTmpWidth).Height) + 11, Integer)
'Save width and height of headers
arrColumnLefts.Add(iLeftMargin)
arrColumnWidths.Add(iTmpWidth)
iLeftMargin = iLeftMargin + iTmpWidth
Next
End If
'Loop till all the grid rows not get printed
While iRow <= MyDataGridView.Rows.Count - 1
Dim GridRow As DataGridViewRow = MyDataGridView.Rows(iRow)
'Set the cell height
iCellHeight = GridRow.Height + 5
Dim iCount As Integer = 0
'Check whether the current page settings allo more rows to print
If iTopMargin + iCellHeight >= e.MarginBounds.Height + e.MarginBounds.Top Then
bNewPage = True
bFirstPage = False
bMorePagesToPrint = True
Exit While
Else
If bNewPage = True Then
'Draw header
e.Graphics.DrawString("Fibre Requirements", New Font(MyDataGridView.Font, FontStyle.Bold), Brushes.Black, e.MarginBounds.Left, e.MarginBounds.Top - e.Graphics.MeasureString("Customer Summary", New Font(MyDataGridView.Font, FontStyle.Bold), e.MarginBounds.Width).Height - 13)
Dim strDate As String = DateTime.Now.ToLongDateString() + " " + DateTime.Now.ToShortTimeString()
'Draw Date
e.Graphics.DrawString(strDate, New Font(MyDataGridView.Font, FontStyle.Bold), Brushes.Black, e.MarginBounds.Left + (e.MarginBounds.Width - e.Graphics.MeasureString(strDate, New Font(MyDataGridView.Font, FontStyle.Bold), e.MarginBounds.Width).Width), e.MarginBounds.Top - e.Graphics.MeasureString("Customer Summary", New Font(New Font(MyDataGridView.Font, FontStyle.Bold), FontStyle.Bold), e.MarginBounds.Width).Height - 13)
'Draw Columns
iTopMargin = e.MarginBounds.Top
For Each GridCol As DataGridViewColumn In MyDataGridView.Columns
e.Graphics.FillRectangle(New SolidBrush(Color.LightGray), New Rectangle(CType(arrColumnLefts(iCount), Integer), iTopMargin, CType(arrColumnWidths(iCount), Integer), iHeaderHeight))
e.Graphics.DrawRectangle(Pens.Black, New Rectangle(CType(arrColumnLefts(iCount), Integer), iTopMargin, CType(arrColumnWidths(iCount), Integer), iHeaderHeight))
e.Graphics.DrawString(GridCol.HeaderText, GridCol.InheritedStyle.Font, New SolidBrush(GridCol.InheritedStyle.ForeColor), New RectangleF(CType(arrColumnLefts(iCount), Integer), iTopMargin, CType(arrColumnWidths(iCount), Integer), iHeaderHeight), strFormat)
iCount = iCount + 1
Next GridCol
bNewPage = False
iTopMargin += iHeaderHeight
End If
iCount = 0
'Draw Columns Contents
For Each Cel As DataGridViewCell In GridRow.Cells
If Not IsDBNull(Cel.Value) Then
e.Graphics.DrawString(Cel.Value.ToString(), Cel.InheritedStyle.Font, New SolidBrush(Cel.InheritedStyle.ForeColor), New RectangleF(CType(arrColumnLefts(iCount), Integer), CType(iTopMargin, Single), CType(arrColumnWidths(iCount), Integer), CType(iCellHeight, Single)), strFormat)
End If
'Drawing Cells Borders
e.Graphics.DrawRectangle(Pens.Black, New Rectangle(CType(arrColumnLefts(iCount), Integer), iTopMargin, CType(arrColumnWidths(iCount), Integer), iCellHeight))
iCount = iCount + 1
Next
End If
iRow = iRow + 1
iTopMargin = iTopMargin + iCellHeight
End While
'If more lines exist, print another page.
If bMorePagesToPrint = True Then
e.HasMorePages = True
Else
e.HasMorePages = False
End If
Catch exc As Exception
MessageBox.Show(exc.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error)
End Try
End Sub
End Class
推荐答案
你已经在普通论坛中发布了这个问题。不要在多个地方发布相同的问题。这使得无法就答案进行合作。
你已经被告知你需要做什么。
You already posted this question in the normal forums. Don''t post the same question in multiple places. It makes it impossible to collaborate on an answer.
You''ve already been told what you need to do.
这篇关于如何打印datagridview的内容的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!