dataGridView to pdf with itextsharp

丶灬走出姿态 提交于 2019-11-29 17:25:40

I have fixed the indentation in your code snippet. You can now see what you're doing wrong in one glimpse.

You have:

PdfPTable pdfTable= new PdfPTable(5);
foreach(DataGridViewRow row in dataGridView1.Rows) {
    foreach (DataGridViewCell celli in row.Cells) {
        try {
            pdfTable.AddCell(celli.Value.ToString());
        }
        catch { }
    }
    doc.Add(pdfTable);
}

This means that you are creating a table, adding it as many times as there are rows, hence the repetition of the rows.

You should have:

PdfPTable pdfTable= new PdfPTable(5);
foreach(DataGridViewRow row in dataGridView1.Rows) {
    foreach (DataGridViewCell celli in row.Cells) {
        try {
            pdfTable.AddCell(celli.Value.ToString());
        }
        catch { }
    }
}
doc.Add(pdfTable);

Or better yet:

PdfPTable pdfTable= new PdfPTable(5);
foreach(DataGridViewRow row in dataGridView1.Rows) {
    foreach (DataGridViewCell celli in row.Cells) {
        pdfTable.AddCell(celli.Value.ToString());
    }
}
doc.Add(pdfTable);

Now you are adding the table only once.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!