Search code examples
c#asp.netgridviewexport-to-excel

Export to Excel from GridView gives exception


My code is as below :

.cs file :

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();
}

The code breaks during execution to give this exception :

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

Edit :

I am also pasting the grid view code in .aspx incase its required.

Grid view code in .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

Solution

  • The exception occurs when one tries to export a GridView control to Word, Excel, PDF, CSV or any other formats. Here the .net compiler thinks that the control is not added to the form and is rendered, hence it throws this error even if your GridView control is inside a form with runat = “server”.

    Tell the compiler that the control is rendered explicitly by overriding the VerifyRenderingInServerForm event. You can do that by adding the event to the code behind file.

    Code

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