必须将’GridView’放在带有runat = server的表单标记内。

所以,我研究了你的网站,我的情况很独特。 我有一个Web控件.ascx,它有一个gridview,代码如下所示:

 

我有一个下载到Excel按钮,执行以下代码:

 protected void dwnLoad(object sender, EventArgs e) { Response.Clear(); Response.AddHeader("content-disposition", "attachment; filename=kbNotification.xls"); Response.Charset = ""; Response.Cache.SetCacheability(HttpCacheability.NoCache); Response.ContentType = "application/vnd.xls"; System.IO.StringWriter stringWrite = new System.IO.StringWriter(); System.Web.UI.HtmlTextWriter htmlWriter = new HtmlTextWriter(stringWrite); GridView1.RenderControl(htmlWriter); Response.End(); } 

当我按下按钮时,我发现以下错误:

  Exception Details: System.Web.HttpException: Control 'pagecontent_0_GridView1' of type 'GridView' must be placed inside a form tag with runat=server. Source Error: Line 54: Response.Cache.SetCacheability(HttpCacheability.NoCache); Line 55: Response.ContentType = "application/vnd.xls"; Line 56: System.IO.StringWriter stringWrite = new System.IO.StringWriter(); Line 57: System.Web.UI.HtmlTextWriter htmlWriter = new HtmlTextWriter(stringWrite); Line 58: GridView1.RenderControl(htmlWriter); Source File: C:\Projects\MEAU\trunk\Code\MEAU.Web\Components\SupportCenter\KB_Notification_rpt.ascx.cs Line: 56 

我试图将以下方法添加到代码隐藏:

 public override void VerifyRenderingInServerForm(Control control) { return; } 

这不起作用,因为这是一个.ascx页面,所以我也尝试将它添加到我的default.aspx页面…并且仍然得到错误,它找不到覆盖的方法。

请帮助,如果你能发现任何不正确的东西,我将不胜感激。 问候,

 protected void Page_Load(object sender, EventArgs e) { btnExcel_Click +=................ if (!IsPostBack) { BindGridview(); } } protected void BindGridview() { gvdetails.DataSourceID = "dsdetails"; } public override void VerifyRenderingInServerForm(Control control) { /* Verifies that the control is rendered */ } protected void btnExcel_Click(object sender, ImageClickEventArgs e) { Response.ClearContent(); Response.Buffer = true; Response.AddHeader("content-disposition", string.Format("attachment; filename={0}", "Customers.xls")); Response.ContentType = "application/ms-excel"; StringWriter sw = new StringWriter(); HtmlTextWriter htw = new HtmlTextWriter(sw); gvdetails.AllowPaging = false; BindGridview(); //Change the Header Row back to white color gvdetails.HeaderRow.Style.Add("background-color", "#FFFFFF"); //Applying stlye to gridview header cells for (int i = 0; i < gvdetails.HeaderRow.Cells.Count; i++) { gvdetails.HeaderRow.Cells[i].Style.Add("background-color", "#df5015"); } gvdetails.RenderControl(htw); Response.Write(sw.ToString()); Response.End(); } 

使用此代码将数据从gridView下载到excel。

WebControl(ascx)不应包含标记。

它生成一个HTML片段,它应该放在HTML页面内部和asp:Form元素内部。

按照两个步骤

步骤1

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

第2步

 EnableEventValidation="false"