Wednesday, July 9, 2008

Export Gridview to Excel with ASP.NET (workaround)

Today I had to create a grid in ASP.Net. But i had this problem when i created the export to Excel:
'GridView' must be placed inside a form tag with runat=server

My gridview was inside the form ???

So this is the workaround i found:

This is the normal function for the export to Excel:

Response.Clear();
Response.AddHeader(
"content-disposition", "attachment;filename=filename.xls");
Response.Charset
= "";
Response.Cache.SetCacheability(HttpCacheability.NoCache);
Response.ContentType
= "application/vnd.xls";
System.IO.StringWriter stringWrite
= new System.IO.StringWriter();
System.Web.UI.HtmlTextWriter htmlWrite
= new HtmlTextWriter(stringWrite);
GridView1.RenderControl(htmlWrite);
Response.Write(stringWrite.ToString());
Response.End();

/* Confirms that an HtmlForm control is rendered for the specified ASP.NET server control at run time. */
public override void VerifyRenderingInServerForm(Control control){}


Just insert this inside your code behind:



More info you can find here @ microsoft (Microsoft has accepted it as bug)

No comments: