Click here to Skip to main content
15,915,094 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Hi Frds,
I have 10 columns in my datagridview but I run time it will show only 6 columns. I want export this 6 Columns to PDF. how Can i do this.



Thanks in Advance

What I have tried:

C#
List<datagridviewcolumn> listVisible = new List<datagridviewcolumn>();
             foreach (DataGridViewColumn col in dataGridView1.Columns)
             {
                 if (col.Visible)
                     listVisible.Add(col);
             }
             PdfPTable pdfTable = new PdfPTable(listVisible.Count);
             pdfTable.DefaultCell.Padding = 2;
             pdfTable.WidthPercentage = 100;
             pdfTable.HorizontalAlignment = Element.ALIGN_LEFT;
             pdfTable.DefaultCell.BorderWidth = 1;
            //Adding Header row
             for (int i = 0; i < listVisible.Count; i++)
             {


                 PdfPCell cell = new PdfPCell(new Phrase(listVisible[i].HeaderText));

                 pdfTable.AddCell(cell);
                
            }

            //Adding DataRow
             for (int i = 0; i < dataGridView1.Rows.Count - 1; i++)
            {
                for (int j = 0; j < listVisible.Count; j++)
                {
                    try
                    {
                      
                        pdfTable.AddCell( dataGridView1.Rows[i].Cells[listVisible[j].Name].Value.ToString());
                    }
                    catch
                    {
                    }
                }
            }
            SaveFileDialog svg = new SaveFileDialog();
            svg.ShowDialog();

            using (FileStream stream = new FileStream(svg.FileName + ".pdf", FileMode.Create))
            {
                Document pdfDoc = new Document(PageSize.A4, 10f, 10f, 10f, 0f);
                PdfWriter.GetInstance(pdfDoc, stream);
                pdfDoc.Open();
                pdfDoc.Add(pdfTable);
                pdfDoc.Close();
                stream.Close();
                MessageBox.Show("PDF Created Successfully");
            }
Posted
v2
Comments
So, loop till 6, what is the problem?
CodeReady 20-Jun-16 3:56am    
For any 6 column, write some logic to skip 4 columns like: create an enum of 4 column and skip these 4 from Header row and Data row.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900