views:

88

answers:

1

Hi There, I have a gridvidew (GV2). I want the user to be able to export the contents of this gridview to an excel spreadsheet for offline processing.

Here is my subroutine:

Protected Sub ExcelButton_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles ExcelButton.Click
        Response.ContentType = "application/vnd.ms-excel"
        Response.Charset = ""
        Me.EnableViewState = False
        Dim stringWriter As New System.IO.StringWriter()
        Dim htmlWriter As New System.Web.UI.HtmlTextWriter(stringWriter)
        GV2.RenderControl(htmlWriter)
        Response.Write(stringWriter.ToString())
        Response.End()
    End Sub

On clicking the ExcelButton I get the error message:

Control 'GV2' of type 'GridView' must be placed inside a form tag with runat=server.

The control GV2 is in fact inside:

 <form id="form1" runat="server"></form>
+1  A: 

There's a 'story' behind this error message. I'll go straight to one of the solutions.

Add this to the code-behind of the ASPX file:

Public Overrides Sub VerifyRenderingInServerForm(control As Control)

End Sub

More info here:

How to export GridView to Word using ASP.NET 2.0 and VB
CodeSnip: Exporting GridView to Excel

o.k.w
Thanks for the help. I added the code above and am now getting: RegisterForEventValidation can only be called during Render();
Phil
I solved this by turning off event validation..... by adding EnableEventValidation ="false" to the @page directive... Does this present any potential dangers?
Phil
@Phil, I assume you only turn off event validation for that specific page, you'll need to make sure postback event for that page will not be hijacked to perform illegal or unwanted operations.
o.k.w