user5547019
user5547019

Reputation:

Export GridView to Excel not working when AllowSorting set to true

I'm displaying some Data from a Sql Database through ObjectDataSource in a GridView. I've also enabled the user to export the data to excel with this code :

  public override void VerifyRenderingInServerForm(Control control)
{

}



private void ExportGridToExcel()
{
    Response.Clear();
    Response.Buffer = true;
    Response.ClearContent();
    Response.ClearHeaders();
    Response.Charset = "";
    string FileName = "Results" + DateTime.Now + ".xls";
    StringWriter strwritter = new StringWriter();
    HtmlTextWriter htmltextwrtter = new HtmlTextWriter(strwritter);
    Response.Cache.SetCacheability(HttpCacheability.NoCache);
    Response.ContentType = "application/vnd.ms-excel";
    Response.AddHeader("Content-Disposition", "attachment;filename=" + FileName);
    GridView1.GridLines = GridLines.Both;
    GridView1.HeaderStyle.Font.Bold = true;
    GridView1.RenderControl(htmltextwrtter);
    Response.Write(strwritter.ToString());
    Response.End();

}


protected void Button3_Click(object sender, EventArgs e)
{
    ExportGridToExcel();
}

All working fine. However, when I set AllowSorting=true in my GridView and click the export button I get following error: ystem.InvalidOperationException:

RegisterForEventValidation can only be called during Render();

It's not a massive issue as I don't necessarily need to allow sorting in the GridView but I'm curious what the issue is?

Upvotes: 3

Views: 334

Answers (1)

Bolo
Bolo

Reputation: 1500

Add this attribute to the @ Page declaration:

EnableEventValidation="false"

Upvotes: 1

Related Questions