Navigation

Search

Categories

On this page

Exporting Data from Excel in a Gridview

Archive

Blogroll

Disclaimer
The opinions expressed herein are my own personal opinions and do not represent my employer's view in anyway.

RSS 2.0 | Atom 1.0 | CDF

Send mail to the author(s) E-mail

Total Posts: 112
This Year: 50
This Month: 0
This Week: 0
Comments: 0

Sign In

 Monday, November 12, 2007
Monday, November 12, 2007 8:49:16 PM (Eastern Standard Time, UTC-05:00) ( )

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" %>

Technorati Tags: ,,