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.


  1. heyyy thnx buddy....gr8 work.....can u upload the code that accessing server controls in gridview.

  2. Hey ashish can u elaborate your problem.


Your comments, Feedbacks and Suggestions are very much valuable to me :)

Things are upgraded

My Dear readers, I am really thankful for being supportive all these years. This site was the first blog site I ever created in my life...