C# 从GridView导出到Excel时出现异常

C# 从GridView导出到Excel时出现异常,c#,asp.net,gridview,export-to-excel,C#,Asp.net,Gridview,Export To Excel,我的代码如下: .cs文件: protected void ExporttoExcel_Click(object sender, EventArgs e) { ExportGridToExcel(GridView2, "myExcel"); } public void ExportGridToExcel(GridView grdGridView, string fileName) { Response.Clear(); Response.AddH

我的代码如下:

.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
控件导出为
Word
Excel
PDF
CSV
或任何其他格式时,会发生异常。在这里,
.net编译器
认为控件未添加到表单中,并且已呈现,因此即使您的
GridView
控件位于带有
runat=“server”
的表单中,它也会抛出此错误

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

代码

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

异常更改为:RegisterForEventValidation只能在Render()期间调用;将
EnableEventValidation=“false”
添加到源页面的
@Page指令
。例如,
它说excel的文件格式不匹配。我们如何更改excel的格式?现在没有例外:)只需将代码中的
.xls
更改为
.xlsx
即可。