Sometime I get "RegisterForEventValidation can only be called during Render" error or "Control 'GridView1' of type 'GridView' must be placed inside a form tag with runat=server" error while implementing export to excel functionality in my application. Let's see what is it all about.
I was implementing export to excel functionality in my application. I had a GridView and was using this to get data into my export to excel method. Suddenly I got this error - "Control 'GridView1' of type 'GridView' must be placed inside a form tag with runat=server". It was shocking because my grid was already in <form> tag.
protected void ButtonExport_Click(object sender, EventArgs e)
{
Response.Clear();
Response.AddHeader("content-disposition",
string.Format("attachment;filename={0}.xls", "Order"));
Response.Charset = "";
Response.ContentType = "application/vnd.xls";
StringWriter stringWrite = new StringWriter();
HtmlTextWriter htmlWrite = new HtmlTextWriter(stringWrite);
GridView1.RenderControl(htmlWrite);
Response.Write(stringWrite.ToString());
Response.End();
}
My code was throwing rendering error. It was throwing error at "GridView1.RenderControl(htmlWrite);" line.
Simply add these line of code in your page and you can continue with your task without any hassle.
public override void VerifyRenderingInServerForm(Control control)
{
//Leave blank
}
Add EnableEventValidation="false" in page directive.
Hope it can help you.