使用C#从asp.net中的转发器控件打印数据

时间:2010-12-08 12:56:34

标签: asp.net

我用来从转发器打印数据时出现此错误

“只能在Render();”

期间调用RegisterForEventValidation

我已经在page指令中设置了EnableEventValidation =“false” 以及我的应用程序在页面标记内的web.config

这是我用于

的代码
public static void PrintWebControl(Control ctrl, string Script)
{

    StringWriter stringWrite = new StringWriter();

    HtmlTextWriter htmlWrite = new HtmlTextWriter(stringWrite);

    if (ctrl is WebControl)
    {

        Unit w = new Unit(50, UnitType.Pixel);

        ((WebControl)ctrl).Width = w;

    }

    Page pg = new Page();      


    if (Script != string.Empty)
    {

        pg.RegisterStartupScript("PrintJavaScript", Script);

    }

    HtmlForm frm = new HtmlForm();

    pg.Controls.Add(frm);

    frm.Attributes.Add("runat", "server");

    frm.Controls.Add(ctrl);

    string scr = "<script>function window.onafterprint(){history.back(1);}</script>";

    htmlWrite.Write(scr);



    pg.DesignerInitialize();

    pg.RenderControl(htmlWrite);       




    string strHTML = stringWrite.ToString();

    HttpContext.Current.Response.Clear();

    HttpContext.Current.Response.Write(strHTML);

    HttpContext.Current.Response.Write("<script>window.print();</script>");

    HttpContext.Current.Response.End();

}

2 个答案:

答案 0 :(得分:1)

替换

Page pg = new Page();       

Page pg = new Page();               
pg.EnableEventValidation = false;

答案 1 :(得分:0)

覆盖Render方法,并调用:

Page.ClientScript.RegisterForEventValidation(..)

并传递此处定义的选项:http://msdn.microsoft.com/en-us/library/system.web.ui.clientscriptmanager.registerforeventvalidation.aspx

HTH。