2016-12-06 3 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 -it) – 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 

あなたは、私が唯一それが共通のnull参照の上に吹いていると仮定することができます使用しているPDFライターについての詳細を知らず。とともに '?。'演算子私は、親または子がnullである場合、それは同じであると言っています。だから本質的に私は何もしていないかどうかをチェックしています。何かがあれば、それを提供します。

+0

これを行うと、もはやエラーがスローされなくなりますが、pdfも作成されません。 NullReferenceExceptionは、オブジェクト参照がオブジェクトのインスタンスに設定されていないことを示します。元のコード行を指しています。私はPDFライターとしてiTextSharpを使用しています。 – MNCS

+0

ブレークポイントを設定し、オブジェクトが正しく取り込まれていることを確認してください。 – djangojazz