Check our online training feedbacks Here

05 May 2011

Export Gridview to Excel

1.Populate the Gridview ->MyGridview with the Data.
2.Override the VerifyRenderingInServerForm method. as
public override void VerifyRenderingInServerForm(Control control)

3.Use the following Code snippet (In button click or somewhere) - It will just export the grid into excel.
Response.AddHeader("content-disposition", "attachment; filename=MyExcelFile.xls");
Response.ContentType = "application/excel";
StringWriter sw = new StringWriter();
HtmlTextWriter htw = new HtmlTextWriter(sw);

Points to remember:-

-->When you try to export the GridView which contains LinkButtons and Paging enabled then you might see the error "RegisterForEventValidation can only be called during Render"
     You can easily handle this error by going to the page source and turning the EnableEventValidation = "false".

<%@ Page Language="C#" EnableEventValidation="false" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %>

We will speak about the Enable EnableEventValidation and VerifyRenderingInServerForm
in subsequent posts.