Solved

Export GridView to Excel

Posted on 2007-11-23
8
1,214 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
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
  • 4
  • 3
8 Comments
 
LVL 10

Expert Comment

by:Oliver Amaya
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
Technology Partners: We Want Your Opinion!

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

 
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
 

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

Technology Partners: We Want Your Opinion!

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

Question has a verified solution.

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

Suggested Solutions

IntroductionWhile developing web applications, a single page might contain many regions and each region might contain many number of controls with the capability to perform  postback. Many times you might need to perform some action on an ASP.NET po…
Problem Hi all,    While many today have fast Internet connection, there are many still who do not, or are connecting through devices with a slower connect, so light web pages and fast load times are still popular.    If your ASP.NET page …
Nobody understands Phishing better than an anti-spam company. That’s why we are providing Phishing Awareness Training to our customers. According to a report by Verizon, only 3% of targeted users report malicious emails to management. With compan…

733 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