0

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);
    }
Muhammad Usman Bashir
  • 1,441
  • 2
  • 14
  • 43
Gaurav Thapa
  • 89
  • 10
  • 1
    Start using a specialized library for creating Excel files, like [EPPlus](https://github.com/JanKallman/EPPlus). [Example here](https://stackoverflow.com/a/47293207/5836671) and [here](https://stackoverflow.com/questions/52002573/send-excel-email-attachment-c-sharp). All you are doing now is creating a HTML page with an .xls extension. – VDWWD Mar 05 '20 at 07:45

1 Answers1

1

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

Gaurav Thapa
  • 89
  • 10