Solved

Export GridView to Excel

Posted on 2007-11-23
8
1,210 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
Courses: Start Training Online With Pros, Today

Brush up on the basics or master the advanced techniques required to earn essential industry certifications, with Courses. Enroll in a course and start learning today. Training topics range from Android App Dev to the Xen Virtualization Platform.

 
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

Courses: Start Training Online With Pros, Today

Brush up on the basics or master the advanced techniques required to earn essential industry certifications, with Courses. Enroll in a course and start learning today. Training topics range from Android App Dev to the Xen Virtualization Platform.

Question has a verified solution.

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

Calculating holidays and working days is a function that is often needed yet it is not one found within the Framework. This article presents one approach to building a working-day calculator for use in .NET.
It was really hard time for me to get the understanding of Delegates in C#. I went through many websites and articles but I found them very clumsy. After going through those sites, I noted down the points in a easy way so here I am sharing that unde…
This video shows how to quickly and easily add an email signature for all users on Exchange 2016. The resulting signature is applied on a server level by Exchange Online. The email signature template has been downloaded from: www.mail-signatures…
This video shows how to use Hyena, from SystemTools Software, to bulk import 100 user accounts from an external text file. View in 1080p for best video quality.

776 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