itextsharp - how can i save a datagrid data into pdf?

poringgunner

Active member
Joined
Feb 23, 2014
Messages
42
Programming Experience
Beginner
here is my code.. i always get error..


Document save = new Document(iTextSharp.text.PageSize.LETTER, 10, 10, 42, 35);
PdfWriter write = PdfWriter.GetInstance(save, new FileStream("Report.pdf", FileMode.Create));
save.Open();


PdfPTable pdfTable = new PdfPTable(dataGridView1.Columns.Count);


for (int i = 0; i < dataGridView1.Columns.Count; i++)
{
pdfTable.AddCell(new Phrase(dataGridView1.Columns.HeaderText));
}


pdfTable.HeaderRows = 1;


for (int p = 0; p < dataGridView1.Rows.Count; p++)
{
for (int o = 0; 0 < dataGridView1.Columns.Count; o++)
{
if (dataGridView1[p, o].Value != null) //i always got an error here.. index was out of range. must be non-negative and less than the size of the collection. parameter name: index.
{
pdfTable.AddCell(new Phrase(dataGridView1[p, o].Value.ToString()));
}
}
}


save.Add(pdfTable);


save.Close();


i dnt know what is wrong in my code :(
 

jmcilhinney

C# Forum Moderator
Staff member
Joined
Apr 23, 2011
Messages
3,272
Location
Sydney, Australia
Programming Experience
10+
If what you have posted is your actual code then the issue is here:
C#:
for (int o = 0; [B][U][COLOR="#FF0000"]0[/COLOR][/U][/B] < dataGridView1.Columns.Count; o++)
You've used the digit `0` there instead of the letter `o`. Maybe use meaningful names like `rowIndex` and `columnIndex` and then such mistakes are far less likely.
 
Top Bottom