Friday, October 22, 2010

GridView - Export to Excel

Solution

Step 1

Paste this code on export button click.

Protected Sub imgExport_Click(ByVal sender As Object, ByVal e As System.Web.UI.ImageClickEventArgs) Handles imgExport.Click

Response.Clear()
Response.AddHeader("content-disposition", "attachment;filename=filename.xls")
Response.Charset = ""
Response.ContentType = "application/vnd.xls"

Dim stringWrite As New StringWriter
Dim htmlWrite As New HtmlTextWriter(stringWrite)

grid.AllowSorting = False
grid.AllowPaging = False
subBindGrid()

grid.RenderControl(htmlWrite)
Response.Write(stringWrite.ToString())
Response.End()

grid.AllowSorting = True
grid.AllowPaging = True
subBindGrid()

End Sub


If u run this code now, you will get error - 'Control 'ctl00_ContentPlaceHolder1_grid' of type 'GridView' must be placed inside a form tag with runat=server'. so, Don't worry. Just follow Step 2.

Step 2

Just copy and paste the below code. Its done.

Public 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