导出excel时报错:类型“GridView”的控件“GridView1”必须放在具有 runat=server 的窗体标记内。

在把数据导出到excel的时候,有时候会这样的错误:类型“GridView”的控件“GridView1”必须放在具有 runat=server 的窗体标记内。

System.Web.UI.Control ctl=this.GridView1;
//DataGrid1 是你在窗体中拖放的控件
HttpContext.Current.Response.AppendHeader("Content-Disposition","attachment;filename=Excel.xls");
HttpContext.Current.Response.Charset ="UTF-8";    
HttpContext.Current.Response.ContentEncoding =System.Text.Encoding.Default;
HttpContext.Current.Response.ContentType ="application/ms-excel";
ctl.Page.EnableViewState =false;   
System.IO.StringWriter  tw = new System.IO.StringWriter() ;
System.Web.UI.HtmlTextWriter hw = new System.Web.UI.HtmlTextWriter (tw);
ctl.RenderControl(hw);
HttpContext.Current.Response.Write(tw.ToString());
HttpContext.Current.Response.End();

  解决方法可以在页面中的cs文件里加上:

public override void VerifyRenderingInServerForm(Control control)
{
     //base.VerifyRenderingInServerForm(control);
}

你可能感兴趣的:(GridView)