I recently ran into a situation where I was unable to export data from a GridView to Excel using the same technique that I've used many times before using a DataGrid (see below). I kept getting the error message "Control 'GridView1' of type 'GridView' must be placed inside a form tag with runat=server. " I had to do this to get this to work.
<script runat="server">
Private Sub ExcelExport(ByVal sender As System.Object, ByVal e As System.EventArgs)
GridView1.AllowSorting = False
Response.Clear()
Response.AddHeader("content-disposition", "attachment;filename=ConferenceAttendees.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
</script>
The trick
was to set EnableEventValidation to false in the page declaration:
<%@ Page Language="VB" EnableEventValidation = "false" %>