Introduction
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
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
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,
- <%@ Page Language="C#" AutoEventWireup="true" CodeBehind="GridViewDemo.aspx.cs" Inherits="GridViewDemo.GridViewDemo" %>
- <!DOCTYPE html>
- <html xmlns="http://www.w3.org/1999/xhtml">
- <head runat="server">
- <title>Satyaprakash Samantaray</title>
- <%--Botstrap Part--%>
- <style>
- .button {
- background-color: #4CAF50;
- border: none;
- color: white;
- padding: 15px 32px;
- text-align: center;
- text-decoration: none;
- display: inline-block;
- font-size: 16px;
- margin: 4px 2px;
- cursor: pointer;
- }
- .DataGridFixedHeader {
- color: White;
- font-size: 13px;
- font-family: Verdana;
- background-color:yellow
- }
- .grid_item {
- background-color: #E3EAEB;
- border-width: 1px;
- font-family: Verdana;
- border-style: solid;
- font-size: 12pt;
- color: black;
- border: 1px solid black;
- }
- .grid_alternate {
- border-width: 1px;
- font-family: Verdana;
- border-style: solid;
- font-size: 12pt;
- color: black;
- background-color: White;
- }
- .button4 {
- border-radius: 9px;
- }
- input[type=text], select {
- width: 40%;
- padding: 12px 20px;
- margin: 10px 0;
- display: inline-block;
- border: 1px solid #ccc;
- border-radius: 4px;
- box-sizing: border-box;
- font-family: 'Montserrat', sans-serif;
- text-indent: 10px;
- color: blue;
- text-shadow: 0 1px 2px rgba(0, 0, 0, 0.3);
- font-size: 20px;
- }
- </style>
- <%--Botstrap Part--%>
- </head>
- <body>
- <form id="form1" runat="server">
- <fieldset>
- <legend style="font-family: Arial Black;background-color:yellow; color:red; font-size:larger;font-style: oblique">Satyaprakash's Real-Time Project</legend>
- <table align="center">
- <tr>
- <td colspan="2" align="center" class="auto-style1">
- <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>
- </td>
- </tr>
- <tr>
- <td style="text-align:center">
- <asp:TextBox runat="server" ID="txtFirstName" placeholder="Enter First Name.." ValidationGroup="add" ></asp:TextBox>
- </td>
- </tr>
- <tr>
- <td style="text-align:center">
- <asp:TextBox runat="server" ID="txtLastName" placeholder="Enter Last Name.." ValidationGroup="add" ></asp:TextBox>
- </td>
- </tr>
- <tr>
- <td style="text-align:center">
- <asp:TextBox runat="server" placeholder="Enter Phone Number.." ID="txtPhoneNumber" ValidationGroup="add"></asp:TextBox>
- </td>
- <td></td>
- </tr>
- <tr>
- <td style="text-align:center">
- <asp:TextBox runat="server" ID="txtEmailAddress" placeholder="Enter Email Address.." ValidationGroup="add" ></asp:TextBox>
- </td>
- </tr>
- <tr>
- <td style="text-align:center">
- <asp:TextBox runat="server" ID="txtSalary" placeholder="Enter Salary.." ValidationGroup="add" ></asp:TextBox>
- </td>
- </tr>
- <tr>
- <td colspan="2" align="center">
- <asp:Button runat="server" ID="btnAddEmployee" Text="Add" OnClick="btnAddEmployee_Click" class="button button4" ValidationGroup="add"/>
- <asp:Button runat="server" ID="btnUpdate" Text="Update" class="button button4" OnClick="btnUpdate_Click"/>
- <asp:Button runat="server" ID="btnReset" Text="Reset" class="button button4" OnClick="btnReset_Click"/>
- </td>
- </tr>
- <tr>
- <td colspan="2" align="center">
- <br />
- <asp:Label runat="server" ID="lblMessage"></asp:Label>
- <br />
- <br />
- </td>
- </tr>
- <tr runat="server" style="height: 3px">
- <td align="center" colspan="2" style="background-color:yellowgreen;width: 100%;">
- <span style="font-family: Arial Black;color:red; font-size:larger;font-style: oblique">Export EXCEL</span>
- <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"/>
- <span style="font-family: Arial Black;color:red; font-size:larger;font-style: oblique">Export PDF</span>
- <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" />
- </td>
- </tr>
- <tr>
- <td colspan="2">
- <asp:GridView ID="grvEmployee" runat="server" AllowPaging="true" CellPadding="2" EnableModelValidation="True"
- ForeColor="red" GridLines="Both" ItemStyle-HorizontalAlign="center" EmptyDataText="There Is No Records In Database!" AutoGenerateColumns="false" Width="1100px"
- HeaderStyle-ForeColor="blue" OnPageIndexChanging="grvEmployee_PageIndexChanging" OnRowCancelingEdit="grvEmployee_RowCancelingEdit" OnRowDeleting="grvEmployee_RowDeleting" OnRowEditing="grvEmployee_RowEditing">
- <HeaderStyle CssClass="DataGridFixedHeader" />
- <RowStyle CssClass="grid_item" />
- <AlternatingRowStyle CssClass="grid_alternate" />
- <FooterStyle CssClass="DataGridFixedHeader" />
- <Columns>
- <asp:TemplateField HeaderText="EmpId">
- <HeaderStyle HorizontalAlign="Left" />
- <ItemStyle HorizontalAlign="Left" />
- <ItemTemplate>
- <asp:Label runat="server" ID="lblEmpId" Text='<%#Eval("id") %>'></asp:Label>
- </ItemTemplate>
- </asp:TemplateField>
- <asp:TemplateField HeaderText="FirstName">
- <HeaderStyle HorizontalAlign="Left" />
- <ItemStyle HorizontalAlign="Left" />
- <ItemTemplate>
- <asp:Label runat="server" ID="lblFirstName" Text='<%#Eval("FirstName") %>'></asp:Label>
- </ItemTemplate>
- </asp:TemplateField>
- <asp:TemplateField HeaderText="LastName">
- <HeaderStyle HorizontalAlign="Left" />
- <ItemStyle HorizontalAlign="Left" />
- <ItemTemplate>
- <asp:Label runat="server" ID="lblLastName" Text='<%#Eval("LastName") %>'></asp:Label>
- </ItemTemplate>
- </asp:TemplateField>
- <asp:TemplateField HeaderText="Phone No.">
- <HeaderStyle HorizontalAlign="Left" />
- <ItemStyle HorizontalAlign="Left" />
- <ItemTemplate>
- <asp:Label runat="server" ID="lblPhoneNumber" Text='<%#Eval("PhoneNumber") %>'></asp:Label>
- </ItemTemplate>
- </asp:TemplateField>
- <asp:TemplateField HeaderText="Email">
- <HeaderStyle HorizontalAlign="Left" />
- <ItemStyle HorizontalAlign="Left" />
- <ItemTemplate>
- <asp:Label runat="server" ID="lblEmailAddress" Text='<%#Eval("EmailAddress") %>'></asp:Label>
- </ItemTemplate>
- </asp:TemplateField>
- <asp:TemplateField HeaderText="Salary">
- <HeaderStyle HorizontalAlign="Left" />
- <ItemStyle HorizontalAlign="Left" />
- <ItemTemplate>
- <asp:Label runat="server" ID="lblSalary" Text='<%#Eval("Salary") %>'></asp:Label>
- </ItemTemplate>
- </asp:TemplateField>
- <asp:TemplateField HeaderText="Update">
- <HeaderStyle HorizontalAlign="Left" />
- <ItemStyle HorizontalAlign="Left" />
- <ItemTemplate>
- <asp:LinkButton runat="server" ID="btnEdit" Text="Edit" CommandName="Edit" ToolTip="Click here to Edit the record" />
- </ItemTemplate>
- </asp:TemplateField>
- <asp:TemplateField HeaderText="Delete">
- <HeaderStyle HorizontalAlign="Left" />
- <ItemStyle HorizontalAlign="Left" />
- <ItemTemplate>
- <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" />
- </span>
- </ItemTemplate>
- </asp:TemplateField>
- </Columns>
- </asp:GridView>
- </td>
- </tr>
- </table>
- </fieldset>
- </form>
- </body>
- <br />
- <br />
- <footer>
- <p style="background-color: Yellow; font-weight: bold; color:blue; text-align: center; font-style: oblique">© <script> document.write(new Date().toDateString()); </script></p>
- </footer>
- </html>
Here, I have added two image buttons to perform export to Excel and PDF.
- <tr runat="server" style="height: 3px">
- <td align="center" colspan="2" style="background-color:yellowgreen;width: 100%;">
- <span style="font-family: Arial Black;color:red; font-size:larger;font-style: oblique">Export EXCEL</span>
- <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"/>
- <span style="font-family: Arial Black;color:red; font-size:larger;font-style: oblique">Export PDF</span>
- <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" />
- </td>
- </tr>
- ImageUrl="~/Images/Excel.gif"
- ImageUrl="~/Images/Pdf.png"
- ToolTip="Click here to Export to Excel"
- ToolTip="Click here to Export to Pdf"
Code ref for GridViewDemo.aspx.cs
- using System;
- using System.Collections.Generic;
- using System.Configuration;
- using System.Data;
- using System.Data.SqlClient;
- using System.Drawing;
- using System.IO;
- using System.Linq;
- using System.Web;
- using System.Web.UI;
- using System.Web.UI.WebControls;
- //namespace for pdf export.
- using System.Text;
- using iTextSharp.text.pdf;
- using iTextSharp.text.html;
- using iTextSharp.text.html.simpleparser;
- using System.Web.UI.HtmlControls;
- namespace GridViewDemo
- {
- public partial class GridViewDemo : System.Web.UI.Page
- {
- private string strConnectionString = ConfigurationManager.ConnectionStrings["myconnection"].ConnectionString;
- private SqlCommand _sqlCommand;
- private SqlDataAdapter _sqlDataAdapter;
- DataSet _dtSet;
- protected void Page_Load(object sender, EventArgs e)
- {
- if (!IsPostBack)
- {
- BindEmployeeData();
- }
- btnUpdate.Visible = false;
- btnAddEmployee.Visible = true;
- }
- private static void ShowAlertMessage(string error)
- {
- System.Web.UI.Page page = System.Web.HttpContext.Current.Handler as System.Web.UI.Page;
- if (page != null)
- {
- error = error.Replace("'", "\'");
- System.Web.UI.ScriptManager.RegisterStartupScript(page, page.GetType(), "err_msg", "alert('" + error + "');", true);
- }
- }
- public void CreateConnection()
- {
- SqlConnection _sqlConnection = new SqlConnection(strConnectionString);
- _sqlCommand = new SqlCommand();
- _sqlCommand.Connection = _sqlConnection;
- }
- public void OpenConnection()
- {
- _sqlCommand.Connection.Open();
- }
- public void CloseConnection()
- {
- _sqlCommand.Connection.Close();
- }
- public void DisposeConnection()
- {
- _sqlCommand.Connection.Dispose();
- }
- public void BindEmployeeData()
- {
- try
- {
- CreateConnection();
- OpenConnection();
- _sqlCommand.CommandText = "Sp_GridCrud";
- _sqlCommand.CommandType = CommandType.StoredProcedure;
- _sqlCommand.Parameters.AddWithValue("@Event", "Select");
- _sqlDataAdapter = new SqlDataAdapter(_sqlCommand);
- _dtSet = new DataSet();
- _sqlDataAdapter.Fill(_dtSet);
- grvEmployee.DataSource = _dtSet;
- grvEmployee.DataBind();
- }
- catch (Exception ex)
- {
- Response.Redirect("The Error is " + ex);
- }
- finally
- {
- CloseConnection();
- DisposeConnection();
- }
- }
- protected void btnAddEmployee_Click(object sender, EventArgs e)
- {
- try
- {
- CreateConnection();
- OpenConnection();
- _sqlCommand.CommandText = "Sp_GridCrud";
- _sqlCommand.CommandType = CommandType.StoredProcedure;
- _sqlCommand.Parameters.AddWithValue("@Event", "Add");
- _sqlCommand.Parameters.AddWithValue("@FirstName", Convert.ToString(txtFirstName.Text.Trim()));
- _sqlCommand.Parameters.AddWithValue("@LastName", Convert.ToString(txtLastName.Text.Trim()));
- _sqlCommand.Parameters.AddWithValue("@PhoneNumber", Convert.ToString(txtPhoneNumber.Text.Trim()));
- _sqlCommand.Parameters.AddWithValue("@EmailAddress", Convert.ToString(txtEmailAddress.Text.Trim()));
- _sqlCommand.Parameters.AddWithValue("@Salary", Convert.ToDecimal(txtSalary.Text));
- int result = Convert.ToInt32(_sqlCommand.ExecuteNonQuery());
- if (result > 0)
- {
- ShowAlertMessage("Record Is Inserted Successfully");
- BindEmployeeData();
- ClearControls();
- }
- else
- {
- ShowAlertMessage("Failed");
- }
- }
- catch (Exception ex)
- {
- ShowAlertMessage("Check your input data");
- }
- finally
- {
- CloseConnection();
- DisposeConnection();
- }
- }
- public void ClearControls()
- {
- txtFirstName.Text = "";
- txtLastName.Text = "";
- txtPhoneNumber.Text = "";
- txtEmailAddress.Text = "";
- txtSalary.Text = "";
- }
- protected void grvEmployee_RowEditing(object sender, GridViewEditEventArgs e)
- {
- btnAddEmployee.Visible = false;
- btnUpdate.Visible = true;
- int RowIndex = e.NewEditIndex;
- Label empid = (Label)grvEmployee.Rows[RowIndex].FindControl("lblEmpId");
- Session["id"] = empid.Text;
- txtFirstName.Text = ((Label)grvEmployee.Rows[RowIndex].FindControl("lblFirstName")).Text.ToString();
- txtLastName.Text = ((Label)grvEmployee.Rows[RowIndex].FindControl("lblLastName")).Text.ToString();
- txtPhoneNumber.Text = ((Label)grvEmployee.Rows[RowIndex].FindControl("lblPhoneNumber")).Text.ToString();
- txtEmailAddress.Text = ((Label)grvEmployee.Rows[RowIndex].FindControl("lblEmailAddress")).Text.ToString();
- txtSalary.Text = ((Label)grvEmployee.Rows[RowIndex].FindControl("lblSalary")).Text.ToString();
- }
- protected void grvEmployee_RowDeleting(object sender, GridViewDeleteEventArgs e)
- {
- try
- {
- CreateConnection();
- OpenConnection();
- Label id = (Label)grvEmployee.Rows[e.RowIndex].FindControl("lblEmpId");
- _sqlCommand.CommandText = "Sp_GridCrud";
- _sqlCommand.Parameters.AddWithValue("@Event", "Delete");
- _sqlCommand.Parameters.AddWithValue("@EmpId", Convert.ToInt32(id.Text));
- _sqlCommand.CommandType = CommandType.StoredProcedure;
- int result = Convert.ToInt32(_sqlCommand.ExecuteNonQuery());
- if (result > 0)
- {
- ShowAlertMessage("Record Is Deleted Successfully");
- grvEmployee.EditIndex = -1;
- BindEmployeeData();
- }
- else
- {
- lblMessage.Text = "Failed";
- lblMessage.ForeColor = System.Drawing.Color.Red;
- BindEmployeeData();
- }
- }
- catch (Exception ex)
- {
- ShowAlertMessage("Check your input data");
- }
- finally
- {
- CloseConnection();
- DisposeConnection();
- }
- }
- protected void grvEmployee_RowCancelingEdit(object sender, GridViewCancelEditEventArgs e)
- {
- grvEmployee.EditIndex = -1;
- BindEmployeeData();
- }
- protected void grvEmployee_PageIndexChanging(object sender, GridViewPageEventArgs e)
- {
- grvEmployee.PageIndex = e.NewPageIndex;
- BindEmployeeData();
- }
- protected void btnReset_Click(object sender, EventArgs e)
- {
- ClearControls();
- }
- protected void btnUpdate_Click(object sender, EventArgs e)
- {
- try
- {
- CreateConnection();
- OpenConnection();
- _sqlCommand.CommandText = "Sp_GridCrud";
- _sqlCommand.CommandType = CommandType.StoredProcedure;
- _sqlCommand.Parameters.AddWithValue("@Event", "Update");
- _sqlCommand.Parameters.AddWithValue("@FirstName", Convert.ToString(txtFirstName.Text.Trim()));
- _sqlCommand.Parameters.AddWithValue("@LastName", Convert.ToString(txtLastName.Text.Trim()));
- _sqlCommand.Parameters.AddWithValue("@PhoneNumber", Convert.ToString(txtPhoneNumber.Text.Trim()));
- _sqlCommand.Parameters.AddWithValue("@EmailAddress", Convert.ToString(txtEmailAddress.Text.Trim()));
- _sqlCommand.Parameters.AddWithValue("@Salary", Convert.ToDecimal(txtSalary.Text));
- _sqlCommand.Parameters.AddWithValue("@EmpId", Convert.ToDecimal(Session["id"]));
- int result = Convert.ToInt32(_sqlCommand.ExecuteNonQuery());
- if (result > 0)
- {
- ShowAlertMessage("Record Is Updated Successfully");
- grvEmployee.EditIndex = -1;
- BindEmployeeData();
- ClearControls();
- }
- else
- {
- ShowAlertMessage("Failed");
- }
- }
- catch (Exception ex)
- {
- ShowAlertMessage("Check your input data");
- }
- finally
- {
- CloseConnection();
- DisposeConnection();
- }
- }
- protected void ibtnExcel_Click(object sender, ImageClickEventArgs e)
- {
- try
- {
- GridView grvEmployee = new GridView();
- CreateConnection();
- OpenConnection();
- _sqlCommand.CommandText = "Sp_GridCrud";
- _sqlCommand.CommandType = CommandType.StoredProcedure;
- _sqlCommand.Parameters.AddWithValue("@Event", "Select");
- _sqlDataAdapter = new SqlDataAdapter(_sqlCommand);
- _dtSet = new DataSet();
- _sqlDataAdapter.Fill(_dtSet);
- grvEmployee.DataSource = _dtSet;
- grvEmployee.DataBind();
- HttpContext.Current.Response.ClearContent();
- HttpContext.Current.Response.AddHeader("content-disposition", "attachment; filename=SatyaRecords.xls");
- HttpContext.Current.Response.ContentType = "application/excel";
- StringWriter sw = new StringWriter();
- HtmlTextWriter htw = new HtmlTextWriter(sw);
- grvEmployee.HeaderRow.BackColor = Color.DarkSlateGray;
- grvEmployee.HeaderStyle.ForeColor = Color.White;
- grvEmployee.AlternatingRowStyle.BackColor = Color.FromArgb(227, 234, 235);
- grvEmployee.RenderControl(htw);
- HttpContext.Current.Response.Write(sw.ToString());
- HttpContext.Current.Response.Flush();
- HttpContext.Current.Response.End();
- }
- catch (Exception ex)
- {
- HttpContext.Current.Response.Flush();
- HttpContext.Current.Response.End();
- }
- }
- protected void ibtnPdf_Click(object sender, ImageClickEventArgs e)
- {
- try
- {
- GridView grvEmployee = new GridView();
- CreateConnection();
- OpenConnection();
- _sqlCommand.CommandText = "Sp_GridCrud";
- _sqlCommand.CommandType = CommandType.StoredProcedure;
- _sqlCommand.Parameters.AddWithValue("@Event", "Select");
- _sqlDataAdapter = new SqlDataAdapter(_sqlCommand);
- _dtSet = new DataSet();
- _sqlDataAdapter.Fill(_dtSet);
- grvEmployee.DataSource = _dtSet;
- grvEmployee.DataBind();
- Response.ContentType = "application/pdf";
- Response.AddHeader("content-disposition", "attachment;filename=SatyaRecords.pdf");
- Response.Cache.SetCacheability(HttpCacheability.NoCache);
- StringWriter swr = new StringWriter();
- HtmlTextWriter htmlwr = new HtmlTextWriter(swr);
- //Mention gridview property for export to pdf.
- grvEmployee.AllowPaging = false;
- grvEmployee.HeaderRow.BackColor = Color.DarkSlateGray;
- grvEmployee.AlternatingRowStyle.BackColor = Color.FromArgb(227, 234, 235);
- grvEmployee.HeaderRow.Style.Add("font-family", "Arial, Helvetica, sans-serif;");
- grvEmployee.HeaderRow.Style.Add("font-size", "8.20px");
- grvEmployee.HeaderRow.Style.Add("color", "White");
- grvEmployee.Style.Add("font-family", "Arial, Helvetica, sans-serif;");
- grvEmployee.Style.Add("font-size", "8px");
- for (int i = 0; i < grvEmployee.Rows.Count; i++)
- {
- grvEmployee.Rows[i].HorizontalAlign = HorizontalAlign.Left;
- //pdfGridView.Rows[i].VerticalAlign = VerticalAlign.Top;
- }
- grvEmployee.RenderControl(htmlwr);
- StringReader srr = new StringReader(swr.ToString());
- //iTextSharp.text.Document pdfdoc = new iTextSharp.text.Document(iTextSharp.text.PageSize.A4, 10f, 10f, 10f, 10f); //Pdf Page size and Margin types. //For Portrait
- iTextSharp.text.Document pdfdoc = new iTextSharp.text.Document(iTextSharp.text.PageSize.A4.Rotate(), 10f, 10f, 10f, 10f); //For Landscape
- HTMLWorker htmlparser = new HTMLWorker(pdfdoc);
- PdfWriter.GetInstance(pdfdoc, Response.OutputStream);
- pdfdoc.Open();
- htmlparser.Parse(srr);
- pdfdoc.Close();
- Response.Write(pdfdoc);
- Response.End();
- }
- catch (Exception ex)
- {
- }
- }
- }
- }
I have added some namespaces for PDF export.
- using System.Text;
- using iTextSharp.text.pdf;
- using iTextSharp.text.html;
- using iTextSharp.text.html.simpleparser;
- using System.Web.UI.HtmlControls;
Then, in button click event of Excel export, I have added the following code.
- protected void ibtnExcel_Click(object sender, ImageClickEventArgs e)
- {
- try
- {
- GridView grvEmployee = new GridView();
- CreateConnection();
- OpenConnection();
- _sqlCommand.CommandText = "Sp_GridCrud";
- _sqlCommand.CommandType = CommandType.StoredProcedure;
- _sqlCommand.Parameters.AddWithValue("@Event", "Select");
- _sqlDataAdapter = new SqlDataAdapter(_sqlCommand);
- _dtSet = new DataSet();
- _sqlDataAdapter.Fill(_dtSet);
- grvEmployee.DataSource = _dtSet;
- grvEmployee.DataBind();
- HttpContext.Current.Response.ClearContent();
- HttpContext.Current.Response.AddHeader("content-disposition", "attachment; filename=SatyaRecords.xls");
- HttpContext.Current.Response.ContentType = "application/excel";
- StringWriter sw = new StringWriter();
- HtmlTextWriter htw = new HtmlTextWriter(sw);
- grvEmployee.HeaderRow.BackColor = Color.DarkSlateGray;
- grvEmployee.HeaderStyle.ForeColor = Color.White;
- grvEmployee.AlternatingRowStyle.BackColor = Color.FromArgb(227, 234, 235);
- grvEmployee.RenderControl(htw);
- HttpContext.Current.Response.Write(sw.ToString());
- HttpContext.Current.Response.Flush();
- HttpContext.Current.Response.End();
- }
- catch (Exception ex)
- {
- HttpContext.Current.Response.Flush();
- HttpContext.Current.Response.End();
- }
- }
- GridView grvEmployee = new GridView();
- CreateConnection();
- OpenConnection();
- _sqlCommand.CommandText = "Sp_GridCrud";
- _sqlCommand.CommandType = CommandType.StoredProcedure;
- _sqlCommand.Parameters.AddWithValue("@Event", "Select");
- _sqlDataAdapter = new SqlDataAdapter(_sqlCommand);
- _dtSet = new DataSet();
- _sqlDataAdapter.Fill(_dtSet);
- grvEmployee.DataSource = _dtSet;
- grvEmployee.DataBind();
- grvEmployee.HeaderRow.BackColor = Color.DarkSlateGray;
- grvEmployee.HeaderStyle.ForeColor = Color.White;
- grvEmployee.AlternatingRowStyle.BackColor = Color.FromArgb(227, 234, 235);
- grvEmployee.RenderControl(htw);
- HttpContext.Current.Response.ClearContent();
- HttpContext.Current.Response.AddHeader("content-disposition", "attachment; filename=SatyaRecords.xls");
- HttpContext.Current.Response.ContentType = "application/excel";
- StringWriter sw = new StringWriter();
- HtmlTextWriter htw = new HtmlTextWriter(sw);
- HttpContext.Current.Response.Write(sw.ToString());
- HttpContext.Current.Response.Flush();
- HttpContext.Current.Response.End();
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.
- context.HttpContext.Response.Clear();
- context.HttpContext.Response.Write(htmlString);
- context.HttpContext.Response.Flush(); // send all buffered output to client
- context.HttpContext.Response.End(); // response.end would work fine now.
- protected void ibtnPdf_Click(object sender, ImageClickEventArgs e)
- {
- try
- {
- GridView grvEmployee = new GridView();
- CreateConnection();
- OpenConnection();
- _sqlCommand.CommandText = "Sp_GridCrud";
- _sqlCommand.CommandType = CommandType.StoredProcedure;
- _sqlCommand.Parameters.AddWithValue("@Event", "Select");
- _sqlDataAdapter = new SqlDataAdapter(_sqlCommand);
- _dtSet = new DataSet();
- _sqlDataAdapter.Fill(_dtSet);
- grvEmployee.DataSource = _dtSet;
- grvEmployee.DataBind();
- Response.ContentType = "application/pdf";
- Response.AddHeader("content-disposition", "attachment;filename=SatyaRecords.pdf");
- Response.Cache.SetCacheability(HttpCacheability.NoCache);
- StringWriter swr = new StringWriter();
- HtmlTextWriter htmlwr = new HtmlTextWriter(swr);
- //Mention gridview property for export to pdf.
- grvEmployee.AllowPaging = false;
- grvEmployee.HeaderRow.BackColor = Color.DarkSlateGray;
- grvEmployee.AlternatingRowStyle.BackColor = Color.FromArgb(227, 234, 235);
- grvEmployee.HeaderRow.Style.Add("font-family", "Arial, Helvetica, sans-serif;");
- grvEmployee.HeaderRow.Style.Add("font-size", "8.20px");
- grvEmployee.HeaderRow.Style.Add("color", "White");
- grvEmployee.Style.Add("font-family", "Arial, Helvetica, sans-serif;");
- grvEmployee.Style.Add("font-size", "8px");
- for (int i = 0; i < grvEmployee.Rows.Count; i++)
- {
- grvEmployee.Rows[i].HorizontalAlign = HorizontalAlign.Left;
- //pdfGridView.Rows[i].VerticalAlign = VerticalAlign.Top;
- }
- grvEmployee.RenderControl(htmlwr);
- StringReader srr = new StringReader(swr.ToString());
- //iTextSharp.text.Document pdfdoc = new iTextSharp.text.Document(iTextSharp.text.PageSize.A4, 10f, 10f, 10f, 10f); //Pdf Page size and Margin types. //For Portrait
- iTextSharp.text.Document pdfdoc = new iTextSharp.text.Document(iTextSharp.text.PageSize.A4.Rotate(), 10f, 10f, 10f, 10f); //For Landscape
- HTMLWorker htmlparser = new HTMLWorker(pdfdoc);
- PdfWriter.GetInstance(pdfdoc, Response.OutputStream);
- pdfdoc.Open();
- htmlparser.Parse(srr);
- pdfdoc.Close();
- Response.Write(pdfdoc);
- Response.End();
- }
- catch (Exception ex)
- {
- }
- }
- GridView grvEmployee = new GridView();
- CreateConnection();
- OpenConnection();
- _sqlCommand.CommandText = "Sp_GridCrud";
- _sqlCommand.CommandType = CommandType.StoredProcedure;
- _sqlCommand.Parameters.AddWithValue("@Event", "Select");
- _sqlDataAdapter = new SqlDataAdapter(_sqlCommand);
- _dtSet = new DataSet();
- _sqlDataAdapter.Fill(_dtSet);
- grvEmployee.DataSource = _dtSet;
- grvEmployee.DataBind();
- grvEmployee.AllowPaging = false;
- grvEmployee.HeaderRow.BackColor = Color.DarkSlateGray;
- grvEmployee.AlternatingRowStyle.BackColor = Color.FromArgb(227, 234, 235);
- grvEmployee.HeaderRow.Style.Add("font-family", "Arial, Helvetica, sans-serif;");
- grvEmployee.HeaderRow.Style.Add("font-size", "8.20px");
- grvEmployee.HeaderRow.Style.Add("color", "White");
- grvEmployee.Style.Add("font-family", "Arial, Helvetica, sans-serif;");
- grvEmployee.Style.Add("font-size", "8px");
- for (int i = 0; i < grvEmployee.Rows.Count; i++)
- {
- grvEmployee.Rows[i].HorizontalAlign = HorizontalAlign.Left;
- //pdfGridView.Rows[i].VerticalAlign = VerticalAlign.Top;
- }
- Response.ContentType = "application/pdf";
- Response.AddHeader("content-disposition", "attachment;filename=SatyaRecords.pdf");
- Response.Cache.SetCacheability(HttpCacheability.NoCache);
- StringWriter swr = new StringWriter();
- HtmlTextWriter htmlwr = new HtmlTextWriter(swr);
- for (int i = 0; i < grvEmployee.Rows.Count; i++)
- {
- grvEmployee.Rows[i].HorizontalAlign = HorizontalAlign.Left;
- //pdfGridView.Rows[i].VerticalAlign = VerticalAlign.Top;
- }
- grvEmployee.RenderControl(htmlwr);
- StringReader srr = new StringReader(swr.ToString());
- //iTextSharp.text.Document pdfdoc = new iTextSharp.text.Document(iTextSharp.text.PageSize.A4, 10f, 10f, 10f, 10f); //Pdf Page size and Margin types. //For Portrait
- iTextSharp.text.Document pdfdoc = new iTextSharp.text.Document(iTextSharp.text.PageSize.A4.Rotate(), 10f, 10f, 10f, 10f); //For Landscape
- HTMLWorker htmlparser = new HTMLWorker(pdfdoc);
- PdfWriter.GetInstance(pdfdoc, Response.OutputStream);
- pdfdoc.Open();
- htmlparser.Parse(srr);
- pdfdoc.Close();
- Response.Write(pdfdoc);
- 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
- What is GridView in ASP.NET.
- Single stored procedure to Export PDF and Excel.
- Image buttons added.
- Styles to be added in Excel and PDF after GridView Export.

Join the conversation! Your thoughts help the community grow.