从 GridView 导出到 Excel 会出现异常

Export to Excel from GridView gives exception

我的代码如下:

.cs 文件:

protected void ExporttoExcel_Click(object sender, EventArgs e)
    {
        ExportGridToExcel(GridView2, "myExcel");
    }
public void ExportGridToExcel(GridView grdGridView, string fileName)
{
    Response.Clear();
    Response.AddHeader("content-disposition", string.Format("attachment;filename={0}.xls", fileName));
    Response.Charset = "";
    Response.ContentType = "application/vnd.xls";

    StringWriter stringWrite = new StringWriter();
    HtmlTextWriter htmlWrite = new HtmlTextWriter(stringWrite);
    GridView2.RenderControl(htmlWrite);
    Response.Write(stringWrite.ToString());
    Response.End();
}

代码在执行期间中断以给出此异常:

Control 'GridView2' of type 'GridView' must be placed inside a form tag with runat=server.

编辑:

我还在 .aspx 中粘贴网格视图代码,以防需要。

.aspx 中的网格视图代码:

 <form id="form2" runat="server">

      <div align="center" class="animated pulse">
        <h1 style="color:#fff400;text-align:center;font-family:Ostrich3;font-size:4vw;" class=" animated pulse" >AUTOMATION RUNS</h1>
      </div>

        <asp:SqlDataSource ProviderName="System.Data.SqlClient" ID = "sourceProducts" runat = "server" ConnectionString = " <%$ ConnectionStrings:testdb %> " SelectCommand = "(my query here)" />

          <div align="center>  

            <asp:GridView ID = "GridView2" runat = "server" HorizontalAlign="Center" 
            DataSourceID = "sourceProducts" AutoGenerateColumns = "False" CssClass="mGrid animated fadeInUp" AllowPaging="True" AllowSorting="True" PageSize="25"  HeaderStyle-HorizontalAlign="Center" Height="22px" Width="1700px" >
             <RowStyle Height="5px" />
                <Columns> 
                (my columns here)
                </Columns>
            </asp:GridView>
        </div>
       <asp:Button runat="server" ID="ExporttoExcel" OnClick="ExporttoExcel_Click" /> 
      </for

当试图将 GridView 控件导出为 WordExcelPDFCSV 或任何其他格式时会发生异常。这里 .net compiler 认为控件未添加到表单并被呈现,因此即使您的 GridView 控件位于带有 runat = “server”.[=20= 的表单内,它也会抛出此错误]

通过重写 VerifyRenderingInServerForm 事件告诉编译器控件已显式呈现。您可以通过将事件添加到代码隐藏文件来实现。

代码

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