无法渲染网格视图

时间:2013-07-11 00:23:37

标签: asp.net c#-4.0 gridview

我的用户控件中有网格视图,我收到以下错误:

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 */
}

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

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

2 个答案:

答案 0 :(得分:1)

将page指令中的EnableEventValidation设置为false可以解决我的问题。

 <%@ Page ............ EnableEventValidation="false" %>

答案 1 :(得分: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()