dataGridView to pdf with itextsharp

2020-02-16 03:43发布

问题:

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.