Error Exporting Gridview data to excel Only when Gridview has template columns...[looking for work around]

Hello I have been exporting data to excel from a gridview using this code:

  

 Protected Sub btnExportar_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnExportar.Click

        ExportToExcel(sender, e)

    End Sub

    Sub ExportToExcel(ByVal Source As Object, ByVal E As EventArgs)

        If Me.gvDesembolsos.Rows.Count.ToString + 1 < 65536 Then
            Me.gvDesembolsos.Enabled = False
            
            'gvDesembolsos.Columns(1).Visible = False
            'gvDesembolsos.Columns(7).Visible = False
            'gvDesembolsos.Columns(9).Visible = False
            'gvDesembolsos.Columns(10).Visible = False

            Me.gvDesembolsos.AllowPaging = False
            Me.gvDesembolsos.AllowSorting = False
            Me.gvDesembolsos.DataBind()
            Dim tw As New StringWriter()
            Dim hw As New System.Web.UI.HtmlTextWriter(tw)
            Dim frm As HtmlForm = New HtmlForm()
            Response.ContentType = "application/vnd.ms-excel"
            Response.AddHeader("content-disposition", "attachment;filename=" & "Export" & ".xls")
            Response.Charset = ""
            EnableViewState = False
            Controls.Add(frm)
            frm.Controls.Add(Me.gvDesembolsos)
            frm.RenderControl(hw)
            Response.Write(tw.ToString())
            Response.End()
            Me.gvDesembolsos.AllowPaging = "True"
            Me.gvDesembolsos.AllowSorting = "True"
            Me.gvDesembolsos.DataBind()
        Else
            '"Too many rows - Export to Excel not possible"
        End If
    End Sub
 

 It works perfect until I had to add two or three template fields into that gridview.  Then those template fields are causing an error when excecute the exporting method:

 

This is the error I am getting:

 System.InvalidOperationException was unhandled by user code
  Message="RegisterForEventValidation can only be called during Render();"
  Source="System.Web"
  StackTrace:
       at System.Web.UI.ClientScriptManager.RegisterForEventValidation(String uniqueId, String argument)
       at System.Web.UI.ClientScriptManager.RegisterForEventValidation(PostBackOptions options)
       at System.Web.UI.WebControls.Button.AddAttributesToRender(HtmlTextWriter writer)
       at System.Web.UI.WebControls.WebControl.RenderBeginTag(HtmlTextWriter writer)
       at System.Web.UI.WebControls.WebControl.Render(HtmlTextWriter writer)
       at System.Web.UI.Control.RenderControlInternal(HtmlTextWriter writer, ControlAdapter adapter)
       at System.Web.UI.Control.RenderControl(HtmlTextWriter writer, ControlAdapter adapter)
       at System.Web.UI.Control.RenderControl(HtmlTextWriter writer)
       at System.Web.UI.Control.RenderChildrenInternal(HtmlTextWriter writer, ICollection children)
       at System.Web.UI.Control.RenderChildren(HtmlTextWriter writer)
       at System.Web.UI.Control.Render(HtmlTextWriter writer)
       at System.Web.UI.WebControls.WebControl.RenderContents(HtmlTextWriter writer)
       at System.Web.UI.WebControls.TableCell.RenderContents(HtmlTextWriter writer)
       at System.Web.UI.WebControls.WebControl.Render(HtmlTextWriter writer)
       at System.Web.UI.Control.RenderControlInternal(HtmlTextWriter writer, ControlAdapter adapter)
       at System.Web.UI.Control.RenderControl(HtmlTextWriter writer, ControlAdapter adapter)
       at System.Web.UI.Control.RenderControl(HtmlTextWriter writer)
       at System.Web.UI.Control.RenderChildrenInternal(HtmlTextWriter writer, ICollection children)
       at System.Web.UI.Control.RenderChildren(HtmlTextWriter writer)
       at System.Web.UI.Control.Render(HtmlTextWriter writer)
       at System.Web.UI.WebControls.WebControl.RenderContents(HtmlTextWriter writer)
       at System.Web.UI.WebControls.WebControl.Render(HtmlTextWriter writer)
       at System.Web.UI.Control.RenderControlInternal(HtmlTextWriter writer, ControlAdapter adapter)
       at System.Web.UI.Control.RenderControl(HtmlTextWriter writer, ControlAdapter adapter)
       at System.Web.UI.Control.RenderControl(HtmlTextWriter writer)
       at System.Web.UI.WebControls.Table.RenderContents(HtmlTextWriter writer)
       at System.Web.UI.WebControls.WebControl.Render(HtmlTextWriter writer)
       at System.Web.UI.Control.RenderControlInternal(HtmlTextWriter writer, ControlAdapter adapter)
       at System.Web.UI.Control.RenderControl(HtmlTextWriter writer, ControlAdapter adapter)
       at System.Web.UI.Control.RenderControl(HtmlTextWriter writer)
       at System.Web.UI.Control.RenderChildrenInternal(HtmlTextWriter writer, ICollection children)
       at System.Web.UI.Control.RenderChildren(HtmlTextWriter writer)
       at System.Web.UI.Control.Render(HtmlTextWriter writer)
       at System.Web.UI.WebControls.WebControl.RenderContents(HtmlTextWriter writer)
       at System.Web.UI.WebControls.GridView.Render(HtmlTextWriter writer, Boolean renderPanel)
       at System.Web.UI.WebControls.GridView.Render(HtmlTextWriter writer)
       at System.Web.UI.Control.RenderControlInternal(HtmlTextWriter writer, ControlAdapter adapter)
       at System.Web.UI.Control.RenderControl(HtmlTextWriter writer, ControlAdapter adapter)
       at System.Web.UI.Control.RenderControl(HtmlTextWriter writer)
       at System.Web.UI.Control.RenderChildrenInternal(HtmlTextWriter writer, ICollection children)
       at System.Web.UI.Control.RenderChildren(HtmlTextWriter writer)
       at System.Web.UI.HtmlControls.HtmlForm.RenderChildren(HtmlTextWriter writer)
       at System.Web.UI.HtmlControls.HtmlContainerControl.Render(HtmlTextWriter writer)
       at System.Web.UI.HtmlControls.HtmlForm.Render(HtmlTextWriter output)
       at System.Web.UI.Control.RenderControlInternal(HtmlTextWriter writer, ControlAdapter adapter)
       at System.Web.UI.Control.RenderControl(HtmlTextWriter writer, ControlAdapter adapter)
       at System.Web.UI.Control.RenderControl(HtmlTextWriter writer)
       at System.Web.UI.HtmlControls.HtmlForm.RenderControl(HtmlTextWriter writer)
       at _Default.ExportToExcel(Object Source, EventArgs E) in C:\Documents and Settings\emg3703\My Documents\Visual Studio 2005\FPCE_Desembolsos\Default.aspx.vb:line 230
       at _Default.btnExportar_Click(Object sender, EventArgs e) in C:\Documents and Settings\emg3703\My Documents\Visual Studio 2005\FPCE_Desembolsos\Default.aspx.vb:line 204
       at System.Web.UI.WebControls.Button.OnClick(EventArgs e)
       at System.Web.UI.WebControls.Button.RaisePostBackEvent(String eventArgument)
       at System.Web.UI.WebControls.Button.System.Web.UI.IPostBackEventHandler.RaisePostBackEvent(String eventArgument)
       at System.Web.UI.Page.RaisePostBackEvent(IPostBackEventHandler sourceControl, String eventArgument)
       at System.Web.UI.Page.RaisePostBackEvent(NameValueCollection postData)
       at System.Web.UI.Page.ProcessRequestMain(Boolean includeStagesBeforeAsyncPoint, Boolean includeStagesAfterAsyncPoint)

 I realized that if I set those templates columns visible property to false then it will work, but those columns are not going to be exported, so it is not a solution to my problem.

 

Please, if anyone knows how to solve this issue, let me know,

 

Thanks a lot. 

0
mendez_edd
12/14/2006 1:39:56 PM
asp.net.presentation-controls 72751 articles. 3 followers. Follow

3 Replies
916 Views

Similar Articles

[PageSpeed] 36

Check out this article, towards the end there is a workaround.

Darrell Norton, MVP
Darrell Norton's Blog


Please mark this post as answered if it helped you!
0
DarrellNorton
12/14/2006 3:36:23 PM

My work around was to eliminate the template columns and format the coulumns during the RowDataBound.

 

Smile

0
mendez_edd
12/19/2006 4:02:04 PM

My work around was to eliminate the template columns and format the coulumns during the RowDataBound.

 

Smile

0
mendez_edd
12/19/2006 4:02:16 PM
Reply:

Similar Artilces:

i have work on gridview control.in that i have 3columns.name as subject,bookname,link. in this some link column data are very large.according to that data(no spaces in that data)gridview has changed.i
hi,i have work on gridview control.in that i have 3columns.name as subject,bookname,link. in this some link column data are very large.according to that data(no spaces in that data)gridview has changed.i want display half of the data and remaining display like this.(ex:http://ww.yahoo.com...........).how can i display like this,and one more thing is always the column size will constant. Try something like this: <asp:templatefield headertext="Link"> <itemtemplate> <asp:hyperlink id="HyperLink1" runat="server" navigateurl='<...

How to export gridview data in excelexport data of gridview in excel?
dear friends i m using gridview with paging facility. can anyone tell me how do i export my gridview in excel? its urgent. thanks shwetaThanksshwetaIn a day when don't come across any problem -you can be sure that you are traveling in wrong path Hi please follow the link. http://mattberseth.com/blog/2007/04/export_gridview_to_excel_1.htmlValentine Day Special SongASP.NET ListView Control hi thanks for d reply but the blog doesnt get open.  ThanksshwetaIn a day when don't come across any problem -you can be sure that you are traveling in wrong path It is opening at ...

Issue with Template Columns & Bound Columns while updating the data in a GridView control
Hi, I'm facing the below problem (In general, ObjectDataSource is driving me crazy ! ) I have a simple gridview control and an ObjectDataSource is used to populate the grid. I'm trying to update a row and the corresponding tableadapter methods & stored procedure are in place. Each row has 2 checkboxes and 2 textboxes in edit mode. When the change the values in edit mode and hit update, the checkbox values changed are saved into the Database properly, whereas the textbox values are not being saved. If the textbox column is a bound column then the column is updated with <NULL> in...

Error Export Gridview Data into Excel.
I am trying to export Gridview data into Excel but getting some error. Here is my code. <asp:Button ID="btntest" Text="Export" OnClick="ExportToExcel_Click" runat="server" />protected void ExportToExcel_Click(object sender, EventArgs e) {string attachment = "attachment; filename=Contacts.xls"; Response.ClearContent();Response.AddHeader("content-disposition", attachment); Response.ContentType = "application/ms-excel";StringWriter sw = new StringWriter();HtmlTextWriter htw = new HtmlTextWriter(sw); grvRequestS...

Handling control columns when exporting a GridView to Excel
Hi, I'm using this well published code to export the contents of a gridview to excel i nresponse to a button click, but in all nearly examples I've seen it gives the 'Must be between TAGS' error messege if there are any controls in the grid, my particular problem is there's tickbox's - here's the code =========================================================   Protected Sub ExportButton_Click(ByVal sender As Object, ByVal e As System.EventArgs) Dim stringWrite As New System.IO.StringWriter Dim htmlWrite As New System.Web.UI.HtmlTextWriter(stringWrite) 'This works as long as t...

Dynamic Data gridView export to Excel error
Hi, Can you help me to solve my problem with dynamicdata grid view export to excel problem.In List.aspx file <asp:Button ID="btnExportGrid" runat="server" Text="Export to Excel" OnClick="BtnExportGrid_Click"/> protected void BtnExportGrid_Click(object sender, EventArgs e) {            GridViewExportUtil.Export("ExportFile.xls", this.GridView1);}GridViewExportUtil i have taken from this good resource http://mattberseth.com/blog/2007/04/export_gridview_to_excel_1.html.But wneh ex...

getting an error when exporting gridview to excel because of keeping the gridview inside the Update Panel
I have a gridview created in the UserControl (.ascx ) . I am registering this usercontrol in the page (.aspx) where I am using Update Panel(AjaxToolKit) . Inside Update panel I am keeping a Repeatercontrol ,and inside the repeater control there is a gridview. The contents inthis gridview should be Exported into Excel. I kept a button at the bottom of the gridview in .ascx file i,e in Usercontrol and wrote a logic for button click in .ascx.cs file . I tested Exporting to Excel code seperately without using Ajax its working ,but when i use it in module that is using Ajax its giving me an error...

GridView child of GridView
I have a Parent GridView and when you click in the Edit one of the columns has a Template Field which has a Child GridView. When you click Edit on the Child GridView I have a Template Field that has a TextBox. How to I retreive this value of the TextBox? GridViewParent-- GridViewChild (Edit - Template Field containing this GridViewChild)----- TextBox inside Template Field in GridViewChild. Thank you.Peace in ChristMarco Napolihttp://www.ourlovingmother.org What you can do as a solution is to override the RowDataBound and try to find the child GridView control. Once you get a reference to...

Exporting Gridview Data to an Excel sheet Not working properly.
 Hi Guys,              I have got a gridview on my page.  I am fill the gridview with a datatable which is created on-the-fly.  I have got one button on the webpage to export the gridview data to an excel sheet.  I am runing the following loop before binding the gridview with datatable to the columns count in the gridview.foreach (DataColumn col in dt.Columns)            {              ...

Control the language encoding for a data exported from gridview to Excel
Hello there, could anybody help me in this problem, I have a data that export to Excel but when it is exported any text that not in english will appear as rubbish.   please help me Hi:   Please open the exported file with notepad, what can you see in the <td>s? Please make sure these fields is Unicode encoding. Also try System.Web.HttpUtility.HtmlEncode(Eval("field_name")) instead of Eval("field_name") RegardsSincerely,Allen ChenMicrosoft Online Community SupportPlease remember to mark the replies as answers if they help and unmark them i...

GridView control exporting to Excel in Net 2.0
Well, I did my homework and found 33,868 references to issues with the gridview control and Excel, none of which were close to whats happening with my app. I have a Gridview control on my VB.NET main page and when I right click on it the popup allows me to export to Excel just fine..5-6 columns, less than 100 rows..when I do the same on another page I get an Excel error popup : "This web query returned no data.."..both grids have a (Select) button in the 1st column. The one that works is simply that...the one that doesn't has the Button.Text defined as something e...

Data Erasing while exporting to excel from gridview beside merge column
Hi All, Below is the code to export to Excelprotected void btnExcel_Click(object sender, EventArgs e) { Response.Clear();Response.AddHeader("content-disposition", "attachment;filename=FileName.xls"); Response.Charset = ""; // If you want the option to open the Excel file without saving then // comment out the line below // Response.Cache.SetCacheability(HttpCacheability.NoCache);Response.ContentType = "application/vnd.xls";  System.IO.StringWriter stringWrite = new System.IO.StringWriter();System.Web.UI.HtmlTextWriter htmlWrite = ...

binding a gridview to xmldatasource gives "The data source for gridview gridview1 did not have any properties or attributes from which to generate columns. Ensure that your data source has columns
Greetings!  I am new to asp.net forum so feel free to point me to the proper resources or forums.  I am using Visual Studio 2005.  I have a simple web page with a gridview control and an xmldatasource control.  I am getting the above error.  Can someone point out why I am getting the above error and what I need to do to resolve it?  Thanks in advance. /////////////////////////////// default.aspx  <%@ Page Language="vb" AutoEventWireup="false" CodeBehind="default.aspx.vb" Inherits="XMLwalkthroughVB._default" %&...

Error when iam having nested gridview, the second gridview gives error on data bind
System.Data.SqlClient.SqlException: A transport-level error has occurred when receiving results from the server. (provider: Shared Memory Provider error: 1 - I/O Error detected in read/write operation)Any pointers ? thanks    ~S...

Web resources about - Error Exporting Gridview data to excel Only when Gridview has template columns...[looking for work around] - asp.net.presentation-controls

Gas Exporting Countries Forum - Wikipedia, the free encyclopedia
The Gas Exporting Countries Forum ( GECF ) is an intergovernmental organization of 11 of the world's leading natural gas producers made up of ...

Facebook policy now clearly bans exporting user data to competing social networks
... of account settings, so it’s unlikely that many users have done this. Google and Facebook blocked or put up roadblocks on importing and exporting ...

Lower dollar a boon for Canberra's wine exporting king
It may mean more expensive holidays for some, but one ACT registered company has enjoyed a profitable time thanks to the sharp fall in the Australian ...

Irish plant shut for exporting horsemeat
Sky News is Australia's leader in 24-hour news.

New online freight marketplace Cargohound aims to be the Uber of exporting
Cargo Hound wants to revolutionise the way goods are shipped from Australia.

Exporting the desperate; out of sight ... and mind
The boats have stopped, the point's been made, so why continue to treat those already ''here'' with such unconscionable cruelty?

Meat market: Andrew Forrest sees fortune in exporting beef to China
China is so desperate for good beef that Australian billionaire Andrew Forrest will be taking sample parcels of steak in his luggage on his next ...

Exporting carbon and hypocrisy: our big growth industry
Never mind our modest cuts to local emissions, new research shows Australia is heading into a carbon export boom.

Spin Cycle: Is Tom Mulcair in favour of exporting bulk water?
The Liberals say Tom Mulcair spoke favourably about the idea of water exports when he was Quebec's environment minister back in 2004. They even ...

Lee Specialties Ltd. Charged With Exporting Prohibited Commodity To Iran
CALGARY - Putting the wrong address on a $15 shipment of synthetic rubber rings has cost an Alberta company $90,000 for violating legislation ...

Resources last updated: 1/21/2016 10:47:48 PM