Reputation: 885
I have grid view in my user control, and I am getting below error:
RegisterForEventValidation can only be called during Render();
I am using gv.RenderControl(htw);
My code is as below:
private void ExportToExcel(string strFileName, GridView gv)
{
Response.ClearContent();
Response.AddHeader("content-disposition", "attachment; filename=" + strFileName);
Response.ContentType = "application/excel";
System.IO.StringWriter sw = new System.IO.StringWriter();
HtmlTextWriter htw = new HtmlTextWriter(sw);
gv.RenderControl(htw);
Response.Write(sw.ToString());
Response.End();
}
And to avoid Server control was created outside form control exception I am using below code:
public override void VerifyRenderingInServerForm(Control control)
{
/* Verifies that the control is rendered */
}
But I'm using all this code in a usercontrol, There isn't this method in the base class. What should I do, even I placed above in my page in which I place my user control, but still I am getting above error
Also note I am using masterpage in which I have form tagged already.
Upvotes: 1
Views: 1674
Reputation: 885
Setting EnableEventValidation in page directive to false solved my problem.
<%@ Page ............ EnableEventValidation="false" %>
Upvotes: 1
Reputation: 1117
C#
StringWriter sw = new StringWriter();
HtmlTextWriter hw = new HtmlTextWriter(sw);
Page pg = new Page();
HtmlForm hf = new HtmlForm();
hf.Attributes.Add("runat", "server");
hf.Controls.Add(gv);
pg.EnableEventValidation = false;
pg.Controls.Add(hf);
pg.DesignerInitialize();
pg.RenderControl(hw);
Current.Response.Clear();
Current.Response.AddHeader("content-disposition", "attachment;filename=FileName.xls");
Current.Response.Charset = string.Empty;
Current.Response.ContentType = "application/vnd.xls";
Current.Response.Write(sw.ToString());
Current.Response.End();
VB.NET
Dim sw As New StringWriter
Dim hw As New HtmlTextWriter(sw)
Dim pg As New Page()
Dim hf As New HtmlForm()
hf.Attributes.Add("runat", "server")
hf.Controls.Add(gv)
pg.EnableEventValidation = False
pg.Controls.Add(hf)
pg.DesignerInitialize()
pg.RenderControl(hw)
Current.Response.Clear()
Current.Response.AddHeader("content-disposition", "attachment;filename=FileName.xls")
Current.Response.Charset = String.Empty
Current.Response.ContentType = "application/vnd.xls"
Current.Response.Write(sw.ToString())
Current.Response.End()
Upvotes: 0