2016-12-06 47 views
-1

好吧我想打印在Visual Basic.net一个DataGridView到PDF我不断收到的NullReferenceException是未处理的错误。我需要一些帮助。Visual Basic中的DataGridView到PDF异常错误

Private Sub Button5_Click(sender As Object, e As EventArgs) Handles Button5.Click 
    'Creating iTextSharp Table from the DataTable data 

    Dim pdfTable As New PdfPTable(DataGridView1.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 DataGridView1.Columns 

      Dim cell As New PdfPCell(New Phrase(column.HeaderText)) 

      cell.BackgroundColor = New iTextSharp.text.BaseColor(240, 240, 240) 

      pdfTable.AddCell(cell) 

     Next 



     'Adding DataRow 

     For Each row As DataGridViewRow In DataGridView1.Rows 

      For Each cell As DataGridViewCell In row.Cells 

       **pdfTable.AddCell(cell.Value.ToString())** (this is where the exception is thrown) 

      Next 

     Next 



     'Exporting to PDF 

     Dim folderPath As String = "C:\Users\mnevi\Documents\testpdf" 

    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 
End Sub 

我已经用**标记了抛出异常的代码。任何援助非常感谢。

+1

的可能的复制[什么是一个NullReferenceException,如何解决呢?(http://stackoverflow.com/questions/4660142/what-is-a-nullreferenceexception-and-how-do-i-fix - 它) – Blackwood

回答

0

更改此:

For Each cell As DataGridViewCell In row.Cells 

       **pdfTable.AddCell(cell.Value.ToString())** (this is where the exception is thrown) 

      Next 

要更多的东西是这样的:

For Each cell As DataGridViewCell In row.Cells 
    Dim val = If(Not String.IsNullOrEmpty(cell?.Value?.ToString), cell?.Value?.ToString, String.Empty) 
       pdfTable.AddCell(val) 

      Next 

不知道更多关于PDF笔者使用的是我只能假设它是在一个共同的空引用炸毁。用'?'算子我在说,如果父母或孩子是空的,就等同于它。所以基本上我检查什么,然后,如果有什么东西,只要它,否则这给了它至少是后话。

+0

那么它不再抛出的错误,当我这样做,但它也不会创建PDF。嗯NullReferenceException说对象引用未设置为对象的实例。指向原始代码行。我正在使用iTextSharp作为pdf编写器。 – MNCS

+0

设置断点,并确保你的对象越来越无误将是我的猜测。 – djangojazz