dataGridView to pdf with itextsharp

久未见 提交于 2019-11-28 12:24:19

问题


I have a problem while trying to get values of specific columns in dataGridView and add them to the PdtPtable. But the values added in the table is repeated, for example row one is added twice.I tried to go through each row and in every row through each column.

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);
}

回答1:


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.



来源:https://stackoverflow.com/questions/28161181/datagridview-to-pdf-with-itextsharp

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