Exporting Data from a Gridview to Excel

I know this is a common topic and I really have done my homework but I've spent hours on this and can't get it to work. When I click a button and run the sub below, I'm getting the error message

"RegisterForEventValidation can only be called during Render"

When I try and add <%@ Page Language="VB" EnableEventValidation="false" MasterPageFile="~masterurl/default.master" %> to the page directive, I get the error message

"Parser Error Message: The enableeventvalidation attribute on the page directive is not allowed in this page."

Sub ExcelExport(ByVal Source As Object, ByVal E As EventArgs)
                   
            MyGrid.AllowPaging = "False"
            MyGrid.AllowSorting = "False"
            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=IT.Work.Requests.xls")
            Response.Charset = ""
            EnableViewState = False
            Controls.Add(frm)
            frm.Controls.Add(MyGrid)
            frm.RenderControl(hw)
            Response.Write(tw.ToString())
            Response.End()
            MyGrid.AllowPaging = "True"
            MyGrid.DataBind()
  

    End Sub
  

 

0
evanburen
9/8/2008 7:42:37 PM
asp.net.presentation-controls 72751 articles. 3 followers. Follow

2 Replies
447 Views

Similar Articles

[PageSpeed] 39

Add this function to your file. 

Public Overloads Overrides Sub VerifyRenderingInServerForm(ByVal control As Control) 
    ' Confirms that an HtmlForm control is rendered for the 
    'specified ASP.NET server control at run time. 
End Sub 
Also check whether you have this before your export code (if you have paging and sorting enabled.) 
MyGrid.AllowPaging = "False"
MyGrid.AllowSorting = "False"
MyGrid.DataBind
 
After doing this, you will not need another DataBind call at the end of the function.
 

Thanks,
Max
Let Me Google That For You!
0
bullpit
9/8/2008 8:48:38 PM

Thanks.  This did work for me. 

This blog post from Matt Berseth also works well. http://mattberseth.com/blog/2007/04/export_gridview_to_excel_1.html 

0
evanburen
9/9/2008 1:11:27 PM
Reply: