Hi guys, Am trying to print datagridview contents to pdf.
I have tried to use the code below I learned from the net, bu it is giving an error message "Object reference not set to an instance of an object."

 Private Sub bntToPDF_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles bntToPDF.Click
        Try
            'Creating iTextSharp Table from the DataTable data
            Dim pdfTable As New PdfPTable(dtgAnualSales.ColumnCount)
            pdfTable.DefaultCell.Padding = 3
            pdfTable.WidthPercentage = 30
            pdfTable.HorizontalAlignment = Element.ALIGN_LEFT
            pdfTable.DefaultCell.BorderWidth = 1

            'Adding Header row
            For Each column As DataGridViewColumn In dtgAnualSales.Columns
                Dim cell As New PdfPCell(New Phrase(column.HeaderText))
                cell.BackgroundColor = New iTextSharp.text.Color(240, 240, 240)
                pdfTable.AddCell(cell)
            Next

            'Adding DataRow
            For Each row As DataGridViewRow In dtgAnualSales.Rows
                For Each cell As DataGridViewCell In row.Cells
                    pdfTable.AddCell(cell.Value.ToString())
                Next
            Next

            'Exporting to PDF
            Dim folderPath As String = "C:\PDFs\"
            If Not Directory.Exists(folderPath) Then
                Directory.CreateDirectory(folderPath)
            End If
            Using stream As New FileStream(folderPath & "DataGridViewExport.pdf", FileMode.Create)
                Dim pdfDoc As New Document(PageSize.A2, 10.0F, 10.0F, 10.0F, 0.0F)
                PdfWriter.GetInstance(pdfDoc, stream)
                pdfDoc.Open()
                pdfDoc.Add(pdfTable)
                pdfDoc.Close()
                stream.Close()
            End Using
        Catch ex As Exception
            MsgBox(ex.Message)
        End Try
    End Sub

I am not sure why the error is occuring. It is stopping to debug on line 20.

Someone to help me pliz.

Hi,
A bit Rusty at PDF creation so forgive me but you don't seam to be adding Rows to your pdfTable.

Anyway I would put a check in to see if the datagrid cell had a value:

'......

For Each cell As DatagridViewCell in rows.cells
    If cell.value isnot Nothing andalso cell.value.tostring <> "" then
        pdfTable.AddCell(cell.Value.ToString())
    else
        pdfTable.AddCell("")
    end if
Next

Edited 1 Year Ago by G_Waddell

Hi,
"Object reference not set to an instance of an object." it means your table does not contain any data or your DataReader does not able to fetch any records from table. check it ones your connection string and table data. if you still facing the same problem get back to me
Thanks

This article has been dead for over six months. Start a new discussion instead.