none
GridView导出EXCEL问题 RRS feed

  • 问题

  • 问题描述:有一个GridView,需要把里面的内容导出到EXCEL里。GridView里有checkbox控件。现在在导出得时候系统报错(F5调试,设断点),错误提示如下:“只能在执行 Render() 的过程中调用 RegisterForEventValidation;”。个人认为是checkbox引起的,但不知道怎么解决。请大家指点下。导出的代码如下:

     

    private void ToExcel( GridView gvToExcel )
    {
                Response.ClearContent();
                Response.AddHeader( "content-disposition", "attachment; filename=QDL" + DateTime.Now.ToString( "yyyyMMdd" ) + ".xls" );
                Response.Charset = "gb2312";
                Response.ContentType = "application/excel";
                StringWriter sw = new StringWriter();
                HtmlTextWriter htw = new HtmlTextWriter( sw );

                gvToExcel.AllowPaging = false;
                DataBound();

                gvToExcel.RenderControl( htw );     错误出在这一行
                Response.Write( sw.ToString() );
                Response.End();

                gvToExcel.AllowPaging = true;
                DataBound();
    }

    public override void VerifyRenderingInServerForm( Control control )
    {

    }

    2008年8月26日 3:21

答案

全部回复

  • 解决办法和代码参见
    http://hi.baidu.com/ly_baidu/blog/item/683cdca264701ca9caefd070.html
    2008年8月26日 3:27
    版主
  •  

    在导出前,调用下这个方法,把textbox加进去就好了。

     

    private void DisableControls(Control gv)
    {
        LinkButton lb = new LinkButton();
        Literal l = new Literal();
        string name = String.Empty;

        for (int i = 0; i < gv.Controls.Count; i++)
        {
            if (gv.ControlsIdea.GetType() == typeof(LinkButton))
            {
                l.Text = (gv.ControlsIdea as LinkButton).Text;
                gv.Controls.Remove(gv.ControlsIdea);
                gv.Controls.AddAt(i, l);
            }
            else if (gv.ControlsIdea.GetType() == typeof(DropDownList))
            {
                l.Text = (gv.ControlsIdea as DropDownList).SelectedItem.Text;
                gv.Controls.Remove(gv.ControlsIdea);
                gv.Controls.AddAt(i, l);
            }

            if (gv.ControlsIdea.HasControls())
            {
                DisableControls(gv.ControlsIdea);
            }
        }
    }

    2008年8月26日 3:31