2016-12-06 43 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