.

Saturday, July 12, 2008

Code for Export data from GridView to Excel

Code for Export data from GridView to Excel: -

Code for Export data from GridView to Excel: -
--------------------------------------------------------------Response.Clear(); Response.AddHeader("content-disposition", "attachment;filename=FileName.xls"); Response.Charset = ""; Response.ContentType = "application/vnd.xls";
StringWriter stringWrite = new StringWriter(); HtmlTextWriter htmlWrite = new HtmlTextWriter(stringWrite); try { dgdManageCategory.RenderControl(htmlWrite); } catch (Exception ex) { string s = ex.Message; Response.Write("Cannot Export to Excel"); }
Response.Write(stringWrite.ToString()); Response.End(); }
--------------------------------------------------------------
As I tried to Export data from GridView to Excel I got this error: -
Control 'dgdManageCategory' of type 'GridView' must be placed inside a form tag with runat=server.
So I searched the net on various sites and saw that I shouild add an overridden method that would solve the problem: -
So I used the method: -
--------------------------------------------------------------
public override void VerifyRenderingInServerForm(Control control) { // Confirms that an HtmlForm control is rendered for the specified ASP.NET server control at run time. }
--------------------------------------------------------------
But I still got an error: -
"RegisterForEventValidation can only be called during Render();"
So I again searched the net and got this solution: -
Under the tag
<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="ManageCategory.aspx.cs" Inherits="CartTest.ManageCategory" %>
I should add "EnableEventValidation = "false" " to the above tag and thus the problem was solved.

Sites from where I got the help was: -
1) http://connect.microsoft.com/VisualStudio/feedback/ViewFeedback.aspx?FeedbackID=118285
2) http://gridviewguy.com/ArticleDetails.aspx?articleID=182
3) http://mattberseth.com/blog/2007/04/export_gridview_to_excel_1.html
--
4) http://geekswithblogs.net/azamsharp/archive/2005/12/21/63845.aspx

No comments:

.