Export filtered ASP.Net GridView record to PDF using iTextSharp in C# and VB.Net

Last Reply 2 months ago By pandeyism

Posted 2 months ago

I want to maintain Gridview results after dropdown list OnSelectedIndexchanged has fired in order to export current Gridview results to PDF because currently all the Gridview results are exporting and not only the filtered results from the Dropdown List which i want to export.

<asp:DropDownList ID="drplstDepartment" OnSelectedIndexChanged="drplstDepartment_SelectedIndexChanged"
    Visible="false" EnableViewState="true" ViewStateMode="Enabled" ForeColor="White"
    CssClass="form-control mb-2 mr-sm-2 btn btn-primary dropdown-toggle" data-toggle="dropdown"
    BackColor="Gray" BorderColor="Gray" runat="server" AutoPostBack="true">
</asp:DropDownList>
<asp:GridView RowStyle-CssClass="text-center" Visible="false" ShowFooter="true" ShowHeader="true"
    runat="server" CssClass="Grid alert-light" EmptyDataText="No Results Found!"
    OnRowDataBound="GridView1_RowDataBound" OnPageIndexChanging="GridView1_PageIndexChanging"
    OnSelectedIndexChanging="GridView1_SelectedIndexChanging" Width="100%" AllowPaging="true"
    class="table table-default table-striped table-bordered table-condensed table-responsive table-hover"
    border="1" ID="GridView1" HeaderStyle-HorizontalAlign="Center" HeaderStyle-VerticalAlign="Middle"
    HeaderStyle-BackColor="#6C6C6C" HeaderStyle-ForeColor="White" RowStyle-BackColor="#eeeeee"
    AlternatingRowStyle-BackColor="#eeeeee" AlternatingRowStyle-ForeColor="#000"
    RowStyle-ForeColor="#000" AutoGenerateColumns="false" PagerSettings-PageButtonCount="50"
    PageSize="20" EditRowStyle-Wrap="False">
    <Columns>
        <asp:BoundField DataField="Department Name" ItemStyle-HorizontalAlign="Center" ItemStyle-VerticalAlign="Middle"
            HeaderText="Department Name" />
        <asp:BoundField DataField="Cost Centre" ItemStyle-HorizontalAlign="Center" ItemStyle-VerticalAlign="Middle"
            HeaderText="Cost Centre" />
        <asp:BoundField DataField="First Name" ItemStyle-HorizontalAlign="Center" ItemStyle-VerticalAlign="Middle"
            HeaderText="First Name" />
        <asp:BoundField DataField="Last Name" ItemStyle-HorizontalAlign="Center" ItemStyle-VerticalAlign="Middle"
            HeaderText="Last Name" />
        <asp:BoundField DataField="Employee Code" ItemStyle-HorizontalAlign="Center" ItemStyle-VerticalAlign="Middle"
            HeaderText="Employee Code" />
        <asp:BoundField DataFormatString="{0:dd/MM/yyyy}" DataField="Date Tested" ItemStyle-HorizontalAlign="Center"
            ItemStyle-VerticalAlign="Middle" HeaderText="Date Tested" />
        <asp:BoundField DataFormatString="{0:dd/MM/yyyy}" DataField="Next Due Date" ItemStyle-HorizontalAlign="Center"
            ItemStyle-VerticalAlign="Middle" HeaderText="Next Due Date" />
        <asp:BoundField DataFormatString="{0:dd/MM/yyyy}" DataField="ECG" ItemStyle-HorizontalAlign="Center"
            ItemStyle-VerticalAlign="Middle" HeaderText="ECG" />
        <asp:BoundField DataFormatString="{0:dd/MM/yyyy}" DataField="Lungfunction" ItemStyle-HorizontalAlign="Center"
            ItemStyle-VerticalAlign="Middle" HeaderText="Lungfunction" />
        <asp:BoundField DataFormatString="{0:dd/MM/yyyy}" DataField="Hearing Test" ItemStyle-HorizontalAlign="Center"
            ItemStyle-VerticalAlign="Middle" HeaderText="Hearing Test" />
        <asp:BoundField DataFormatString="{0:dd/MM/yyyy}" DataField="Eye Test" ItemStyle-HorizontalAlign="Center"
            ItemStyle-VerticalAlign="Middle" HeaderText="Eye Test" />
    </Columns>
</asp:GridView>

 

Posted 2 months ago

Hi Tevin,

Refer below sample.

HTML

<asp:DropDownList runat="server" ID="ddlCountry" OnSelectedIndexChanged="drplstDepartment_SelectedIndexChanged"
    AutoPostBack="true" AppendDataBoundItems="true">
    <asp:ListItem Text="Select" Value=""></asp:ListItem>
</asp:DropDownList>
<br />
<br />
<asp:GridView runat="server" ID="gvCustomers" AutoGenerateColumns="false" AllowPaging="true"
    PageSize="5" OnPageIndexChanging="gvCustomers_PageIndexChanging">
    <Columns>
        <asp:BoundField DataField="CompanyName" HeaderText="CompanyName" />
        <asp:BoundField DataField="City" HeaderText="City" />
        <asp:BoundField DataField="Country" HeaderText="Country" />
    </Columns>
</asp:GridView>
<br />
<asp:Button Text="Export" runat="server" OnClick="btnPDF_Click" />

Namespaces

C#

using System.Data;
using System.Data.SqlClient;
using System.Configuration;
using System.IO;
using iTextSharp.text.pdf;
using iTextSharp.text;
using iTextSharp.text.html.simpleparser;

VB.Net

Imports System.IO
Imports iTextSharp.text
Imports iTextSharp.text.html.simpleparser
Imports iTextSharp.text.pdf
Imports System.Data.SqlClient
Imports System.Data

Code

C#

protected void Page_Load(object sender, EventArgs e)
{
    if (!this.IsPostBack)
    {
        LoadDataGrid("");
        using (SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["constr"].ConnectionString))
        {
            using (SqlCommand cmd = new SqlCommand("SELECT DISTINCT Country FROM Customers", conn))
            {
                SqlDataAdapter sda = new SqlDataAdapter(cmd);
                DataTable dt = new DataTable();
                sda.Fill(dt);
                ddlCountry.DataSource = dt;
                ddlCountry.DataTextField = "Country";
                ddlCountry.DataValueField = "Country";
                ddlCountry.DataBind();
            }
        }
    }
}

private void LoadDataGrid(string country)
{
    DataTable dt = new DataTable();
    using (SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["constr"].ToString()))
    {
        SqlCommand cmd = new SqlCommand("SELECT CompanyName,City,Country FROM Customers WHERE Country = @Country OR @Country IS NULL", conn);
        cmd.Parameters.AddWithValue("@Country", !string.IsNullOrEmpty(country) ? country : (object)DBNull.Value);
        SqlDataAdapter da = new SqlDataAdapter(cmd);
        da.Fill(dt);
        gvCustomers.DataSource = dt;
        gvCustomers.DataBind();
    }
}

protected void drplstDepartment_SelectedIndexChanged(object sender, EventArgs e)
{
    LoadDataGrid(ddlCountry.SelectedItem.Value);
}

protected void btnPDF_Click(object sender, EventArgs e)
{
    using (StringWriter sw = new StringWriter())
    {
        using (HtmlTextWriter hw = new HtmlTextWriter(sw))
        {
            // To Export all pages
            gvCustomers.AllowPaging = false;
            // Rebind the filtered record to GridView.
            LoadDataGrid(ddlCountry.SelectedItem.Value);
            gvCustomers.RenderControl(hw);
            StringReader sr = new StringReader(sw.ToString());
            Document pdfDoc = new Document(PageSize.A4, 10.0F, 10.0F, 10.0F, 0.0F);
            HTMLWorker htmlparser = new HTMLWorker(pdfDoc);
            PdfWriter.GetInstance(pdfDoc, Response.OutputStream);
            pdfDoc.Open();
            htmlparser.Parse(sr);
            pdfDoc.Close();
            Response.ContentType = "application/pdf";
            Response.AddHeader("content-disposition", "attachment;filename=GridViewExport.pdf");
            Response.Cache.SetCacheability(HttpCacheability.NoCache);
            Response.Write(pdfDoc);
            Response.End();
        }
    }
}

public override void VerifyRenderingInServerForm(Control control)
{
    /* Verifies that the control is rendered */
}

protected void gvCustomers_PageIndexChanging(object sender, GridViewPageEventArgs e)
{
    gvCustomers.PageIndex = e.NewPageIndex;
    LoadDataGrid(ddlCountry.SelectedItem.Value);
}

VB.Net

Protected Sub Page_Load(ByVal sender As Object, ByVal e As EventArgs) Handles Me.Load
    If Not Me.IsPostBack Then
        LoadDataGrid("")
        Using conn As SqlConnection = New SqlConnection(ConfigurationManager.ConnectionStrings("constr").ConnectionString)
            Using cmd As SqlCommand = New SqlCommand("SELECT DISTINCT Country FROM Customers", conn)
                Dim sda As SqlDataAdapter = New SqlDataAdapter(cmd)
                Dim dt As DataTable = New DataTable()
                sda.Fill(dt)
                ddlCountry.DataSource = dt
                ddlCountry.DataTextField = "Country"
                ddlCountry.DataValueField = "Country"
                ddlCountry.DataBind()
            End Using
        End Using
    End If
End Sub

Private Sub LoadDataGrid(ByVal country As String)
    Dim dt As DataTable = New DataTable()
    Using conn As SqlConnection = New SqlConnection(ConfigurationManager.ConnectionStrings("constr").ToString())
        Dim cmd As SqlCommand = New SqlCommand("SELECT CompanyName,City,Country FROM Customers WHERE Country = @Country OR @Country IS NULL", conn)
        cmd.Parameters.AddWithValue("@Country", If(Not String.IsNullOrEmpty(country), country, CObj(DBNull.Value)))
        Dim da As SqlDataAdapter = New SqlDataAdapter(cmd)
        da.Fill(dt)
        gvCustomers.DataSource = dt
        gvCustomers.DataBind()
    End Using
End Sub

Protected Sub drplstDepartment_SelectedIndexChanged(ByVal sender As Object, ByVal e As EventArgs)
    LoadDataGrid(ddlCountry.SelectedItem.Value)
End Sub

Protected Sub btnPDF_Click(ByVal sender As Object, ByVal e As EventArgs)
    Using sw As StringWriter = New StringWriter()
        Using hw As HtmlTextWriter = New HtmlTextWriter(sw)
            gvCustomers.AllowPaging = False
            LoadDataGrid(ddlCountry.SelectedItem.Value)
            gvCustomers.RenderControl(hw)
            Dim sr As StringReader = New StringReader(sw.ToString())
            Dim pdfDoc As Document = New Document(PageSize.A4, 10.0F, 10.0F, 10.0F, 0.0F)
            Dim htmlparser As HTMLWorker = New HTMLWorker(pdfDoc)
            PdfWriter.GetInstance(pdfDoc, Response.OutputStream)
            pdfDoc.Open()
            htmlparser.Parse(sr)
            pdfDoc.Close()
            Response.ContentType = "application/pdf"
            Response.AddHeader("content-disposition", "attachment;filename=GridViewExport.pdf")
            Response.Cache.SetCacheability(HttpCacheability.NoCache)
            Response.Write(pdfDoc)
            Response.[End]()
        End Using
    End Using
End Sub

Public Overrides Sub VerifyRenderingInServerForm(ByVal control As Control)
End Sub

Protected Sub gvCustomers_PageIndexChanging(ByVal sender As Object, ByVal e As GridViewPageEventArgs)
    gvCustomers.PageIndex = e.NewPageIndex
    LoadDataGrid(ddlCountry.SelectedItem.Value)
End Sub

Screenshot