Export GridView In Excel And PDF Using Stored Procedure In ASP.NET In Real-Time

Introduction
 
A Grid View is a graphical control element that presents a Tabular View of data. A typical Grid View also supports some or all of the following: Clicking a column header to change the sort order of the grid. Dragging column headers to change their size and their order.

The GridView control displays the values of a data source in a table. Each column represents a field, while each row represents a record.

Description
 
This article shows you how to export GridView records in Excel and PDF. Before that, read my previus article carefully.

http://www.c-sharpcorner.com/article/crud-using-stored-procedure-in-asp-net-gridview-real-time/


Only a small modification is added in this article for exporting image buttons. So, there is no need to describe same things as I described in my previous article.

Steps to be Followed
 
Step1

I have created one ASP.NET web application named "GridViewDemo". Then, add an ASP.NET web page named "GridViewDemo.aspx". Then add images in Images folder (check attached file).

Code ref for GridViewDemo.aspx,
  1. <%@ Page Language="C#" AutoEventWireup="true" CodeBehind="GridViewDemo.aspx.cs" Inherits="GridViewDemo.GridViewDemo" %>  
  2.   
  3. <!DOCTYPE html>  
  4. <html xmlns="http://www.w3.org/1999/xhtml">  
  5. <head runat="server">  
  6.     <title>Satyaprakash Samantaray</title>  
  7. <%--Botstrap Part--%>  
  8.     <style>  
  9.         .button {  
  10.             background-color: #4CAF50;  
  11.             border: none;  
  12.             color: white;  
  13.             padding: 15px 32px;  
  14.             text-align: center;  
  15.             text-decoration: none;  
  16.             display: inline-block;  
  17.             font-size: 16px;  
  18.             margin: 4px 2px;  
  19.             cursor: pointer;  
  20.         }  
  21.       .DataGridFixedHeader {  
  22.     color: White;  
  23.     font-size: 13px;  
  24.     font-family: Verdana;   
  25.     background-color:yellow  
  26. }  
  27.         .grid_item {  
  28.      
  29.     background-color: #E3EAEB;  
  30.     border-width: 1px;  
  31.     font-family: Verdana;  
  32.     border-style: solid;  
  33.     font-size: 12pt;  
  34.     color: black;  
  35.     border: 1px solid black;  
  36. }  
  37.         .grid_alternate {  
  38.     border-width: 1px;  
  39.     font-family: Verdana;  
  40.     border-style: solid;  
  41.     font-size: 12pt;  
  42.     color: black;  
  43.     background-color: White;  
  44. }  
  45.   
  46.         .button4 {  
  47.             border-radius: 9px;  
  48.         }  
  49.   
  50.        
  51.         input[type=text], select {  
  52.         width: 40%;  
  53.         padding: 12px 20px;  
  54.         margin: 10px 0;  
  55.         display: inline-block;  
  56.         border: 1px solid #ccc;  
  57.         border-radius: 4px;  
  58.         box-sizing: border-box;  
  59.         font-family: 'Montserrat', sans-serif;    
  60.         text-indent: 10px;    
  61.         color: blue;    
  62.         text-shadow: 0 1px 2px rgba(0, 0, 0, 0.3);    
  63.         font-size: 20px;    
  64.     }  
  65.     </style>  
  66. <%--Botstrap Part--%>  
  67.   
  68. </head>  
  69. <body>  
  70.     <form id="form1" runat="server">  
  71.   <fieldset>  
  72.     <legend style="font-family: Arial Black;background-color:yellow; color:red; font-size:larger;font-style: oblique">Satyaprakash's Real-Time Project</legend>  
  73.                 <table align="center">  
  74.                     <tr>  
  75.                         <td colspan="2" align="center" class="auto-style1">  
  76.                             <h2 style="background-color: Yellow;color: Blue; text-align: center; font-style: oblique">Satyaprakash's Real-Time GridView Export Excel and Pdf In Asp.Net</h2>  
  77.                         </td>  
  78.                     </tr>   
  79.                     <tr>                                           
  80.                         <td style="text-align:center">  
  81.                             <asp:TextBox runat="server" ID="txtFirstName" placeholder="Enter First Name.." ValidationGroup="add" ></asp:TextBox>  
  82.                         </td>  
  83.                     </tr>  
  84.                     <tr>  
  85.                           
  86.                         <td style="text-align:center">  
  87.                             <asp:TextBox runat="server" ID="txtLastName" placeholder="Enter Last Name.." ValidationGroup="add" ></asp:TextBox>  
  88.                         </td>  
  89.                     </tr>  
  90.                     <tr>  
  91.                          
  92.                         <td style="text-align:center">  
  93.                             <asp:TextBox runat="server" placeholder="Enter Phone Number.." ID="txtPhoneNumber" ValidationGroup="add"></asp:TextBox>  
  94.                         </td>  
  95.                         <td></td>  
  96.                     </tr>  
  97.                     <tr>  
  98.                          
  99.                         <td style="text-align:center">  
  100.                             <asp:TextBox runat="server" ID="txtEmailAddress" placeholder="Enter Email Address.." ValidationGroup="add" ></asp:TextBox>  
  101.                         </td>  
  102.                     </tr>  
  103.                     <tr>  
  104.                         
  105.                         <td style="text-align:center">  
  106.                             <asp:TextBox runat="server" ID="txtSalary" placeholder="Enter Salary.." ValidationGroup="add" ></asp:TextBox>  
  107.                         </td>  
  108.                     </tr>  
  109.                     <tr>  
  110.                         <td colspan="2" align="center">  
  111.                             <asp:Button runat="server" ID="btnAddEmployee" Text="Add" OnClick="btnAddEmployee_Click" class="button button4"  ValidationGroup="add"/>  
  112.                             <asp:Button runat="server" ID="btnUpdate" Text="Update" class="button button4" OnClick="btnUpdate_Click"/>  
  113.                             <asp:Button runat="server" ID="btnReset" Text="Reset"  class="button button4" OnClick="btnReset_Click"/>  
  114.                         </td>  
  115.                     </tr>  
  116.                     <tr>  
  117.                         <td colspan="2" align="center">  
  118.                             <br />  
  119.                             <asp:Label runat="server" ID="lblMessage"></asp:Label>  
  120.                             <br />  
  121.                             <br />  
  122.                         </td>  
  123.                     </tr>  
  124.                       <tr runat="server" style="height: 3px">  
  125.                         <td align="center" colspan="2" style="background-color:yellowgreen;width: 100%;">  
  126.                            <span style="font-family: Arial Black;color:red; font-size:larger;font-style: oblique">Export EXCEL</span>                                                                                                                                                                                                                                                                             
  127.                            <asp:ImageButton ID="ibtnExcel" runat="server" AlternateText="Click here to Export to Excel" BorderColor="black" ImageAlign="Middle" ImageUrl="~/Images/Excel.gif"  Style="height: 30px" ToolTip="Click here to Export to Excel"  OnClick="ibtnExcel_Click"/>      
  128.                             <span style="font-family: Arial Black;color:red; font-size:larger;font-style: oblique">Export PDF</span>                                                                                                                                            
  129.                            <asp:ImageButton ID="ibtnPdf" runat="server" AlternateText="Click here to Export to Pdf" BorderColor="black" ImageAlign="Middle" ImageUrl="~/Images/Pdf.png"  Style="height: 20px" ToolTip="Click here to Export to Pdf" OnClick="ibtnPdf_Click" />  
  130.                                                                                                                                                                   
  131.                         </td>  
  132.                       </tr>  
  133.                     <tr>  
  134.                         <td colspan="2">  
  135.                             <asp:GridView ID="grvEmployee" runat="server" AllowPaging="true" CellPadding="2" EnableModelValidation="True"  
  136.                                         ForeColor="red" GridLines="Both" ItemStyle-HorizontalAlign="center" EmptyDataText="There Is No Records In Database!" AutoGenerateColumns="false" Width="1100px"  
  137.                                 HeaderStyle-ForeColor="blue"   OnPageIndexChanging="grvEmployee_PageIndexChanging" OnRowCancelingEdit="grvEmployee_RowCancelingEdit" OnRowDeleting="grvEmployee_RowDeleting" OnRowEditing="grvEmployee_RowEditing">  
  138.                                 <HeaderStyle CssClass="DataGridFixedHeader" />  
  139.                                 <RowStyle CssClass="grid_item" />  
  140.                                 <AlternatingRowStyle CssClass="grid_alternate" />  
  141.                                 <FooterStyle CssClass="DataGridFixedHeader" />  
  142.                                 <Columns>  
  143.                                     <asp:TemplateField HeaderText="EmpId">  
  144.                                          <HeaderStyle HorizontalAlign="Left" />  
  145.                                         <ItemStyle HorizontalAlign="Left" />  
  146.                                         <ItemTemplate>  
  147.                                             <asp:Label runat="server" ID="lblEmpId" Text='<%#Eval("id") %>'></asp:Label>  
  148.                                         </ItemTemplate>  
  149.                                     </asp:TemplateField>  
  150.                                     <asp:TemplateField HeaderText="FirstName">  
  151.                                          <HeaderStyle HorizontalAlign="Left" />  
  152.                                         <ItemStyle HorizontalAlign="Left" />  
  153.                                         <ItemTemplate>  
  154.                                             <asp:Label runat="server" ID="lblFirstName" Text='<%#Eval("FirstName") %>'></asp:Label>  
  155.                                         </ItemTemplate>  
  156.                                           
  157.                                     </asp:TemplateField>  
  158.                                     <asp:TemplateField HeaderText="LastName">  
  159.                                          <HeaderStyle HorizontalAlign="Left" />  
  160.                                         <ItemStyle HorizontalAlign="Left" />  
  161.                                         <ItemTemplate>  
  162.                                             <asp:Label runat="server" ID="lblLastName" Text='<%#Eval("LastName") %>'></asp:Label>  
  163.                                         </ItemTemplate>  
  164.                                           
  165.                                     </asp:TemplateField>  
  166.                                     <asp:TemplateField HeaderText="Phone No.">  
  167.                                          <HeaderStyle HorizontalAlign="Left" />  
  168.                                         <ItemStyle HorizontalAlign="Left" />  
  169.                                         <ItemTemplate>  
  170.                                             <asp:Label runat="server" ID="lblPhoneNumber" Text='<%#Eval("PhoneNumber") %>'></asp:Label>  
  171.                                         </ItemTemplate>  
  172.                                           
  173.                                     </asp:TemplateField>  
  174.                                     <asp:TemplateField HeaderText="Email">  
  175.                                          <HeaderStyle HorizontalAlign="Left" />  
  176.                                         <ItemStyle HorizontalAlign="Left" />  
  177.                                         <ItemTemplate>  
  178.                                             <asp:Label runat="server" ID="lblEmailAddress" Text='<%#Eval("EmailAddress") %>'></asp:Label>  
  179.                                         </ItemTemplate>  
  180.                                           
  181.                                     </asp:TemplateField>  
  182.   
  183.                                     <asp:TemplateField HeaderText="Salary">  
  184.                                          <HeaderStyle HorizontalAlign="Left" />  
  185.                                         <ItemStyle HorizontalAlign="Left" />  
  186.                                         <ItemTemplate>  
  187.                                             <asp:Label runat="server" ID="lblSalary" Text='<%#Eval("Salary") %>'></asp:Label>  
  188.                                         </ItemTemplate>  
  189.                                         
  190.                                     </asp:TemplateField>  
  191.                                     <asp:TemplateField HeaderText="Update">  
  192.                                          <HeaderStyle HorizontalAlign="Left" />  
  193.                                         <ItemStyle HorizontalAlign="Left" />  
  194.                                         <ItemTemplate>  
  195.                                             <asp:LinkButton runat="server" ID="btnEdit" Text="Edit" CommandName="Edit" ToolTip="Click here to Edit the record" />                                                                                         
  196.                                         </ItemTemplate>  
  197.                                          
  198.                                     </asp:TemplateField>  
  199.                                     <asp:TemplateField HeaderText="Delete">  
  200.                                         <HeaderStyle HorizontalAlign="Left" />  
  201.                                         <ItemStyle HorizontalAlign="Left" />  
  202.                                         <ItemTemplate>                                                                          
  203.                                                 <asp:LinkButton runat="server" ID="btnDelete" Text="Delete" CommandName="Delete" OnClientClick="return confirm('Are You Sure You want to Delete the Record?');" ToolTip="Click here to Delete the record" />  
  204.                                             </span>  
  205.                                         </ItemTemplate>                                         
  206.                                     </asp:TemplateField>  
  207.                                 </Columns>  
  208.   
  209.                             </asp:GridView>  
  210.                         </td>  
  211.                     </tr>  
  212.                 </table>  
  213.       </fieldset>  
  214.     </form>  
  215. </body>  
  216.     <br />  
  217.     <br />  
  218.    <footer>    
  219.         <p style="background-color: Yellow; font-weight: bold; color:blue; text-align: center; font-style: oblique">© <script> document.write(new Date().toDateString()); </script></p>    
  220.     </footer>    
  221. </html> 
Code Description

Here, I have added two image buttons to perform export to Excel and PDF.
  1. <tr runat="server" style="height: 3px">  
  2.                         <td align="center" colspan="2" style="background-color:yellowgreen;width: 100%;">  
  3.                            <span style="font-family: Arial Black;color:red; font-size:larger;font-style: oblique">Export EXCEL</span>                                                                                                                                                                                                                                                                             
  4.                            <asp:ImageButton ID="ibtnExcel" runat="server" AlternateText="Click here to Export to Excel" BorderColor="black" ImageAlign="Middle" ImageUrl="~/Images/Excel.gif"  Style="height: 30px" ToolTip="Click here to Export to Excel"  OnClick="ibtnExcel_Click"/>      
  5.                             <span style="font-family: Arial Black;color:red; font-size:larger;font-style: oblique">Export PDF</span>                                                                                                                                            
  6.                            <asp:ImageButton ID="ibtnPdf" runat="server" AlternateText="Click here to Export to Pdf" BorderColor="black" ImageAlign="Middle" ImageUrl="~/Images/Pdf.png"  Style="height: 20px" ToolTip="Click here to Export to Pdf" OnClick="ibtnPdf_Click" />  
  7.                                                                                                                                                                   
  8.                         </td>  
  9.                       </tr> 
I have mentioned image path as -
  1. ImageUrl="~/Images/Excel.gif"  
  2. ImageUrl="~/Images/Pdf.png" 
I have added tooltip for both image buttons -
  1. ToolTip="Click here to Export to Excel"  
  2. ToolTip="Click here to Export to Pdf" 
Step2

Code ref for GridViewDemo.aspx.cs
  1. using System;  
  2. using System.Collections.Generic;  
  3. using System.Configuration;  
  4. using System.Data;  
  5. using System.Data.SqlClient;  
  6. using System.Drawing;  
  7. using System.IO;  
  8. using System.Linq;  
  9. using System.Web;  
  10. using System.Web.UI;  
  11. using System.Web.UI.WebControls;  
  12.   
  13. //namespace for pdf export.  
  14. using System.Text;  
  15. using iTextSharp.text.pdf;  
  16. using iTextSharp.text.html;  
  17. using iTextSharp.text.html.simpleparser;  
  18. using System.Web.UI.HtmlControls;  
  19.   
  20. namespace GridViewDemo  
  21. {  
  22.     public partial class GridViewDemo : System.Web.UI.Page  
  23.     {  
  24.         private string strConnectionString = ConfigurationManager.ConnectionStrings["myconnection"].ConnectionString;  
  25.         private SqlCommand _sqlCommand;  
  26.         private SqlDataAdapter _sqlDataAdapter;  
  27.         DataSet _dtSet;  
  28.         protected void Page_Load(object sender, EventArgs e)  
  29.         {  
  30.             if (!IsPostBack)  
  31.             {  
  32.                 BindEmployeeData();  
  33.                  
  34.             }  
  35.             btnUpdate.Visible = false;  
  36.             btnAddEmployee.Visible = true;  
  37.         }  
  38.         private static void ShowAlertMessage(string error)  
  39.         {  
  40.             System.Web.UI.Page page = System.Web.HttpContext.Current.Handler as System.Web.UI.Page;  
  41.             if (page != null)  
  42.             {  
  43.                 error = error.Replace("'""\'");  
  44.                 System.Web.UI.ScriptManager.RegisterStartupScript(page, page.GetType(), "err_msg""alert('" + error + "');"true);  
  45.             }  
  46.         }  
  47.         public void CreateConnection()  
  48.         {  
  49.             SqlConnection _sqlConnection = new SqlConnection(strConnectionString);  
  50.             _sqlCommand = new SqlCommand();  
  51.             _sqlCommand.Connection = _sqlConnection;  
  52.         }  
  53.         public void OpenConnection()  
  54.         {  
  55.             _sqlCommand.Connection.Open();  
  56.         }  
  57.         public void CloseConnection()  
  58.         {  
  59.             _sqlCommand.Connection.Close();  
  60.         }  
  61.         public void DisposeConnection()  
  62.         {  
  63.             _sqlCommand.Connection.Dispose();  
  64.         }  
  65.         public void BindEmployeeData()  
  66.         {  
  67.             try  
  68.             {  
  69.                 CreateConnection();  
  70.                 OpenConnection();  
  71.                 _sqlCommand.CommandText = "Sp_GridCrud";  
  72.                 _sqlCommand.CommandType = CommandType.StoredProcedure;  
  73.                 _sqlCommand.Parameters.AddWithValue("@Event""Select");  
  74.                 _sqlDataAdapter = new SqlDataAdapter(_sqlCommand);  
  75.                 _dtSet = new DataSet();  
  76.                 _sqlDataAdapter.Fill(_dtSet);  
  77.                 grvEmployee.DataSource = _dtSet;  
  78.                 grvEmployee.DataBind();  
  79.             }  
  80.             catch (Exception ex)  
  81.             {  
  82.                 Response.Redirect("The Error is " + ex);  
  83.             }  
  84.             finally  
  85.             {  
  86.                 CloseConnection();  
  87.                 DisposeConnection();  
  88.             }  
  89.         }  
  90.   
  91.         protected void btnAddEmployee_Click(object sender, EventArgs e)  
  92.         {  
  93.             try  
  94.             {  
  95.                 CreateConnection();  
  96.                 OpenConnection();  
  97.                 _sqlCommand.CommandText = "Sp_GridCrud";  
  98.                 _sqlCommand.CommandType = CommandType.StoredProcedure;  
  99.                 _sqlCommand.Parameters.AddWithValue("@Event""Add");  
  100.                 _sqlCommand.Parameters.AddWithValue("@FirstName", Convert.ToString(txtFirstName.Text.Trim()));  
  101.                 _sqlCommand.Parameters.AddWithValue("@LastName", Convert.ToString(txtLastName.Text.Trim()));  
  102.                 _sqlCommand.Parameters.AddWithValue("@PhoneNumber", Convert.ToString(txtPhoneNumber.Text.Trim()));  
  103.                 _sqlCommand.Parameters.AddWithValue("@EmailAddress", Convert.ToString(txtEmailAddress.Text.Trim()));  
  104.                 _sqlCommand.Parameters.AddWithValue("@Salary", Convert.ToDecimal(txtSalary.Text));  
  105.                 int result = Convert.ToInt32(_sqlCommand.ExecuteNonQuery());  
  106.                 if (result > 0)  
  107.                 {  
  108.                       
  109.                     ShowAlertMessage("Record Is Inserted Successfully");  
  110.                     BindEmployeeData();  
  111.                     ClearControls();  
  112.                 }  
  113.                 else  
  114.                 {  
  115.                       
  116.                     ShowAlertMessage("Failed");  
  117.                 }  
  118.             }  
  119.             catch (Exception ex)  
  120.             {  
  121.                   
  122.                 ShowAlertMessage("Check your input data");  
  123.                 
  124.             }  
  125.             finally  
  126.             {  
  127.                 CloseConnection();  
  128.                 DisposeConnection();  
  129.             }  
  130.         }  
  131.   
  132.         public void ClearControls()  
  133.         {  
  134.             txtFirstName.Text = "";  
  135.             txtLastName.Text = "";  
  136.             txtPhoneNumber.Text = "";  
  137.             txtEmailAddress.Text = "";  
  138.             txtSalary.Text = "";  
  139.         }  
  140.   
  141.         protected void grvEmployee_RowEditing(object sender, GridViewEditEventArgs e)  
  142.         {  
  143.                 btnAddEmployee.Visible = false;  
  144.                 btnUpdate.Visible = true;  
  145.              
  146.                 int RowIndex = e.NewEditIndex;  
  147.                 Label empid = (Label)grvEmployee.Rows[RowIndex].FindControl("lblEmpId");  
  148.                 Session["id"] = empid.Text;  
  149.                  
  150.                 txtFirstName.Text = ((Label)grvEmployee.Rows[RowIndex].FindControl("lblFirstName")).Text.ToString();  
  151.                 txtLastName.Text = ((Label)grvEmployee.Rows[RowIndex].FindControl("lblLastName")).Text.ToString();  
  152.                 txtPhoneNumber.Text = ((Label)grvEmployee.Rows[RowIndex].FindControl("lblPhoneNumber")).Text.ToString();  
  153.                 txtEmailAddress.Text = ((Label)grvEmployee.Rows[RowIndex].FindControl("lblEmailAddress")).Text.ToString();  
  154.                 txtSalary.Text = ((Label)grvEmployee.Rows[RowIndex].FindControl("lblSalary")).Text.ToString();  
  155.            
  156.         }  
  157.   
  158.         protected void grvEmployee_RowDeleting(object sender, GridViewDeleteEventArgs e)  
  159.         {  
  160.             try  
  161.             {  
  162.                 CreateConnection();  
  163.                 OpenConnection();  
  164.                 Label id = (Label)grvEmployee.Rows[e.RowIndex].FindControl("lblEmpId");  
  165.                 _sqlCommand.CommandText = "Sp_GridCrud";  
  166.                 _sqlCommand.Parameters.AddWithValue("@Event""Delete");  
  167.                 _sqlCommand.Parameters.AddWithValue("@EmpId", Convert.ToInt32(id.Text));  
  168.                 _sqlCommand.CommandType = CommandType.StoredProcedure;  
  169.                 int result = Convert.ToInt32(_sqlCommand.ExecuteNonQuery());  
  170.                 if (result > 0)  
  171.                 {  
  172.                       
  173.                     ShowAlertMessage("Record Is Deleted Successfully");  
  174.                     grvEmployee.EditIndex = -1;  
  175.                     BindEmployeeData();  
  176.                 }  
  177.                 else  
  178.                 {  
  179.                     lblMessage.Text = "Failed";  
  180.                     lblMessage.ForeColor = System.Drawing.Color.Red;  
  181.                     BindEmployeeData();  
  182.                 }  
  183.             }  
  184.             catch (Exception ex)  
  185.             {  
  186.                  
  187.                 ShowAlertMessage("Check your input data");  
  188.             }  
  189.             finally  
  190.             {  
  191.                 CloseConnection();  
  192.                 DisposeConnection();  
  193.             }  
  194.         }  
  195.          
  196.         protected void grvEmployee_RowCancelingEdit(object sender, GridViewCancelEditEventArgs e)  
  197.         {  
  198.             grvEmployee.EditIndex = -1;  
  199.             BindEmployeeData();  
  200.         }  
  201.   
  202.         protected void grvEmployee_PageIndexChanging(object sender, GridViewPageEventArgs e)  
  203.         {  
  204.             grvEmployee.PageIndex = e.NewPageIndex;  
  205.             BindEmployeeData();  
  206.         }  
  207.   
  208.         protected void btnReset_Click(object sender, EventArgs e)  
  209.         {  
  210.             ClearControls();  
  211.         }  
  212.   
  213.         protected void btnUpdate_Click(object sender, EventArgs e)  
  214.         {  
  215.             try  
  216.             {  
  217.                  
  218.                     CreateConnection();  
  219.                     OpenConnection();  
  220.   
  221.                     _sqlCommand.CommandText = "Sp_GridCrud";  
  222.                     _sqlCommand.CommandType = CommandType.StoredProcedure;  
  223.                     _sqlCommand.Parameters.AddWithValue("@Event""Update");  
  224.                     _sqlCommand.Parameters.AddWithValue("@FirstName", Convert.ToString(txtFirstName.Text.Trim()));  
  225.                     _sqlCommand.Parameters.AddWithValue("@LastName", Convert.ToString(txtLastName.Text.Trim()));  
  226.                     _sqlCommand.Parameters.AddWithValue("@PhoneNumber", Convert.ToString(txtPhoneNumber.Text.Trim()));  
  227.                     _sqlCommand.Parameters.AddWithValue("@EmailAddress", Convert.ToString(txtEmailAddress.Text.Trim()));  
  228.                     _sqlCommand.Parameters.AddWithValue("@Salary", Convert.ToDecimal(txtSalary.Text));  
  229.                     _sqlCommand.Parameters.AddWithValue("@EmpId", Convert.ToDecimal(Session["id"]));  
  230.   
  231.                     int result = Convert.ToInt32(_sqlCommand.ExecuteNonQuery());  
  232.                     if (result > 0)  
  233.                     {                         
  234.                         ShowAlertMessage("Record Is Updated Successfully");  
  235.                         grvEmployee.EditIndex = -1;  
  236.                         BindEmployeeData();  
  237.                         ClearControls();  
  238.                     }  
  239.                     else  
  240.                     {                         
  241.                         ShowAlertMessage("Failed");  
  242.                     }  
  243.                 }  
  244.   
  245.             catch (Exception ex)  
  246.             {                
  247.                 ShowAlertMessage("Check your input data");  
  248.             }  
  249.                 finally  
  250.                 {  
  251.                     CloseConnection();  
  252.                     DisposeConnection();  
  253.                 }  
  254.         }  
  255.   
  256.         protected void ibtnExcel_Click(object sender, ImageClickEventArgs e)  
  257.         {  
  258.             try  
  259.             {  
  260.                 GridView grvEmployee = new GridView();  
  261.                 CreateConnection();  
  262.                 OpenConnection();  
  263.                 _sqlCommand.CommandText = "Sp_GridCrud";  
  264.                 _sqlCommand.CommandType = CommandType.StoredProcedure;  
  265.                 _sqlCommand.Parameters.AddWithValue("@Event""Select");  
  266.                 _sqlDataAdapter = new SqlDataAdapter(_sqlCommand);  
  267.                 _dtSet = new DataSet();  
  268.                 _sqlDataAdapter.Fill(_dtSet);  
  269.                 grvEmployee.DataSource = _dtSet;  
  270.                 grvEmployee.DataBind();  
  271.   
  272.                 HttpContext.Current.Response.ClearContent();  
  273.                 HttpContext.Current.Response.AddHeader("content-disposition""attachment; filename=SatyaRecords.xls");  
  274.                 HttpContext.Current.Response.ContentType = "application/excel";  
  275.                 StringWriter sw = new StringWriter();  
  276.                 HtmlTextWriter htw = new HtmlTextWriter(sw);  
  277.   
  278.                 grvEmployee.HeaderRow.BackColor = Color.DarkSlateGray;  
  279.                 grvEmployee.HeaderStyle.ForeColor = Color.White;  
  280.                 grvEmployee.AlternatingRowStyle.BackColor = Color.FromArgb(227, 234, 235);  
  281.                 grvEmployee.RenderControl(htw);  
  282.   
  283.                 HttpContext.Current.Response.Write(sw.ToString());  
  284.                 HttpContext.Current.Response.Flush();  
  285.                 HttpContext.Current.Response.End();  
  286.   
  287.             }  
  288.             catch (Exception ex)  
  289.             {  
  290.                 HttpContext.Current.Response.Flush();  
  291.                 HttpContext.Current.Response.End();  
  292.             }  
  293.         }  
  294.   
  295.         protected void ibtnPdf_Click(object sender, ImageClickEventArgs e)  
  296.         {  
  297.             try  
  298.             {  
  299.                 GridView grvEmployee = new GridView();  
  300.                 CreateConnection();  
  301.                 OpenConnection();  
  302.                 _sqlCommand.CommandText = "Sp_GridCrud";  
  303.                 _sqlCommand.CommandType = CommandType.StoredProcedure;  
  304.                 _sqlCommand.Parameters.AddWithValue("@Event""Select");  
  305.                 _sqlDataAdapter = new SqlDataAdapter(_sqlCommand);  
  306.                 _dtSet = new DataSet();  
  307.                 _sqlDataAdapter.Fill(_dtSet);  
  308.                 grvEmployee.DataSource = _dtSet;  
  309.                 grvEmployee.DataBind();  
  310.   
  311.                 Response.ContentType = "application/pdf";  
  312.                 Response.AddHeader("content-disposition""attachment;filename=SatyaRecords.pdf");  
  313.                 Response.Cache.SetCacheability(HttpCacheability.NoCache);  
  314.                 StringWriter swr = new StringWriter();  
  315.                 HtmlTextWriter htmlwr = new HtmlTextWriter(swr);  
  316.                 //Mention gridview property for export to pdf.  
  317.                 grvEmployee.AllowPaging = false;  
  318.                 grvEmployee.HeaderRow.BackColor = Color.DarkSlateGray;  
  319.                 grvEmployee.AlternatingRowStyle.BackColor = Color.FromArgb(227, 234, 235);  
  320.                 grvEmployee.HeaderRow.Style.Add("font-family""Arial, Helvetica, sans-serif;");  
  321.                 grvEmployee.HeaderRow.Style.Add("font-size""8.20px");  
  322.                 grvEmployee.HeaderRow.Style.Add("color""White");  
  323.                 grvEmployee.Style.Add("font-family""Arial, Helvetica, sans-serif;");  
  324.                 grvEmployee.Style.Add("font-size""8px");  
  325.                 for (int i = 0; i < grvEmployee.Rows.Count; i++)  
  326.                 {  
  327.                     grvEmployee.Rows[i].HorizontalAlign = HorizontalAlign.Left;  
  328.                     //pdfGridView.Rows[i].VerticalAlign = VerticalAlign.Top;  
  329.                 }  
  330.                 grvEmployee.RenderControl(htmlwr);  
  331.                 StringReader srr = new StringReader(swr.ToString());  
  332.                 //iTextSharp.text.Document pdfdoc = new iTextSharp.text.Document(iTextSharp.text.PageSize.A4, 10f, 10f, 10f, 10f); //Pdf Page size and Margin types. //For Portrait   
  333.                 iTextSharp.text.Document pdfdoc = new iTextSharp.text.Document(iTextSharp.text.PageSize.A4.Rotate(), 10f, 10f, 10f, 10f); //For Landscape  
  334.                 HTMLWorker htmlparser = new HTMLWorker(pdfdoc);  
  335.                 PdfWriter.GetInstance(pdfdoc, Response.OutputStream);  
  336.                 pdfdoc.Open();  
  337.                 htmlparser.Parse(srr);  
  338.                 pdfdoc.Close();  
  339.                 Response.Write(pdfdoc);  
  340.                 Response.End();  
  341.             }  
  342.             catch (Exception ex)  
  343.             {  
  344.   
  345.             }  
  346.         }  
  347.     }  

Code Description

I have added some namespaces for PDF export.
  1. using System.Text;  
  2. using iTextSharp.text.pdf;  
  3. using iTextSharp.text.html;  
  4. using iTextSharp.text.html.simpleparser;  
  5. using System.Web.UI.HtmlControls; 
For that, I have added one DLL file named "itextsharp.dll" . A free PDF library is ported from Java iText.
 
 
 
Then, in button click event of Excel export, I have added the following code.
  1. protected void ibtnExcel_Click(object sender, ImageClickEventArgs e)  
  2.         {  
  3.             try  
  4.             {  
  5.                 GridView grvEmployee = new GridView();  
  6.                 CreateConnection();  
  7.                 OpenConnection();  
  8.                 _sqlCommand.CommandText = "Sp_GridCrud";  
  9.                 _sqlCommand.CommandType = CommandType.StoredProcedure;  
  10.                 _sqlCommand.Parameters.AddWithValue("@Event""Select");  
  11.                 _sqlDataAdapter = new SqlDataAdapter(_sqlCommand);  
  12.                 _dtSet = new DataSet();  
  13.                 _sqlDataAdapter.Fill(_dtSet);  
  14.                 grvEmployee.DataSource = _dtSet;  
  15.                 grvEmployee.DataBind();  
  16.   
  17.                 HttpContext.Current.Response.ClearContent();  
  18.                 HttpContext.Current.Response.AddHeader("content-disposition""attachment; filename=SatyaRecords.xls");  
  19.                 HttpContext.Current.Response.ContentType = "application/excel";  
  20.                 StringWriter sw = new StringWriter();  
  21.                 HtmlTextWriter htw = new HtmlTextWriter(sw);  
  22.   
  23.                 grvEmployee.HeaderRow.BackColor = Color.DarkSlateGray;  
  24.                 grvEmployee.HeaderStyle.ForeColor = Color.White;  
  25.                 grvEmployee.AlternatingRowStyle.BackColor = Color.FromArgb(227, 234, 235);  
  26.                 grvEmployee.RenderControl(htw);  
  27.   
  28.                 HttpContext.Current.Response.Write(sw.ToString());  
  29.                 HttpContext.Current.Response.Flush();  
  30.                 HttpContext.Current.Response.End();  
  31.   
  32.             }  
  33.             catch (Exception ex)  
  34.             {  
  35.                 HttpContext.Current.Response.Flush();  
  36.                 HttpContext.Current.Response.End();  
  37.             }  
  38.         } 
Here, I have created a dynamic object for GridView and put stored procedure and  appropriate ADO.NET related objects to fetch data.
  1. GridView grvEmployee = new GridView();  
  2.                 CreateConnection();  
  3.                 OpenConnection();  
  4.                 _sqlCommand.CommandText = "Sp_GridCrud";  
  5.                 _sqlCommand.CommandType = CommandType.StoredProcedure;  
  6.                 _sqlCommand.Parameters.AddWithValue("@Event""Select");  
  7.                 _sqlDataAdapter = new SqlDataAdapter(_sqlCommand);  
  8.                 _dtSet = new DataSet();  
  9.                 _sqlDataAdapter.Fill(_dtSet);  
  10.                 grvEmployee.DataSource = _dtSet;  
  11.                 grvEmployee.DataBind(); 
Then, I have added some style to GridView.
  1. grvEmployee.HeaderRow.BackColor = Color.DarkSlateGray;  
  2.                 grvEmployee.HeaderStyle.ForeColor = Color.White;  
  3.                 grvEmployee.AlternatingRowStyle.BackColor = Color.FromArgb(227, 234, 235);  
  4.                 grvEmployee.RenderControl(htw); 
Then, I added code for export to Excel with specified Excel sheet name.
  1. HttpContext.Current.Response.ClearContent();  
  2.                 HttpContext.Current.Response.AddHeader("content-disposition""attachment; filename=SatyaRecords.xls");  
  3.                 HttpContext.Current.Response.ContentType = "application/excel";  
  4.                 StringWriter sw = new StringWriter();  
  5.                 HtmlTextWriter htw = new HtmlTextWriter(sw);  
  6.   
  7. HttpContext.Current.Response.Write(sw.ToString());  
  8.                 HttpContext.Current.Response.Flush();  
  9.                 HttpContext.Current.Response.End(); 
Note - Response.Flush forces all currently buffered output to be sent to the client. The Flush method can be called multiple times during the request processing.

Response.End sends all the currently buffered output to the client, stops execution of the page, and raises the EndRequest event.

You should try using this code if you are not doing any processing on the page after Response.Write and want to stop processing the page.
  1. context.HttpContext.Response.Clear();  
  2.     context.HttpContext.Response.Write(htmlString);                
  3.     context.HttpContext.Response.Flush(); // send all buffered output to client   
  4.     context.HttpContext.Response.End(); // response.end would work fine now. 
In the PDF button click event, I have added code for Export data to PDF format.
  1. protected void ibtnPdf_Click(object sender, ImageClickEventArgs e)  
  2.         {  
  3.             try  
  4.             {  
  5.                 GridView grvEmployee = new GridView();  
  6.                 CreateConnection();  
  7.                 OpenConnection();  
  8.                 _sqlCommand.CommandText = "Sp_GridCrud";  
  9.                 _sqlCommand.CommandType = CommandType.StoredProcedure;  
  10.                 _sqlCommand.Parameters.AddWithValue("@Event""Select");  
  11.                 _sqlDataAdapter = new SqlDataAdapter(_sqlCommand);  
  12.                 _dtSet = new DataSet();  
  13.                 _sqlDataAdapter.Fill(_dtSet);  
  14.                 grvEmployee.DataSource = _dtSet;  
  15.                 grvEmployee.DataBind();  
  16.   
  17.                 Response.ContentType = "application/pdf";  
  18.                 Response.AddHeader("content-disposition""attachment;filename=SatyaRecords.pdf");  
  19.                 Response.Cache.SetCacheability(HttpCacheability.NoCache);  
  20.                 StringWriter swr = new StringWriter();  
  21.                 HtmlTextWriter htmlwr = new HtmlTextWriter(swr);  
  22.                 //Mention gridview property for export to pdf.  
  23.                 grvEmployee.AllowPaging = false;  
  24.                 grvEmployee.HeaderRow.BackColor = Color.DarkSlateGray;  
  25.                 grvEmployee.AlternatingRowStyle.BackColor = Color.FromArgb(227, 234, 235);  
  26.                 grvEmployee.HeaderRow.Style.Add("font-family""Arial, Helvetica, sans-serif;");  
  27.                 grvEmployee.HeaderRow.Style.Add("font-size""8.20px");  
  28.                 grvEmployee.HeaderRow.Style.Add("color""White");  
  29.                 grvEmployee.Style.Add("font-family""Arial, Helvetica, sans-serif;");  
  30.                 grvEmployee.Style.Add("font-size""8px");  
  31.                 for (int i = 0; i < grvEmployee.Rows.Count; i++)  
  32.                 {  
  33.                     grvEmployee.Rows[i].HorizontalAlign = HorizontalAlign.Left;  
  34.                     //pdfGridView.Rows[i].VerticalAlign = VerticalAlign.Top;  
  35.                 }  
  36.                 grvEmployee.RenderControl(htmlwr);  
  37.                 StringReader srr = new StringReader(swr.ToString());  
  38.                 //iTextSharp.text.Document pdfdoc = new iTextSharp.text.Document(iTextSharp.text.PageSize.A4, 10f, 10f, 10f, 10f); //Pdf Page size and Margin types. //For Portrait   
  39.                 iTextSharp.text.Document pdfdoc = new iTextSharp.text.Document(iTextSharp.text.PageSize.A4.Rotate(), 10f, 10f, 10f, 10f); //For Landscape  
  40.                 HTMLWorker htmlparser = new HTMLWorker(pdfdoc);  
  41.                 PdfWriter.GetInstance(pdfdoc, Response.OutputStream);  
  42.                 pdfdoc.Open();  
  43.                 htmlparser.Parse(srr);  
  44.                 pdfdoc.Close();  
  45.                 Response.Write(pdfdoc);  
  46.                 Response.End();  
  47.             }  
  48.             catch (Exception ex)  
  49.             {  
  50.   
  51.             }  
  52.         } 
Here, I have created a dynamic object for GridView and put stored procedure and appropriate ADO.NET related objects to fetch data.
  1. GridView grvEmployee = new GridView();  
  2.                 CreateConnection();  
  3.                 OpenConnection();  
  4.                 _sqlCommand.CommandText = "Sp_GridCrud";  
  5.                 _sqlCommand.CommandType = CommandType.StoredProcedure;  
  6.                 _sqlCommand.Parameters.AddWithValue("@Event""Select");  
  7.                 _sqlDataAdapter = new SqlDataAdapter(_sqlCommand);  
  8.                 _dtSet = new DataSet();  
  9.                 _sqlDataAdapter.Fill(_dtSet);  
  10.                 grvEmployee.DataSource = _dtSet;  
  11.                 grvEmployee.DataBind(); 
Then, I added some style to GridView.
  1. grvEmployee.AllowPaging = false;  
  2.                 grvEmployee.HeaderRow.BackColor = Color.DarkSlateGray;  
  3.                 grvEmployee.AlternatingRowStyle.BackColor = Color.FromArgb(227, 234, 235);  
  4.                 grvEmployee.HeaderRow.Style.Add("font-family""Arial, Helvetica, sans-serif;");  
  5.                 grvEmployee.HeaderRow.Style.Add("font-size""8.20px");  
  6.                 grvEmployee.HeaderRow.Style.Add("color""White");  
  7.                 grvEmployee.Style.Add("font-family""Arial, Helvetica, sans-serif;");  
  8.                 grvEmployee.Style.Add("font-size""8px");  
  9.                 for (int i = 0; i < grvEmployee.Rows.Count; i++)  
  10.                 {  
  11.                     grvEmployee.Rows[i].HorizontalAlign = HorizontalAlign.Left;  
  12.                     //pdfGridView.Rows[i].VerticalAlign = VerticalAlign.Top;  
  13.                 } 
 Then, I added code for Export to PDF with specified PDF name.
  1. Response.ContentType = "application/pdf";  
  2.                 Response.AddHeader("content-disposition""attachment;filename=SatyaRecords.pdf");  
  3.                 Response.Cache.SetCacheability(HttpCacheability.NoCache);  
  4.                 StringWriter swr = new StringWriter();  
  5.                 HtmlTextWriter htmlwr = new HtmlTextWriter(swr);  
  6.   
  7. for (int i = 0; i < grvEmployee.Rows.Count; i++)  
  8.                 {  
  9.                     grvEmployee.Rows[i].HorizontalAlign = HorizontalAlign.Left;  
  10.                     //pdfGridView.Rows[i].VerticalAlign = VerticalAlign.Top;  
  11.                 }  
  12.                 grvEmployee.RenderControl(htmlwr);  
  13.                 StringReader srr = new StringReader(swr.ToString());  
  14.                 //iTextSharp.text.Document pdfdoc = new iTextSharp.text.Document(iTextSharp.text.PageSize.A4, 10f, 10f, 10f, 10f); //Pdf Page size and Margin types. //For Portrait   
  15.                 iTextSharp.text.Document pdfdoc = new iTextSharp.text.Document(iTextSharp.text.PageSize.A4.Rotate(), 10f, 10f, 10f, 10f); //For Landscape  
  16.                 HTMLWorker htmlparser = new HTMLWorker(pdfdoc);  
  17.                 PdfWriter.GetInstance(pdfdoc, Response.OutputStream);  
  18.                 pdfdoc.Open();  
  19.                 htmlparser.Parse(srr);  
  20.                 pdfdoc.Close();  
  21.                 Response.Write(pdfdoc);  
  22.                 Response.End();   
OUTPUT
 

I have added only this part to the existing one as mentioned in my previous article.
 

Then, Export to Excel. 
 
Compare Excel sheet data with GridView.
 

Then, export to PDF. 

Compare PDF data with GridView.
 


GIF images for better understanding
 
 


 
Summary
  1. What is GridView in ASP.NET.
  2. Single stored procedure to Export PDF and Excel.
  3. Image buttons added.
  4. Styles to be added in Excel and PDF after GridView Export.


Similar Articles