October 10, 2007

Exporting Gridveiw data int o excel file

hi guys exporting files from gridview is quite simple

u have to just put this code inside buttononclick
protected void btnExcel_Click(object sender, EventArgs e)
Response.ContentType = "application/vnd.ms-excel";
Response.AddHeader("content-disposition", "attachment;filename=My Report_" + System.DateTime.Today.Date.ToShortDateString().Replace("/", "_") + ".xls");
Response.Charset = "";
System.IO.StringWriter stringWrite = new System.IO.StringWriter();
System.Web.UI.HtmlTextWriter htmlWrite = new HtmlTextWriter(stringWrite);


if u compile this code i wont work finely.

All you need to do is to override the VerifyRenderingInServerForum event as I have shown below.

public override void VerifyRenderingInServerForm(Control control)

// Confirms that an HtmlForm control is rendered for the specified ASP.NET server control at run time.


After that if it shows the error

Control 'Gridview1' of type 'GridView' must be placed inside a form tag with runat=server

Then open user .aspx file in that u just add the attribute EnableEventValidation="false" like this

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

Now ur code will works fine