Friday, July 17, 2009

Expost Data to Excel from asp.net GridView

Hi.
This is the code i Learn to Expost data to Excel file from GridView.
You Have to make EnableEventValidation="false" to run this code Without any error.
other wise it will Throw Exception RegisterForEventValidation can only be called during Render();
Here is the Code.

protected void btnExport_Click(object sender, EventArgs e)
{
this.grvCountry.AllowPaging = false;
this.grvCountry.AllowSorting = false;
this.grvCountry.EditIndex = -1;
Response.Clear();
Response.ContentType = "application/vnd.xls";
Response.AddHeader("content-disposition", "attachment;filename=Countries.xls");
StringWriter swriter = new StringWriter();
HtmlTextWriter hwriter = new HtmlTextWriter(swriter);
HtmlForm frm = new HtmlForm();
this.grvCountry.Parent.Controls.Add(frm);
frm.Attributes["runat"] = "server";
frm.Controls.Add(this.grvCountry);
frm.RenderControl(hwriter);
Response.Write(swriter.ToString());
Response.End();
}

Thanks.