1

我的用户控件中有网格视图,但出现以下错误:

RegisterForEventValidation can only be called during Render();

我在用gv.RenderControl(htw);

我的代码如下:

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();
    }

为了避免在表单控件异常之外创建服务器控件,我使用以下代码:

public override void VerifyRenderingInServerForm(Control control)
{
    /* Verifies that the control is rendered */
}

但是我在用户控件中使用了所有这些代码,基类中没有这个方法。我应该怎么做,即使我放在我放置用户控件的页面的上方,但我仍然遇到错误

另请注意,我正在使用已标记表单的母版页。

4

2 回答 2

1

将页面指令中的 EnableEventValidation 设置为 false 解决了我的问题。

 <%@ Page ............ EnableEventValidation="false" %>
于 2013-07-14T10:02:59.797 回答
0

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()
于 2013-07-11T00:42:11.207 回答