Export DataGridView to PDF Error: Object reference not set to an instance of an object in VB.Net

Last Reply on Jan 05, 2018 06:19 AM By kalpesh

Posted on Jan 05, 2018 05:59 AM

hi i have followed your steps but i seem to have an error.. also im using mysql database as my datagrid

Export Windows Forms DataGridView to PDF using iTextSharp, C# and VB.Net

Posted on Jan 05, 2018 06:19 AM Modified on on Jan 05, 2018 06:33 AM

1) First Debug the code to check the cell.value value if it’s null or empty it will throw NullReferenceException error.

2) Use Convert.ToString to convert the nullable string values so it will not throw such error. Or you can check the cell value using string.IsNullOrEmpty to handle nullable error.

Check the below Modified line code and implement it as per your code logic.

C#

pdfTable.AddCell(Convert.ToString(cell.Value));        
// or Below line code if you need to assign any default value if its null 
// here i assign empty string value if cell.Value is null or empty
pdfTable.AddCell(!string.IsNullOrEmpty(cell.Value) ? Convert.ToString(cell.Value) :"");

VB.Net

pdfTable.AddCell(Convert.ToString(cell.Value))
' or Below line code if you need to assign any default value if its null 
' here i assign empty string value if cell.Value is null or empty
pdfTable.AddCell(If(Not String.IsNullOrEmpty(cell.Value), Convert.ToString(cell.Value), ""))