I have a problem with the code I am writing to generate a pdf with the data from a DataGridView. After I run the DGV with the MySQL query, and I give the generate button, it throws an error that says: "Object reference not set to an instance of an object" the truth is I'm guiding myself from a video on youtube. (I'm new to programming: 3)
using System;
using System.IO;
using System.Windows.Forms;
using iTextSharp.text;
using iTextSharp.text.pdf;
public void exportarPDF(DataGridView DGAusentismo, string nombreArchivo)
{
try
{
BaseFont bf = BaseFont.CreateFont(BaseFont.TIMES_ROMAN, BaseFont.CP1250, BaseFont.EMBEDDED);
PdfPTable pdfTable = new PdfPTable(DGAusentismo.Columns.Count);
pdfTable.DefaultCell.Padding = 3;
pdfTable.WidthPercentage = 100;
pdfTable.HorizontalAlignment = Element.ALIGN_CENTER;
pdfTable.DefaultCell.BorderWidth = 1;
iTextSharp.text.Font texto = new Font(bf, 10, iTextSharp.text.Font.NORMAL);
//Header
foreach (DataGridViewColumn columnas in DGAusentismo.Columns)
{
PdfPCell celda = new PdfPCell(new Phrase(columnas.HeaderText, texto));
celda.BackgroundColor = new iTextSharp.text.BaseColor(240, 240, 240);
pdfTable.AddCell(celda);
}
//Agregar DataRow
foreach (DataGridViewRow Filas in DGAusentismo.Rows)
{
foreach (DataGridViewCell Celdas in Filas.Cells)
{
pdfTable.AddCell(new Phrase(Celdas.Value.ToString(),texto)); // El mensaje de error me dice que es esta linea
}
}
var savedialog = new SaveFileDialog();
savedialog.FileName = nombreArchivo;
savedialog.DefaultExt = ".pdf";
if (savedialog.ShowDialog() == DialogResult.OK)
{
using (FileStream stream = new FileStream(savedialog.FileName, FileMode.Create))
{
Document pdf = new Document(PageSize.LEGAL, 10f, 10f, 10f, 0f);
PdfWriter.GetInstance(pdf, stream);
pdf.Open();
pdf.Add(pdfTable);
pdf.Close();
stream.Close();
}
}
}
catch (Exception error)
{
MessageBox.Show("A ocurrido un error durante la exportacion: " + error.ToString());
}
}
The video that I'm guiding myself on is this: Export Datagridview to PDF
Now if someone has a better guide to export the datagridview to pdf I would be very grateful if you let me know because the video is in English and I do not understand many things that it explains.
Thanks