0
votes

On pressing Button1, the contents of gridview1 should be exported to excel. Whereas I encounter the following error:

System.Web.HttpException: 'Control 'GridView1' of type 'GridView' must be placed inside a form tag with runat=server.'

and when I completely removed the content of the override VerifyRenderingInServerForm() method as shown in one of the youtube videos, I get the following error:

System.InvalidOperationException: 'RegisterForEventValidation can only be called during Render();'

   protected void Button1_Click(object sender, EventArgs e)
    {
        Response.Clear();
        Response.AppendHeader("content-disposition", "attachment; filename=student.xls");
        Response.ContentType = "application/excel";
        StringWriter strw = new StringWriter();
        HtmlTextWriter htmltw = new HtmlTextWriter(strw);
        GridView1.RenderControl(htmltw);

        Response.Write(strw.ToString());
        Response.End();
    }
    public override void VerifyRenderingInServerForm(Control control)
    {
         base.VerifyRenderingInServerForm(control);
    }
1
Start using a specialized library for creating Excel files, like EPPlus. Example here and here. All you are doing now is creating a HTML page with an .xls extension.VDWWD

1 Answers

0
votes

The solution was to disable event validation in the page properties
<%@ Page ............ EnableEventValidation="false" %>