Click here to Skip to main content
14,421,065 members
Rate this:
Please Sign up or sign in to vote.
See more:
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
Posted
Updated 16-May-13 4:08am
v2
Comments
[no name] 16-May-13 8:32am
   
Instead of dumping all of your code here, why don't you post the relevant code related to your problem? Besides that running your code through the debugger would tell you which object is null and that in turn will tell you what you need to do to make the object not null.

1 solution

Rate this:
Please Sign up or sign in to vote.

Solution 1

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.
   

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)




CodeProject, 503-250 Ferrand Drive Toronto Ontario, M3C 3G8 Canada +1 416-849-8900 x 100