To Render Or Not To Render
Posted
26. rujan 2007 21:52
by
dadamec
We run into ASP.NET 2.0 run-time error when trying to export GridView to Excel.
Simple method we used look like:
public void GridView2Excel(GridView CurrGridView, string FileName)
{
HttpContext.Current.Response.Clear();
HttpContext.Current.Response.AddHeader("content-disposition", "attachment;filename=" + FileName);
HttpContext.Current.Response.Charset = "";HttpContext.Current.Response.ContentType = "application/vnd.xls";
System.IO.StringWriter stringWriter = new System.IO.StringWriter();
System.Web.UI.HtmlTextWriter htmlWrite = new HtmlTextWriter(stringWriter);
CurrGridView.RenderControl(htmlWriter);
HttpContext.Current.Response.Write(stringWrite.ToString());
HttpContext.Current.Response.End();
}
And the methods throws run-time error saying "...of type 'GridView' must be placed inside a form tag with runat=server". And our GridView was of course inside the form tag with runat=server tag.
It happens that RenderControl throwing error - because of the "wrong timing" in page life cycle it couldn't find the GridView inside Form tag.
The workaround is simple: just override the Page.VerifyRenderingInServerForm method.
public
override void VerifyRenderingInServerForm(Control control)
{
}
And be sure that you don't need her original actions - checking if all server controls are inside the server form tag! Don't forget that ASP.NET page would not work as expected if you forgot this rule.