Exporting GridView to Excel

Posted: Thursday, December 22, 2005 in asp.net

In the project that Im current working, there was a requirement to export the data, which is in a GridView to Excel.

Normally I used the below method in old projects with DataGrid

Response.Clear();
Response.AddHeader(“content-disposition”, “attachment;filenameAlldata.xls”);
Response.Charset “”;
Response.Cache.SetCacheability(HttpCacheability.NoCache);
Response.ContentType “application/vnd.ms-excel”;
System.IO.StringWriter stringWrite new System.IO.StringWriter();
System.Web.UI.HtmlTextWriter htmlWrite new HtmlTextWriter(stringWrite);
DGMain.RenderControl(htmlWrite);
Response.Write(stringWrite.ToString());
Response.End();

But changing the
DGMain.RenderControl(htmlWrite);

To GridView
GVMain.RenderControl(htmlWrite);

It gave an error saying
Control ‘ GVMain ‘ of type ‘GridView’ must be placed inside a form tag with runatserver.

Well after serching the solution for this I got the answer in ASP.NET Forums.
You need to put this code in your .aspx

public override void VerifyRenderingInServerForm(Control control)
{
}

this method Confirms that an HtmlForm control is rendered for the specified ASP.NET server control at run time.
Finally the export worked.

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s