Selecting Radio Button to Download file in Different Format

Selecting a Radio Button download in this Format:

Step 1: Database

Table:

Database Table
 
Step 2: Html Coding

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Excel_and_Pdf.aspx.cs" Inherits="Excel_and_Pdf" %>

 

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">

<head id="Head1" runat="server">

    <title></title>

</head>

<body>

    <form id="form1" runat="server">

    <div>

        <asp:RadioButtonList ID="Rd" runat="server" OnSelectedIndexChanged="Rd_SelectedIndexChanged"

            AutoPostBack="true">

            <asp:ListItem Text="Excel"></asp:ListItem>

            <asp:ListItem Text="Pdf"></asp:ListItem>

            <asp:ListItem Text="CSV"></asp:ListItem>

            <asp:ListItem Text="Word"></asp:ListItem>

            <asp:ListItem Text="CSV1"></asp:ListItem>

        </asp:RadioButtonList>

        <br />

        <asp:HiddenField ID="hdvalue" runat="server" />

        <br />

        <asp:Button ID="Btndownload" runat="server" Text="Download" OnClick="Btndownload_Click" />

        <br />

        <br />

        <br />

        <br />

        <asp:GridView ID="gvdetails" runat="server">

        </asp:GridView>

    </div>

    </form>

</body>

</html>

  
Step 3: C# Coding

using System;

using System.Collections.Generic;

using System.Linq;

using System.Web;

using System.Web.UI;

using System.Web.UI.WebControls;

using System.Data;

using System.Data.SqlClient;

using System.Drawing;

using System.Globalization;

using System.IO;

using System.Collections;

using System.Configuration;

using iTextSharp.text;

using iTextSharp.text.html.simpleparser;

using iTextSharp.text.pdf;

using System.Web.UI.HtmlControls;

using System.Text;

 

public partial class Excel_and_Pdf : System.Web.UI.Page

{

    private SqlConnection con = new SqlConnection("Data Source=gopi-pc;Integrated Security=true;Initial Catalog=MySamplesDB");

 

    protected void Page_Load(object sender, EventArgs e)

    {

        if (!IsPostBack)

        {

 

            gridBind();

        }

    }

    protected void Rd_SelectedIndexChanged(object sender, EventArgs e)

    {

        if (Rd.SelectedItem.Text == "Excel")

        {

            hdvalue.Value = "Xls";

        }

        else if (Rd.SelectedItem.Text == "Pdf")

        {

            hdvalue.Value = "pdf";

        }

        else if (Rd.SelectedItem.Text == "CSV")

        {

            hdvalue.Value = "CSV";

        }

 

        else if (Rd.SelectedItem.Text == "Word")

        {

            hdvalue.Value = "Word";

        }

 

        else if (Rd.SelectedItem.Text == "CSV1")

        {

            hdvalue.Value = "CSV1";

        }

    }

 

    protected void Btndownload_Click(object sender, EventArgs e)

    {

        if (hdvalue.Value == "Xls")

        {

            excel();

        }

        else if (hdvalue.Value == "pdf")

        {

            pdf();

        }

 

        else if (hdvalue.Value == "CSV")

        {

            CSV();

        }

        else if (hdvalue.Value == "Word")

        {

            Word();

        }

        else if (hdvalue.Value == "CSV1")

        {

            CSV1();

        }

        else

        {

            //ur data

 

            hdvalue.Value = string.Empty;

        }

    }

 

    private void gridBind()

    {

        //hi gobi  Load grid Value  ur function or query and get one viewsate beleow ur example

        // MIS_data.MIS_info()-----> grid select query

        con.Open();

        SqlCommand cmd = new SqlCommand("select * from User_Information", con);

        SqlDataAdapter da = new SqlDataAdapter(cmd);

        DataSet ds = new DataSet();

        // ds.Tables[0] = ds;

        da.Fill(ds);

        con.Close();

        //DataView dv = new DataView(MIS_data.MIS_info());

        //ViewState["gv"] = dv.ToTable();

        //gvdetails.DataSource = dv;

        gvdetails.DataSource = ds;

        gvdetails.DataBind();

        ViewState["gv"] = ds.Tables[0];

    }

    private void excel()

    {

        DataTable dt = new DataTable();

        dt = (DataTable)ViewState["gv"];

        Response.Clear();

        Response.Buffer = true;

        string attachment = "attachment; filename=city.xls";

        //Response.AddHeader("content-disposition", string.Format("attachment; filename={0}", "Details.xls"));

        Response.ClearContent();

        // Response.AddHeader("content-disposition", "attachment;filename=GridViewExport.xls");

        //Response.Charset = "";

        Response.AddHeader("content-disposition", attachment);

        Response.ContentType = "application/vnd.ms-excel";

        //StringWriter sw = new StringWriter();

        //HtmlTextWriter hw = new HtmlTextWriter(sw);

        string tab = "";

        foreach (DataColumn dc in dt.Columns)

        {

            Response.Write(tab + dc.ColumnName);

            tab = "\t";

        }

        Response.Write("\n");

        int i;

        foreach (DataRow dr in dt.Rows)

        {

            tab = "";

            for (i = 0; i < dt.Columns.Count; i++)

            {

                Response.Write(tab + dr[i].ToString());

                tab = "\t";

            }

            Response.Write("\n");

        }

        Response.End();

    }

    private void CSV()

    {

        try

        {

            Response.ClearContent();

            string attachment = "attachment; filename=MyExelFile.xls";

            Response.ClearContent();

            Response.AddHeader("content-disposition", attachment);

            Response.ContentType = "application/ms-excel";

            StringWriter strWrite = new StringWriter();

            HtmlTextWriter htmWrite = new HtmlTextWriter(strWrite);

            HtmlForm htmfrm = new HtmlForm();

            gvdetails.Parent.Controls.Add(htmfrm);

            htmfrm.Attributes["runat"] = "server";

            htmfrm.Controls.Add(gvdetails);

            htmfrm.RenderControl(htmWrite);

            Response.Write(strWrite.ToString());

            Response.Flush();

            Response.End();

        }

        catch (Exception ex) { }

    }

    private void CSV1()

    {

        try

        {

            Response.ClearContent();

            Response.AddHeader("content-disposition", "attachment;filename=MyCsvFile.csv");

            Response.ContentType = "application/text";

            StringBuilder strBr = new StringBuilder();

            for (int i = 0; i < gvdetails.Columns.Count; i++)

            {

                strBr.Append(gvdetails.Columns[i].HeaderText + ',');

            }

            strBr.Append("\n");

            for (int j = 0; j < gvdetails.Rows.Count; j++)

            {

                for (int k = 0; k < gvdetails.Columns.Count; k++)

                {

                    strBr.Append(gvdetails.Rows[j].Cells[k].Text + ',');

                }

                strBr.Append("\n");

            }

            Response.Write(strBr.ToString());

            Response.Flush();

            Response.End();

        }

        catch (Exception ex) { }

    }

    private void pdf()

    {

        //using (StringWriter sw = new StringWriter())

        //{

        //    using (HtmlTextWriter hw = new HtmlTextWriter(sw))

        //    {

        //To Export all pages

        //gvdetails.AllowPaging = false;

        //this.gridBind();

        //DataTable dt = new DataTable();

        //dt = (DataTable)ViewState["gv"];

        //gvdetails.RenderControl(hw);

        //StringReader sr = new StringReader(sw.ToString());

        //Document pdfDoc = new Document(PageSize.A2, 10f, 10f, 10f, 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();

        //        gridBind();

        //        Response.ContentType = "application/pdf";

        //        Response.AddHeader("content-disposition", "attachment;filename=Details.pdf");

        //        Response.Cache.SetCacheability(HttpCacheability.NoCache);

        //        //StringWriter sw = new StringWriter();

        //        //HtmlTextWriter hw = new HtmlTextWriter(sw);

        //        gvdetails.RenderControl(hw);

        //        //gvdetails.RenderControl(hw);

        //        StringReader sr = new StringReader(sw.ToString());

        //        Document pdfDoc = new Document(PageSize.A4, 10f, 10f, 10f, 0f);

        //        HTMLWorker htmlparser = new HTMLWorker(pdfDoc);

        //        PdfWriter.GetInstance(pdfDoc, Response.OutputStream);

        //        pdfDoc.Open();

        //        htmlparser.Parse(sr);

        //        pdfDoc.Close();

        //        Response.Write(pdfDoc);

        //        Response.End();

        //    }

        //}

 

        try

        {

            Response.ClearContent();

            Response.ContentType = "application/pdf";

            Response.AddHeader("content-disposition", "attachment;filename=MyPdfFile.pdf");

            Response.Cache.SetCacheability(HttpCacheability.NoCache);

            StringWriter strWrite = new StringWriter();

            HtmlTextWriter htmWrite = new HtmlTextWriter(strWrite);

            HtmlForm frm = new HtmlForm();

            gvdetails.Parent.Controls.Add(frm);

            frm.Attributes["runat"] = "server";

            frm.Controls.Add(gvdetails);

            frm.RenderControl(htmWrite);

            StringReader sr = new StringReader(strWrite.ToString());

            Document pdfDoc = new Document(PageSize.A4, 8f, 8f, 8f, 2f);

            HTMLWorker htmlparser = new HTMLWorker(pdfDoc);

            PdfWriter.GetInstance(pdfDoc, Response.OutputStream);

            pdfDoc.Open();

            htmlparser.Parse(sr);

            pdfDoc.Close();

            Response.Write(pdfDoc);

            Response.Flush();

            Response.End();

        }

        catch (Exception ex) { }

    }

    private void Word()

    {

        try

        {

            Response.ClearContent();

            Response.AddHeader("content-disposition", "attachment;filename=MyWordFile.doc");

            Response.Cache.SetCacheability(HttpCacheability.NoCache);

            Response.Buffer = true;

            Response.Charset = "";

            Response.ContentType = "application/vnd.word";

            StringWriter strWrite = new System.IO.StringWriter();

            HtmlTextWriter htmWrite = new HtmlTextWriter(strWrite);

            HtmlForm htmfrm = new HtmlForm();

            gvdetails.Parent.Controls.Add(htmfrm);

            gvdetails.AllowPaging = false;

            htmfrm.Attributes["runat"] = "server";

            htmfrm.Controls.Add(gvdetails);

            htmfrm.RenderControl(htmWrite);

            Response.Write(strWrite.ToString());

            Response.Flush();

            Response.End();

        }

        catch (Exception ex) { }

    }

    public DataTable mis { get; set; }

}
 
Step 4: (Added Bin directory inside Itextsharp.dll)

Screen Shot:

Added Bin directory
 
Step 5:

Radio Button
 
Step 6: (Select the Radio button after clicking on the download button to download in the desired format.)

 
Selecting Radio button