Export datagridview to pdf in windows form application in asp.net

Description:-

In this example we explain that how to export DataGridView data to PDF file in Windows Forms (WinForms) Applications using ItextSharp PDF conversion library using C#. DataGridView cannot provide facility to export Griddata directally to pdf and so that we have to use one .dll file and give reference to your project and use the functionality export to pdf in table format by using the iTextSharp.dll Table for this solution.

To export DataGrid data or row to pdf format first download the iTextSharp.dll and the use it in your project. Here below is code to export DataGridView data to pdf with table format and Company logo or image logo with header footer in pdf writing data.

Create Table:-

CREATETABLE [dbo].[cardetail](
 [carno] [nvarchar](50)NOTNULL,
 [carname] [nvarchar](50)NOTNULL,
 [address] [nvarchar](50)NOTNULL,
 [personname] [varchar](50)NOTNULL,
 [cellno] [bigint] NOTNULL,
 [detail] [nvarchar](50)NOTNULL,
 [total] [bigint] NOTNULL,
 [id] [bigint] IDENTITY(1,1)NOTNULL,
CONSTRAINT [PK_cardetail] PRIMARYKEYCLUSTERED
(
 [id] ASC
)WITH (PAD_INDEX=OFF,STATISTICS_NORECOMPUTE=OFF,IGNORE_DUP_KEY=OFF,ALLOW_ROW_LOCKS=ON,ALLOW_PAGE_LOCKS=ON)ON [PRIMARY]
)ON [PRIMARY]

GO

Default.aspx.cs:-

SqlConnection cn = new SqlConnection("ConnectionString");
Int32 empid;
public Form1()
{
  //this.cardetail_Load();
  InitializeComponent();
}

//function for pass data to this function as a datareader and its display in pdf table format 
private void GenerateBillAndExport(SqlDataReader Reader)
{
if (Reader.HasRows)
{
  if (Reader.Read())
  {
    PdfPTablePdfPTable = newPdfPTable(4);
    PdfPTable.DefaultCell.Padding = 3;
    PdfPTable.WidthPercentage = 100;
    PdfPTable.HorizontalAlignment = Element.ALIGN_LEFT;
    PdfPTable.DefaultCell.BorderWidth = 1;

    PdfPTable.AddCell(new PdfPCell(iTextSharp.text.Image.GetInstance("D://Logo.jpg")) { Border = 0 });
    PdfPTable.AddCell(new PdfPCell(new Phrase("Name: " + Reader[3].ToString())) { Border = 0 });
    PdfPTable.AddCell(new PdfPCell(new Phrase("Date :" + DateTime.Now.ToShortDateString())) { Border = 0 });
    PdfPTable.AddCell(new PdfPCell(new Phrase("Mobile No  :" + Reader[4].ToString())) { Border = 0 });

    PdfPTable.AddCell(new PdfPCell(new Phrase("CarName")) { BackgroundColor = iTextSharp.text.BaseColor.GRAY });
    PdfPTable.AddCell(new PdfPCell(new Phrase("Detail")) { BackgroundColor = iTextSharp.text.BaseColor.GRAY });
    PdfPTable.AddCell(new PdfPCell(new Phrase("Total")) { BackgroundColor = iTextSharp.text.BaseColor.GRAY });
    PdfPTable.AddCell(new PdfPCell(new Phrase("CarNo")) { BackgroundColor = iTextSharp.text.BaseColor.GRAY });

    PdfPTable.AddCell(Reader[1].ToString());
    PdfPTable.AddCell(Reader[5].ToString());
    PdfPTable.AddCell(Reader[6].ToString());
    PdfPTable.AddCell(Reader[0].ToString());
    //add blank row 
    iTextSharp.text.pdf.PdfPCell c1 = new iTextSharp.text.pdf.PdfPCell(new Phrase(" "));
    iTextSharp.text.pdf.PdfPCell c2 = new iTextSharp.text.pdf.PdfPCell(new Phrase(" "));
    iTextSharp.text.pdf.PdfPCell c3 = new iTextSharp.text.pdf.PdfPCell(new Phrase(" "));
    iTextSharp.text.pdf.PdfPCell c4 = new iTextSharp.text.pdf.PdfPCell(new Phrase(" "));
    PdfPTable.AddCell(c1);
    PdfPTable.AddCell(c2);
    PdfPTable.AddCell(c3);
    PdfPTable.AddCell(c4);
    //Add Footer row 
    PdfPTable.AddCell(newPdfPCell(new Phrase("Name:- Umesh Adroja" + Environment.NewLine + "Contact No:- 8000762096"))
    {
      BackgroundColor = iTextSharp.text.BaseColor.LIGHT_GRAY
    });
    PdfPTable.AddCell(newPdfPCell(new Phrase("")));
    PdfPTable.AddCell(newPdfPCell(new Phrase("")));
    PdfPTable.AddCell(newPdfPCell(new Phrase("")));
    //PdfPTable.AddCell(new PdfPCell(new Phrase("Name:- Umesh Adroja" + Environment.NewLine + "Contact No:- 8000762096"))
    //{
    //    BackgroundColor = iTextSharp.text.BaseColor.LIGHT_GRAY
    //});
    //Exporting to PDF 
    stringfolderPath = "D:\\PDFs\\";
    if (!Directory.Exists(folderPath))
    {
      Directory.CreateDirectory(folderPath);
    }
    //Reader.GetValue(0) + "_" + DateTime.Now.ToShortDateString() 
    FileStream stream = new FileStream(folderPath + Reader.GetValue(0) + "_" + ".pdf", FileMode.Create);
    using (stream)
    {
      Document pdfDoc = new Document(PageSize.A2, 10f, 10f, 10f, 0f);
      PdfWriter.GetInstance(pdfDoc, stream);
      pdfDoc.Open();
      pdfDoc.Add(PdfPTable);
      pdfDoc.Close();
      stream.Close();
      System.Diagnostics.Process.Start(folderPath + Reader.GetValue(0) + "_" + ".pdf");
    }
  }
}
}

private void cardetail_Load(object sender, EventArgs e)
{
  DataTable dt = binddata();
  dataGridView2.DataSource = dt;
  dataGridView2.AutoGenerateColumns = false;
  dataGridView2.AllowUserToAddRows = false;
  DataGridViewLinkColumnEditlink = newDataGridViewLinkColumn();
  Editlink.UseColumnTextForLinkValue = true;
  Editlink.HeaderText = "Edit";
  Editlink.DataPropertyName = "lnkColumn";
  Editlink.LinkBehavior = LinkBehavior.SystemDefault;
  Editlink.Text = "Edit";
  dataGridView2.Columns.Add(Editlink);
  DataGridViewLinkColumnDeletelink = newDataGridViewLinkColumn();
  Deletelink.UseColumnTextForLinkValue = true;
  Deletelink.HeaderText = "delete";
  Deletelink.DataPropertyName = "lnkColumn";
  Deletelink.LinkBehavior = LinkBehavior.SystemDefault;
  Deletelink.Text = "Delete";
  dataGridView2.Columns.Add(Deletelink);
  DataGridViewLinkColumnPrintlink = newDataGridViewLinkColumn();
  Printlink.UseColumnTextForLinkValue = true;
  Deletelink.HeaderText = "Export to pdf";
  Printlink.DataPropertyName = "lnkColumn";
  Printlink.LinkBehavior = LinkBehavior.SystemDefault;
  Printlink.Text = "Export to pdf";
  dataGridView2.Columns.Add(Printlink);
}

//Binding Gridview <!--[if !supportLineBreakNewLine]--><!--[endif]-->
public DataTable binddata()
{
  DataTable dt = new DataTable();
  string query = "select * from cardetail";
  SqlCommand cmd = new SqlCommand(query, cn);
  SqlDataAdaptersa = new SqlDataAdapter();
  sa.SelectCommand = cmd;
  cn.Open();
  cmd.ExecuteNonQuery();
  sa.Fill(dt);
  dataGridView2.DataSource = dt;
  dataGridView2.AutoGenerateColumns = false;
  dataGridView2.AllowUserToAddRows = false;
  cn.Close();
  returndt;
}

//Edit Delete Event <!--[if !supportLineBreakNewLine]--><!--[endif]-->
private void dataGridView2_CellContentClick(object sender, DataGridViewCellEventArgs e)
{
  SqlCommand cmd;
  SqlCommand Command;
  SqlDataReader Reader;
  try
  {
    empid = Convert.ToInt32(dataGridView2.Rows[e.RowIndex].Cells["id"].Value);
    switch (e.ColumnIndex)
    {
      case 0:
        cn.Open();
        Command = new SqlCommand("Select * from cardetail where id='" + empid + "'", cn);
        Reader = Command.ExecuteReader();
        if (Reader.HasRows)
        {
          if (Reader.Read())
          {
            textBox8.Text = Reader.GetValue(0).ToString();
            textBox9.Text = Reader.GetValue(1).ToString();
            textBox10.Text = Reader.GetValue(2).ToString();
            textBox11.Text = Reader.GetValue(3).ToString();
            textBox12.Text = Reader.GetValue(4).ToString();
            textBox13.Text = Reader.GetValue(5).ToString();
            textBox14.Text = Reader.GetValue(6).ToString();

            button4.Visible = true;
            button3.Visible = false;
          }
        }
        cn.Close();
      break;
      case 1:
        cn.Open();
        cmd = new SqlCommand("delete from cardetail where id = '" + empid + "'", cn);
        cmd.ExecuteNonQuery();
        cn.Close();
        MessageBox.Show("Deleted Successfully.....");
        binddata();
      break;
      case 2:
        cn.Open();
        Command = new SqlCommand("Select * from cardetail where id='" + empid + "'", cn);
        Reader = Command.ExecuteReader();
        GenerateBillAndExport(Reader);
        cn.Close();
      break;
    }
  }
  catch (Exception ex)
  {
    MessageBox.Show(ex.Message);
  }
}

//Update Button Click <!--[if !supportLineBreakNewLine]--><!--[endif]-->
private void button4_Click(object sender, EventArgs e)
{
  string a = DateTime.Now.ToShortDateString();
  string query = "update cardetail set carno='" + textBox8.Text + "',carname='" + textBox9.Text + "',address='" + textBox10.Text + "',personname='" + textBox11.Text + "',cellno='" + textBox12.Text + "',detail='" + textBox13.Text + "',total='" +   Convert.ToDouble(textBox14.Text) + "' where id='" + empid + "'";
  SqlCommand cmd = new SqlCommand(query, cn);
  cn.Open();
  cmd.ExecuteNonQuery();
  MessageBox.Show("Record Updates Successfully.....");
  cn.Close();
  //clear();
  binddata();
  button3.Visible = true;
  button4.Visible = false;
}

private void Form1_Load(object sender, EventArgs e)
{
  // TODO: This line of code loads data into the 'uHDataSet1.cardetail' table. You can move, or remove it, as needed.
  this.cardetailTableAdapter1.Fill(this.uHDataSet1.cardetail);
  // TODO: This line of code loads data into the 'uHDataSet.cardetail' table. You can move, or remove it, as needed.
  // this.cardetailTableAdapter.Fill(this.uHDataSet.cardetail);
  this.binddata();
}

//Insert button Code
private void button3_Click(object sender, EventArgs e)
{
  string a = DateTime.Now.ToShortDateString();
  string query = "insert into cardetail values(@carno,@carname,@address,@personname,@cellno,@detail,@total)";
  SqlCommand cmd = new SqlCommand(query, cn);
  cmd.Parameters.AddWithValue("@carno", textBox8.Text);
  cmd.Parameters.AddWithValue("@carname", textBox9.Text);
  cmd.Parameters.AddWithValue("@address", textBox10.Text);
  cmd.Parameters.AddWithValue("@personname", textBox11.Text);
  cmd.Parameters.AddWithValue("@cellno", textBox12.Text);
  cmd.Parameters.AddWithValue("@detail", textBox13.Text);
  cmd.Parameters.AddWithValue("@total", textBox14.Text);
  cn.Open();
  cmd.ExecuteNonQuery();
  MessageBox.Show("Record Inserted Successfully.....");
  cn.Close();
  //clear();
  binddata();
  button3.Visible = false;
  button4.Visible = true;
}

Related Posts

Previous
Next Post »

Thanks for comments.....