Export GridView Template Column To PDF

We can have any type of column in a Grid View by using a Template column like Link, Drop Down, Radio button and check box list. So how to export all those into a PDF file? We will learn how to do that here.

I got a business requirement to design a form as in the following and export this into a PDF.

The following is my SQL Server Table in Design mode:



Script of my table

  1. CREATE TABLE [dbo].[Employee]  
  2. (  
  3. [ID] [int] IDENTITY(11) NOT NULL,  
  4. [Name] [varchar](50) NULL,  
  5. [Email] [varchar](500) NULL,  
  6. [Country] [varchar](50) NULL  
  7. ) ON [PRIMARY] GO  

Here, to export the Grid View Data to a PDF we need to add a reference of iTextSharp as in the following:



aspx code

Now the following is my aspx code:

  1. <%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Default.aspx.cs" Inherits="ExportGridViewTemplateColumnToPDF.Default" %>  
  2. <!DOCTYPE html>  
  3. <html  
  4.     xmlns="http://www.w3.org/1999/xhtml">  
  5.     <head runat="server">  
  6.         <title>Export Grid View Template Column (Link, Drop Down List, Radio Button, Check Box List) To PDF</title>  
  7.     </head>  
  8.     <body>  
  9.         <form id="form1" runat="server">  
  10.             <div>  
  11.                 <asp:GridView ID="GridView1" HeaderStyle-BackColor="#666666" HeaderStyle-ForeColor="White" Font-Names="Verdana"  
  12. RowStyle-BackColor="#E4E4E4" runat="server" AutoGenerateColumns="False" CellPadding="4" ForeColor="#333333" GridLines="None">  
  13.                     <AlternatingRowStyle BackColor="White" ForeColor="#284775" Font-Names="Verdana" />  
  14.                     <Columns>  
  15.                         <asp:BoundField DataField="Id" HeaderText="Id" ItemStyle-Width="30px">  
  16.                             <ItemStyle Width="30px"></ItemStyle>  
  17.                         </asp:BoundField>  
  18.                         <asp:TemplateField HeaderText="Name">  
  19.                             <ItemTemplate>  
  20.                                 <asp:HyperLink ID="lnkName" runat="server" NavigateUrl="#" Text='<%# Eval("Name") %>'>  
  21.                                 </asp:HyperLink>  
  22.                             </ItemTemplate>  
  23.                         </asp:TemplateField>  
  24.                         <asp:TemplateField HeaderText="Email">  
  25.                             <ItemTemplate>  
  26.                                 <asp:TextBox ID="txtEmail" runat="server" Text='<%# Eval("Email") %>'>  
  27.                                 </asp:TextBox>  
  28.                             </ItemTemplate>  
  29.                         </asp:TemplateField>  
  30.                         <asp:TemplateField HeaderText="Country">  
  31.                             <ItemTemplate>  
  32.                                 <asp:TextBox ID="txtCountry" runat="server" Text='<%# Eval("Country") %>'>  
  33.                                 </asp:TextBox>  
  34.                             </ItemTemplate>  
  35.                         </asp:TemplateField>  
  36.                         <asp:TemplateField HeaderText="Reporting Manager">  
  37.                             <ItemTemplate>  
  38.                                 <asp:DropDownList ID="ddlManager" runat="server">  
  39.                                     <asp:ListItem Text="Shambhu Sharma" Value="Shambhu Sharma" />  
  40.                                     <asp:ListItem Text="Amol Malhotra" Value="Amol Malhotra" />  
  41.                                     <asp:ListItem Text="Manu Khanna" Value="Manu Khanna" />  
  42.                                 </asp:DropDownList>  
  43.                             </ItemTemplate>  
  44.                         </asp:TemplateField>  
  45.                         <asp:TemplateField HeaderText="Designation" ItemStyle-ForeColor="Red" ItemStyle-Font-Size="10pt">  
  46.                             <ItemTemplate>  
  47.                                 <asp:CheckBoxList ID="chkDesignation" runat="server" RepeatColumns="3" RepeatDirection="Horizontal">  
  48.                                     <asp:ListItem Text="Softwate Developer" Value="Softwate Developer" Selected="True" />  
  49.                                     <asp:ListItem Text="Technical Analyst" Value="Technical Analyst" />  
  50.                                     <asp:ListItem Text="Consultant" Value="Consultant" />  
  51.                                     <asp:ListItem Text="Solution Architect" Value="Solution Architect" />  
  52.                                     <asp:ListItem Text="Project Manager" Value="Project Manager" />  
  53.                                 </asp:CheckBoxList>  
  54.                             </ItemTemplate>  
  55.                         </asp:TemplateField>  
  56.                         <asp:TemplateField HeaderText="Experience" ItemStyle-ForeColor="Blue" ItemStyle-Font-Size="10pt">  
  57.                             <ItemTemplate>  
  58.                                 <asp:RadioButtonList ID="rblExperience" runat="server" RepeatColumns="2" RepeatDirection="Horizontal">  
  59.                                     <asp:ListItem Text="1-2 Years" Value="1-2 Years" Selected="True" />  
  60.                                     <asp:ListItem Text="2-4 Years" Value="2-4 Years" />  
  61.                                     <asp:ListItem Text="4-6 Years" Value="4-6 Years" />  
  62.                                     <asp:ListItem Text="10+ Years" Value="10+ Years" />  
  63.                                 </asp:RadioButtonList>  
  64.                             </ItemTemplate>  
  65.                         </asp:TemplateField>  
  66.                     </Columns>  
  67.                     <EditRowStyle BackColor="#999999" />  
  68.                     <FooterStyle BackColor="#5D7B9D" Font-Bold="True" ForeColor="White" />  
  69.                     <HeaderStyle BackColor="#5D7B9D" ForeColor="White" Font-Bold="True"></HeaderStyle>  
  70.                     <PagerStyle BackColor="#284775" ForeColor="White" HorizontalAlign="Center" />  
  71.                     <RowStyle BackColor="#F7F6F3" ForeColor="#333333"></RowStyle>  
  72.                     <SelectedRowStyle BackColor="#E2DED6" Font-Bold="True" ForeColor="#333333" />  
  73.                     <SortedAscendingCellStyle BackColor="#E9E7E2" />  
  74.                     <SortedAscendingHeaderStyle BackColor="#506C8C" />  
  75.                     <SortedDescendingCellStyle BackColor="#FFFDF8" />  
  76.                     <SortedDescendingHeaderStyle BackColor="#6F8DAE" />  
  77.                 </asp:GridView>  
  78.                 <br />  
  79.                 <asp:Button ID="btnGridViewExport" runat="server" Text="Export To PDF" OnClick="btnGridViewExport_ExportToPDF" />  
  80.             </div>  
  81.         </form>  
  82.     </body>  
  83. </html>

aspx.cs code

Now my aspx.cs code is:

  1. using System;  
  2. using System.Collections.Generic;  
  3. using System.Linq;  
  4. using System.Web;  
  5. using System.Web.UI;  
  6. using System.Web.UI.WebControls;  
  7. using System.IO;  
  8. using System.Data;  
  9. using iTextSharp.text.pdf;  
  10. using iTextSharp.text.html.simpleparser;  
  11. using System.Configuration;  
  12. using System.Data.SqlClient;  
  13. namespace ExportGridViewTemplateColumnToPDF {  
  14.     public partial class Default: System.Web.UI.Page {  
  15.         protected void Page_Load(object sender, EventArgs e) {  
  16.             if (!this.IsPostBack) {  
  17.                 BindEmployees();  
  18.             }  
  19.         }  
  20.         private void BindEmployees() {  
  21.             string constr = ConfigurationManager.ConnectionStrings["RConnection"].ConnectionString;  
  22.             using(SqlConnection con = new SqlConnection(constr)) {  
  23.                 using(SqlCommand cmd = new SqlCommand("SELECT * FROM Employee ORDER BY ID")) {  
  24.                     using(SqlDataAdapter da = new SqlDataAdapter()) {  
  25.                         DataTable dt = new DataTable();  
  26.                         cmd.CommandType = CommandType.Text;  
  27.                         cmd.Connection = con;  
  28.                         da.SelectCommand = cmd;  
  29.                         da.Fill(dt);  
  30.                         GridView1.DataSource = dt;  
  31.                         GridView1.DataBind();  
  32.                     }  
  33.                 }  
  34.             }  
  35.         }  
  36.         protected void btnGridViewExport_ExportToPDF(object sender, EventArgs e) {  
  37.             using(StringWriter sw = new StringWriter()) {  
  38.                 HtmlTextWriter hw = new HtmlTextWriter(sw);  
  39.                 foreach(TableCell cell in GridView1.HeaderRow.Cells) {  
  40.                     cell.BackColor = GridView1.HeaderStyle.BackColor;  
  41.                 }  
  42.                 foreach(GridViewRow row in GridView1.Rows) {  
  43.                     foreach(TableCell cell in row.Cells) {  
  44.                         cell.BackColor = GridView1.RowStyle.BackColor;  
  45.                         List < Control > controls = new List < Control > ();  
  46.   
  47.                         //Add controls to be removed to Generic List  
  48.                         foreach(Control control in cell.Controls) {  
  49.                             controls.Add(control);  
  50.                         }  
  51.                         //Loop through the controls to be removed and replace then with Literal  
  52.                         foreach(Control control in controls) {  
  53.                             switch (control.GetType().Name) {  
  54.                                 case "HyperLink":  
  55.                                     cell.Controls.Add(new Literal {  
  56.                                         Text = (control as HyperLink).Text  
  57.                                     });  
  58.                                     break;  
  59.                                 case "TextBox":  
  60.                                     cell.Controls.Add(new Literal {  
  61.                                         Text = (control as TextBox).Text  
  62.                                     });  
  63.                                     break;  
  64.                                 case "LinkButton":  
  65.                                     cell.Controls.Add(new Literal {  
  66.                                         Text = (control as LinkButton).Text  
  67.                                     });  
  68.                                     break;  
  69.                                 case "DropDownList":  
  70.                                     cell.Controls.Add(new Literal {  
  71.                                         Text = (control as DropDownList).SelectedItem.Text  
  72.                                     });  
  73.                                     break;  
  74.                                 case "CheckBoxList":  
  75.                                     foreach(ListItem item in (control as CheckBoxList).Items) {  
  76.                                         if (item.Selected) {  
  77.                                             cell.Controls.Add(new Literal {  
  78.                                                 Text = item.Text + " "  
  79.                                             });  
  80.                                         }  
  81.                                     }  
  82.                                     break;  
  83.                                 case "RadioButtonList":  
  84.                                     cell.Controls.Add(new Literal {  
  85.                                         Text = (control as RadioButtonList).SelectedItem.Text  
  86.                                     });  
  87.                                     break;  
  88.                             }  
  89.                             cell.Controls.Remove(control);  
  90.                         }  
  91.                     }  
  92.                 }  
  93.                 GridView1.RenderControl(hw);  
  94.                 StringReader sr = new StringReader(sw.ToString());  
  95.                 iTextSharp.text.Document pdfDoc = new iTextSharp.text.Document(iTextSharp.text.PageSize.A4, 10f, 10f, 10f, 0f);  
  96.                 HTMLWorker htmlparser = new HTMLWorker(pdfDoc);  
  97.                 PdfWriter.GetInstance(pdfDoc, Response.OutputStream);  
  98.                 pdfDoc.Open();  
  99.                 htmlparser.Parse(sr);  
  100.                 pdfDoc.Close();  
  101.                 Response.ContentType = "application/pdf";  
  102.                 Response.AddHeader("content-disposition""attachment;filename=GridViewExport.pdf");  
  103.                 Response.Cache.SetCacheability(HttpCacheability.NoCache);  
  104.                 Response.Write(pdfDoc);  
  105.                 Response.End();  
  106.             }  
  107.         }  
  108.         public override void VerifyRenderingInServerForm(Control control) {  
  109.             /* Verifies that the control is rendered */  
  110.         }  
  111.     }  
  112. }  

web.config file

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

  1. <?xml version="1.0"?>  
  2. <!--  
  3. For more information on how to configure your ASP.NET application, please visit  
  4. http://go.microsoft.com/fwlink/?LinkId=169433  
  5. -->  
  6. <configuration>  
  7.     <system.web>  
  8.         <compilation debug="true" targetFramework="4.5" />  
  9.         <httpRuntime targetFramework="4.5" />  
  10.     </system.web>  
  11.     <connectionStrings>  
  12.         <add name="RConnection" connectionString="Server=INDIA\MSSQLServer2k8;database=TestDB;UID=sa; pwd=india;"/>  
  13.     </connectionStrings>  
  14. </configuration>  

Test

Now run the application.



Now you can change the value from Drop Down List, Radio Button or Check Box List as in the following:







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


Similar Articles