Email: Password:       Forgot Password 
A Saarsha Group Online Community for dot net codes group like C#, Asp.NET, VB.NET, Sharepoint, JavaScript, JQuery, Ajax, SQL, WCF, WPF.

Export Grid View Template Column To PDF

Viewed:  2492 
Posted On:  19/05/2015 20:55:23 
How we can Export Grid View Template Column To PDF ? 

In this article I am going to show how we can export our Grid View to PDF. Mean we can have any type of column in a Grid View by using Template column like Link, Drop Down, Radio button and check box list. So how we can export those all into a PDF file. We will learn this here.

I got a business requirement to design a form below and get export this into PDF.

Below is my SQL Server Table in Design mode:


Image 1.

Script of my table:

CREATE TABLE [dbo].[Employee](
          [ID] [int] IDENTITY(1,1) NOT NULL,
          [Name] [varchar](50) NULL,
          [Email] [varchar](500) NULL,
          [Country] [varchar](50) NULL

Here to export Grid View Data to PDF we need to add a reference of iTextSharp like below:




Image 2.


Now below is my aspx code:


<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Default.aspx.cs" Inherits="ExportGridViewTemplateColumnToPDF.Default" %>
<!DOCTYPE html>
<html xmlns="">
<head runat="server">
    <title>Export Grid View Template Column (Link, Drop Down List, Radio Button, Check Box List) To PDF</title>
    <form id="form1" runat="server">
            <asp:GridView ID="GridView1" HeaderStyle-BackColor="#666666" HeaderStyle-ForeColor="White" Font-Names="Verdana"
                RowStyle-BackColor="#E4E4E4" runat="server" AutoGenerateColumns="False" CellPadding="4" ForeColor="#333333" GridLines="None">
                <AlternatingRowStyle BackColor="White" ForeColor="#284775" Font-Names="Verdana" />
                    <asp:BoundField DataField="Id" HeaderText="Id" ItemStyle-Width="30px">
                        <ItemStyle Width="30px"></ItemStyle>
                    <asp:TemplateField HeaderText="Name">
                            <asp:HyperLink ID="lnkName" runat="server" NavigateUrl="#" Text='<%# Eval("Name") %>'></asp:HyperLink>
                    <asp:TemplateField HeaderText="Email">
                            <asp:TextBox ID="txtEmail" runat="server" Text='<%# Eval("Email") %>'></asp:TextBox>
                    <asp:TemplateField HeaderText="Country">
                            <asp:TextBox ID="txtCountry" runat="server" Text='<%# Eval("Country") %>'></asp:TextBox>
                    <asp:TemplateField HeaderText="Reporting Manager">
                            <asp:DropDownList ID="ddlManager" runat="server">
                                <asp:ListItem Text="Shambhu Sharma" Value="Shambhu Sharma" />
                                <asp:ListItem Text="Amol Malhotra" Value="Amol Malhotra" />
                                <asp:ListItem Text="Manu Khanna" Value="Manu Khanna" />
                    <asp:TemplateField HeaderText="Designation" ItemStyle-ForeColor="Red" ItemStyle-Font-Size="10pt">
                            <asp:CheckBoxList ID="chkDesignation" runat="server" RepeatColumns="3" RepeatDirection="Horizontal">
                                <asp:ListItem Text="Softwate Developer" Value="Softwate Developer" Selected="True" />
                                <asp:ListItem Text="Technical Analyst" Value="Technical Analyst" />
                                <asp:ListItem Text="Consultant" Value="Consultant" />
                                <asp:ListItem Text="Solution Architect" Value="Solution Architect" />
                                <asp:ListItem Text="Project Manager" Value="Project Manager" />
                    <asp:TemplateField HeaderText="Experience" ItemStyle-ForeColor="Blue" ItemStyle-Font-Size="10pt">
                            <asp:RadioButtonList ID="rblExperience" runat="server" RepeatColumns="2" RepeatDirection="Horizontal">
                                <asp:ListItem Text="1-2 Years" Value="1-2 Years" Selected="True" />
                                <asp:ListItem Text="2-4 Years" Value="2-4 Years" />
                                <asp:ListItem Text="4-6 Years" Value="4-6 Years" />
                                <asp:ListItem Text="10+ Years" Value="10+ Years" />
                <EditRowStyle BackColor="#999999" />
                <FooterStyle BackColor="#5D7B9D" Font-Bold="True" ForeColor="White" />
                <HeaderStyle BackColor="#5D7B9D" ForeColor="White" Font-Bold="True"></HeaderStyle>
                <PagerStyle BackColor="#284775" ForeColor="White" HorizontalAlign="Center" />
                <RowStyle BackColor="#F7F6F3" ForeColor="#333333"></RowStyle>
                <SelectedRowStyle BackColor="#E2DED6" Font-Bold="True" ForeColor="#333333" />
                <SortedAscendingCellStyle BackColor="#E9E7E2" />
                <SortedAscendingHeaderStyle BackColor="#506C8C" />
                <SortedDescendingCellStyle BackColor="#FFFDF8" />
                <SortedDescendingHeaderStyle BackColor="#6F8DAE" />
            <br />
            <asp:Button ID="btnGridViewExport" runat="server" Text="Export To PDF" OnClick="btnGridViewExport_ExportToPDF" />

Now my aspx.cs code is:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.IO;
using System.Data;
using iTextSharp.text.pdf;
using iTextSharp.text.html.simpleparser;
using System.Configuration;
using System.Data.SqlClient;
namespace ExportGridViewTemplateColumnToPDF
    public partial class Default : System.Web.UI.Page
        protected void Page_Load(object sender, EventArgs e)
            if (!this.IsPostBack)
        private void BindEmployees()
            string constr = ConfigurationManager.ConnectionStrings["RConnection"].ConnectionString;
            using (SqlConnection con = new SqlConnection(constr))
                using (SqlCommand cmd = new SqlCommand("SELECT * FROM Employee ORDER BY ID"))
                    using (SqlDataAdapter da = new SqlDataAdapter())
                        DataTable dt = new DataTable();
                        cmd.CommandType = CommandType.Text;
                        cmd.Connection = con;
                        da.SelectCommand = cmd;
                        GridView1.DataSource = dt;
        protected void btnGridViewExport_ExportToPDF(object sender, EventArgs e)
            using (StringWriter sw = new StringWriter())
                HtmlTextWriter hw = new HtmlTextWriter(sw);
                foreach (TableCell cell in GridView1.HeaderRow.Cells)
                    cell.BackColor = GridView1.HeaderStyle.BackColor;
                foreach (GridViewRow row in GridView1.Rows)
                    foreach (TableCell cell in row.Cells)
                        cell.BackColor = GridView1.RowStyle.BackColor;
                        List<Control> controls = new List<Control>();

                        foreach (Control control in cell.Controls)

                        foreach (Control control in controls)
                            switch (control.GetType().Name)
                                case "HyperLink":
                                    cell.Controls.Add(new Literal { Text = (control as HyperLink).Text });
                                case "TextBox":
                                    cell.Controls.Add(new Literal { Text = (control as TextBox).Text });
                                case "LinkButton":
                                    cell.Controls.Add(new Literal { Text = (control as LinkButton).Text });
                                case "DropDownList":
                                    cell.Controls.Add(new Literal { Text = (control as DropDownList).SelectedItem.Text });
                                case "CheckBoxList":
                                    foreach (ListItem item in (control as CheckBoxList).Items)
                                        if (item.Selected)
                                            cell.Controls.Add(new Literal { Text = item.Text + " " });
                                case "RadioButtonList":
                                    cell.Controls.Add(new Literal { Text = (control as RadioButtonList).SelectedItem.Text });
                StringReader sr = new StringReader(sw.ToString());
                iTextSharp.text.Document pdfDoc = new iTextSharp.text.Document(iTextSharp.text.PageSize.A4, 10f, 10f, 10f, 0f);
                HTMLWorker htmlparser = new HTMLWorker(pdfDoc);
                PdfWriter.GetInstance(pdfDoc, Response.OutputStream);
                Response.ContentType = "application/pdf";
                Response.AddHeader("content-disposition", "attachment;filename=GridViewExport.pdf");
        public override void VerifyRenderingInServerForm(Control control)
            /* Verifies that the control is rendered */

Below is my web.config file where I define my connection string:

<?xml version="1.0"?>
  For more information on how to configure your ASP.NET application, please visit
    <compilation debug="true" targetFramework="4.5" />
    <httpRuntime targetFramework="4.5" />
    <add name="RConnection" connectionString="Server=INDIA\MSSQLServer2k8;database=TestDB;UID=sa; pwd=india;"/>

Now run the application:


Image 3.

Now you can change the value from Drop Down List, Radio Button or Check Box List like below:


Image 4.


Image 5.


Image 6.

You can make change in your from and do export again:


Image 7.

         HOME   |   Submit Article   |   Contact Us   |   About Us   |   Terms & Condition   |   Advertise With us