Exporting GridView to Excel ‘GridView’ must be placed inside a form tag
This article explains how you can export your GridView control to Excel files. If you are working with GridView.
Exporting Grid View to Excel Files:
The approach is pretty much the same as it was in Gridview. The following code executes on a button click event.
protected void _btnReports_Click(object sender, EventArgs e)
{
Response.Clear();
Response.Write(@”<!DOCTYPE HTML PUBLIC “”-//W3C//DTD HTML 4.0 Transitional//EN”">”);
Response.AddHeader(“content-disposition”, “inline;filename=search_topicarea.doc”);
Response.Charset = “”;
Response.Cache.SetCacheability(HttpCacheability.NoCache);
Response.ContentType = “application/vnd.doc”;
System.IO.StringWriter stringWrite = new System.IO.StringWriter();
//System.Web.UI.HtmlTextWriter htmlWrite = new HtmlTextWriter(stringWrite);
System.Web.UI.HtmlTextWriter htmlWrite = new HtmlTextWriter(stringWrite);
//Render(htmlWrite);
_gvViewresults.RenderControl(htmlWrite);
Response.Write(stringWrite.ToString());
Response.End();
}
The above shown code is almost identical to what we normally use when exporting Gridview to some other formats. But if you run this code it will not work, the reason is that we need to tell ASP.NET that there is a control in our form that will be rendered at runtime.
In order to work the above shown code you need to add some piece of code as shown below i.e just override the Page.VerifyRenderingInServerForm method.
public override void VerifyRenderingInServerForm(Control control)
{
// Confirms that an HtmlForm control is rendered for the
//specified ASP.NET server control at run time.
}
Now if you try to export your GridView to excel it will work fine.
Happy Coding……….
No comments
No comments yet. Be the first.
Leave a reply
