View Single Post
  #8 (permalink)  
Old February 1st, 2007, 01:42 PM
robgerwing robgerwing is offline
Registered User
Join Date: Feb 2007
Location: Golden, CO, USA.
Posts: 2
Thanks: 0
Thanked 0 Times in 0 Posts

Here is the technique I use that have worked with me. I use master page as well. So hope this helps. You will see I added couple other things. This is base on ASP.NET 2.0 page. This is obviously a combination of different source on the internet and Imar's suggestion above creating new control.

1) On your ASPX add to Page Directive EnableEventValidation="false" Only use if the page complains about RenderControl must be in Form tag.

2) On the code behind of ASPX page as the following constructor:

public override void VerifyRenderingInServerForm(Control control)
        // Confirms that an HtmlForm control is rendered for the specified ASP.NET server control at run time.
3) On the code behind of your grid (either aspx or if load on user control put there) This works if Session is not controled in SQL DB.

//First Step
//Declare Grid control after public partial class

public GridView GridView1 = new GridView();

//Second Step Method for button onclick

protected void btnExport_Click(object sender, EventArgs e) {

        Response.AddHeader("content-disposition", "attachment; filename=FileName_"+DateTime.Now.ToShortDateString ().Replace("/","_")+".xls");

        Response.Charset = "";
        // If you want the option to open the Excel file without saving than
        // comment out the line below
        // Response.Cache.SetCacheability(HttpCacheability.No Cache);
        Response.ContentType = "application/";
        System.IO.StringWriter stringWrite = new System.IO.StringWriter();
        System.Web.UI.HtmlTextWriter htmlWrite = new HtmlTextWriter(stringWrite);

        //Reference the originally renders grid id name and your data source
        Session["ExportGridviewColumns"] = this.gvList.Columns;
        Session["ExportGridViewDataSource"] = this.objDsList.Select();

        //Add the columns to the print gridview
        foreach (DataControlField dcf in (DataControlFieldCollection)Session["ExportGridviewColumns"])

        //Turning off paging will avoid errors and get all contents
        //Provide some basic attributes to make excel data pretty

        GridView1.AllowPaging = false;
        GridView1.AllowSorting = false;
        GridView1.Font.Name = "Verdana";
        GridView1.Font.Size = 8;

        //Using ObjectDataSource Grabs Entire Contents
        this.GridView1.DataSource = Session["ExportGridViewDataSource"];



        Response.End(); }