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
Dim arrColumnLefts = New ArrayList()
Dim arrColumnWidths = New ArrayList()
Dim iCellHeight As Integer = 0
Dim iTotalWidth As Integer = 0
Dim iCount As Integer = 0
Dim iRow As Integer = 0
Dim bFirstPage As Boolean = False
Dim bNewPage As Boolean = False
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
Dim MyPrintDialog = New PrintDialog()
MyPrintDialog.Document = printDocument1
MyPrintDialog.UseEXDialog = True
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
Try
strFormat.Alignment = StringAlignment.Near
strFormat.LineAlignment = StringAlignment.Center
strFormat.Trimming = StringTrimming.EllipsisCharacter
arrColumnLefts.Clear()
arrColumnWidths.Clear()
iCellHeight = 0
bFirstPage = True
bNewPage = True
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
Dim iLeftMargin As Integer = e.MarginBounds.Left
Dim iTopMargin As Integer = e.MarginBounds.Top
Dim bMorePagesToPrint As Boolean = False
Dim iTmpWidth As Integer = 0
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)
arrColumnLefts.Add(iLeftMargin)
arrColumnWidths.Add(iTmpWidth)
iLeftMargin = iLeftMargin + iTmpWidth
Next
End If
While iRow <= MyDataGridView.Rows.Count - 1
Dim GridRow As DataGridViewRow = MyDataGridView.Rows(iRow)
iCellHeight = GridRow.Height + 5
Dim iCount As Integer = 0
If iTopMargin + iCellHeight >= e.MarginBounds.Height + e.MarginBounds.Top Then
bNewPage = True
bFirstPage = False
bMorePagesToPrint = True
Exit While
Else
If bNewPage = True Then
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()
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)
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
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
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 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