Solved

Export GridView to Excel

Posted on 2007-11-23
8
1,207 Views
Last Modified: 2010-04-21
I have been trying to export a gridview to an excel file using the following code in the click event

rotected Sub Button4_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles Button4.Click
        Response.AddHeader("content-disposition", "attachment;filename=C:\Documents and Settings\All Users\Desktop\print_file.xls")
        Response.ContentType = "application/vnd.ms-excel"
        Response.Charset = ""
        Me.EnableViewState = False
        Dim objStrWriter As New System.IO.StringWriter
        Dim objHtmlTextWriter As New System.Web.UI.HtmlTextWriter(objStrWriter)
        'Get the DataGrid HTML from the control
        GridView1.RenderControl(objHtmlTextWriter)
        'writes the dg info
        Response.Write(objStrWriter.ToString())
        Response.End()
End Sub

This gives the following error in the Inetrnet Explorer page when I run it

Server Error in '/ptn' Application.
--------------------------------------------------------------------------------

Control 'GridView1' of type 'GridView' must be placed inside a form tag with runat=server.
Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.

Exception Details: System.Web.HttpException: Control 'GridView1' of type 'GridView' must be placed inside a form tag with runat=server.

Source Error:


Line 666:        Dim objHtmlTextWriter As New System.Web.UI.HtmlTextWriter(objStrWriter)
Line 667:        'Get the DataGrid HTML from the control
Line 668:        GridView1.RenderControl(objHtmlTextWriter)
Line 669:        'writes the dg info
Line 670:        Response.Write(objStrWriter.ToString())
 

Source File: C:\Inetpub\wwwroot\ptn\MemberPages\Print\ptn_data_print.aspx.vb    Line: 668

Stack Trace:


[HttpException (0x80004005): Control 'GridView1' of type 'GridView' must be placed inside a form tag with runat=server.]
   System.Web.UI.Page.VerifyRenderingInServerForm(Control control) +2038991
   System.Web.UI.WebControls.GridView.Render(HtmlTextWriter writer, Boolean renderPanel) +37
   System.Web.UI.WebControls.GridView.Render(HtmlTextWriter writer) +30
   System.Web.UI.Control.RenderControlInternal(HtmlTextWriter writer, ControlAdapter adapter) +25
   System.Web.UI.Control.RenderControl(HtmlTextWriter writer, ControlAdapter adapter) +121
   System.Web.UI.Control.RenderControl(HtmlTextWriter writer) +22
   _Default.Button4_Click(Object sender, EventArgs e) in C:\Inetpub\wwwroot\ptn\MemberPages\Print\ptn_data_print.aspx.vb:668
   System.Web.UI.WebControls.Button.OnClick(EventArgs e) +105
   System.Web.UI.WebControls.Button.RaisePostBackEvent(String eventArgument) +107
   System.Web.UI.WebControls.Button.System.Web.UI.IPostBackEventHandler.RaisePostBackEvent(String eventArgument) +7
   System.Web.UI.Page.RaisePostBackEvent(IPostBackEventHandler sourceControl, String eventArgument) +11
   System.Web.UI.Page.RaisePostBackEvent(NameValueCollection postData) +33
   System.Web.UI.Page.ProcessRequestMain(Boolean includeStagesBeforeAsyncPoint, Boolean includeStagesAfterAsyncPoint) +1746

 


--------------------------------------------------------------------------------
Version Information: Microsoft .NET Framework Version:2.0.50727.1378; ASP.NET Version:2.0.50727.1378
0
Comment
Question by:gcyrille
  • 4
  • 3
8 Comments
 
LVL 10

Expert Comment

by:joex911
ID: 20338348
Hi, in your aspx do you have a tag like this one? your gridview should be inside it.
<form runat="server"></form>

Open in new window

0
 
LVL 2

Expert Comment

by:DJFuller
ID: 20338831
If you use this code to export

Response.Clear()
        Response.AddHeader("content-disposition", "attachment;filename=filename.xls")
        Response.Charset = ""
        Response.ContentType = "application/vnd.xls"
        Dim stringWrite As System.IO.StringWriter = New System.IO.StringWriter
        Dim htmlWrite As System.Web.UI.HtmlTextWriter = New HtmlTextWriter(stringWrite)
        GridView1.RenderControl(htmlWrite)
        Response.Write(stringWrite.ToString)
        Response.End()

You need to include this code somewhere in your code behind

 Public Overloads Overrides Sub VerifyRenderingInServerForm(ByVal control As Control)
        'this enables the export format in above code
    End Sub
0
 

Author Comment

by:gcyrille
ID: 20340904
As I said I am new to this stuff. I am using Visual Web Developer 2008. How do I put

Public Overloads Overrides Sub VerifyRenderingInServerForm(ByVal control As Control)
        'this enables the export format in above code
    End Sub

somewhere in my code behind
0
 
LVL 2

Accepted Solution

by:
DJFuller earned 500 total points
ID: 20348853
just copy and paste it underneath the "End Sub" on your onclick event
0
Is Your Active Directory as Secure as You Think?

More than 75% of all records are compromised because of the loss or theft of a privileged credential. Experts have been exploring Active Directory infrastructure to identify key threats and establish best practices for keeping data safe. Attend this month’s webinar to learn more.

 

Author Comment

by:gcyrille
ID: 20350455
Thanks for your continued support DJ but when I pasted the code below the onclick event another error occurs as shown below

RegisterForEventValidation can only be called during Render();
Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.

Exception Details: System.InvalidOperationException: RegisterForEventValidation can only be called during Render();

Source Error:


Line 664:        Dim stringWrite As System.IO.StringWriter = New System.IO.StringWriter
Line 665:        Dim htmlWrite As System.Web.UI.HtmlTextWriter = New HtmlTextWriter(stringWrite)
Line 666:        GridView1.RenderControl(htmlWrite)
Line 667:        Response.Write(stringWrite.ToString)
Line 668:        Response.End()
 

Source File: C:\Inetpub\wwwroot\ptn\MemberPages\Print\ptn_data_print.aspx.vb    Line: 666

Stack Trace:


[InvalidOperationException: RegisterForEventValidation can only be called during Render();]
   System.Web.UI.ClientScriptManager.RegisterForEventValidation(String uniqueId, String argument) +2122651
   System.Web.UI.ClientScriptManager.GetPostBackEventReference(PostBackOptions options, Boolean registerForEventValidation) +49
   System.Web.UI.WebControls.LinkButton.AddAttributesToRender(HtmlTextWriter writer) +256
   System.Web.UI.WebControls.WebControl.RenderBeginTag(HtmlTextWriter writer) +17
   System.Web.UI.WebControls.DataControlLinkButton.Render(HtmlTextWriter writer) +34
   System.Web.UI.Control.RenderControlInternal(HtmlTextWriter writer, ControlAdapter adapter) +25
   System.Web.UI.Control.RenderControl(HtmlTextWriter writer, ControlAdapter adapter) +121
   System.Web.UI.Control.RenderControl(HtmlTextWriter writer) +22
   System.Web.UI.Control.RenderChildrenInternal(HtmlTextWriter writer, ICollection children) +199
   System.Web.UI.Control.RenderChildren(HtmlTextWriter writer) +20
   System.Web.UI.WebControls.TableCell.RenderContents(HtmlTextWriter writer) +97
   System.Web.UI.WebControls.WebControl.Render(HtmlTextWriter writer) +29
   System.Web.UI.Control.RenderControlInternal(HtmlTextWriter writer, ControlAdapter adapter) +25
   System.Web.UI.Control.RenderControl(HtmlTextWriter writer, ControlAdapter adapter) +121
   System.Web.UI.Control.RenderControl(HtmlTextWriter writer) +22
   System.Web.UI.Control.RenderChildrenInternal(HtmlTextWriter writer, ICollection children) +199
   System.Web.UI.Control.RenderChildren(HtmlTextWriter writer) +20
   System.Web.UI.WebControls.WebControl.RenderContents(HtmlTextWriter writer) +7
   System.Web.UI.WebControls.WebControl.Render(HtmlTextWriter writer) +29
   System.Web.UI.Control.RenderControlInternal(HtmlTextWriter writer, ControlAdapter adapter) +25
   System.Web.UI.Control.RenderControl(HtmlTextWriter writer, ControlAdapter adapter) +121
   System.Web.UI.Control.RenderControl(HtmlTextWriter writer) +22
   System.Web.UI.WebControls.Table.RenderContents(HtmlTextWriter writer) +536
   System.Web.UI.WebControls.WebControl.Render(HtmlTextWriter writer) +29
   System.Web.UI.Control.RenderControlInternal(HtmlTextWriter writer, ControlAdapter adapter) +25
   System.Web.UI.Control.RenderControl(HtmlTextWriter writer, ControlAdapter adapter) +121
   System.Web.UI.Control.RenderControl(HtmlTextWriter writer) +22
   System.Web.UI.Control.RenderChildrenInternal(HtmlTextWriter writer, ICollection children) +199
   System.Web.UI.Control.RenderChildren(HtmlTextWriter writer) +20
   System.Web.UI.WebControls.WebControl.RenderContents(HtmlTextWriter writer) +7
   System.Web.UI.WebControls.GridView.Render(HtmlTextWriter writer, Boolean renderPanel) +202
   System.Web.UI.WebControls.GridView.Render(HtmlTextWriter writer) +30
   System.Web.UI.Control.RenderControlInternal(HtmlTextWriter writer, ControlAdapter adapter) +25
   System.Web.UI.Control.RenderControl(HtmlTextWriter writer, ControlAdapter adapter) +121
   System.Web.UI.Control.RenderControl(HtmlTextWriter writer) +22
   _Default.Button4_Click(Object sender, EventArgs e) in C:\Inetpub\wwwroot\ptn\MemberPages\Print\ptn_data_print.aspx.vb:666
   System.Web.UI.WebControls.Button.OnClick(EventArgs e) +105
   System.Web.UI.WebControls.Button.RaisePostBackEvent(String eventArgument) +107
   System.Web.UI.WebControls.Button.System.Web.UI.IPostBackEventHandler.RaisePostBackEvent(String eventArgument) +7
   System.Web.UI.Page.RaisePostBackEvent(IPostBackEventHandler sourceControl, String eventArgument) +11
   System.Web.UI.Page.RaisePostBackEvent(NameValueCollection postData) +33
   System.Web.UI.Page.ProcessRequestMain(Boolean includeStagesBeforeAsyncPoint, Boolean includeStagesAfterAsyncPoint) +1746

 


--------------------------------------------------------------------------------
Version Information: Microsoft .NET Framework Version:2.0.50727.1378; ASP.NET Version:2.0.50727.1
0
 

Author Closing Comment

by:gcyrille
ID: 31410650
I managed to solve the problem with the error oulined above by turning off event validation for the page. I have therefore accepted DJFuller's solution.
0
 
LVL 2

Expert Comment

by:DJFuller
ID: 20356532
Say my button is named btnExport: this is the code to copy and paste

Protected Sub btnExport_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnExport.Click
       
        'export the Gridview to an excel document called Data.xls
        Response.Clear()
        Response.AddHeader("content-disposition", "attachment;filename=Data.xls")
        Response.Charset = ""
        Response.ContentType = "application/vnd.xls"
        Dim stringWrite As System.IO.StringWriter = New System.IO.StringWriter
        Dim htmlWrite As System.Web.UI.HtmlTextWriter = New HtmlTextWriter(stringWrite)
        GridView1.RenderControl(htmlWrite)
        Response.Write(stringWrite.ToString)
        Response.End()

    End Sub

    Public Overloads Overrides Sub VerifyRenderingInServerForm(ByVal control As Control)
        'this enables the export format in above code
    End Sub

Does that look like your code? This is done using VB.net, if you use C# you may need to convert - but I'm not sure
0
 

Author Comment

by:gcyrille
ID: 20367437
I managed to solve the problem with the error oulined above by turning off event validation for the page. Hence as you can see ,I have therefore accepted your solution
0

Featured Post

Is Your Active Directory as Secure as You Think?

More than 75% of all records are compromised because of the loss or theft of a privileged credential. Experts have been exploring Active Directory infrastructure to identify key threats and establish best practices for keeping data safe. Attend this month’s webinar to learn more.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Microsoft Reports are based on a report definition, which is an XML file that describes data and layout for the report, with a different extension. You can create a client-side report definition language (*.rdlc) file with Visual Studio, and build g…
A quick way to get a menu to work on our website, is using the Menu control and assign it to a web.sitemap using SiteMapDataSource. Example of web.sitemap file: (CODE) Sample code to add to the page menu: (CODE) Running the application, we wi…
Along with being a a promotional video for my three-day Annielytics Dashboard Seminor, this Micro Tutorial is an intro to Google Analytics API data.
Internet Business Fax to Email Made Easy - With eFax Corporate (http://www.enterprise.efax.com), you'll receive a dedicated online fax number, which is used the same way as a typical analog fax number. You'll receive secure faxes in your email, fr…

920 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

15 Experts available now in Live!

Get 1:1 Help Now