I'm using the code below in a attempt to export a Gridview to Excel. The Gridview itself displays fine. I get an error when I click on the 'Export to Excel button'
I get a error of "Control 'Gridview1' of type 'GridView' must be placed inside a form tag with runat=server. "
the error is on the line
Gridview1.RenderControl(htw)
(line 32 of the code behind file)
I'm using ASP.NET 2.0 and have tried this code both in the VWD server and on a Production server with asp.net 2.0 loaded on it, both produce the same error.
Can anyone tell me how to fix this? Thanks in advance for any assistance you can give me.
-MARK-
Mark Buckley
I get a error of "Control 'Gridview1' of type 'GridView' must be placed inside a form tag with runat=server. "
the error is on the line
Gridview1.RenderControl(htw)
(line 32 of the code behind file)
I'm using ASP.NET 2.0 and have tried this code both in the VWD server and on a Production server with asp.net 2.0 loaded on it, both produce the same error.
Can anyone tell me how to fix this? Thanks in advance for any assistance you can give me.
-MARK-
Code:
.apsx file
<%@ Page Language="VB" AutoEventWireup="false" CodeFile="testExcel.aspx.vb" Debug="true" Inherits="testExcel" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "[URL unfurl="true"]http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">[/URL]
<html xmlns="[URL unfurl="true"]http://www.w3.org/1999/xhtml"[/URL] >
<head runat="server">
<title>Untitled Page</title>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:Button ID="Btn_Export" runat="server" Text="Export to Excel" OnClick="Btn_Export_Click" />
<asp:gridview ID="Gridview1" runat="server"></asp:gridview>
</div>
</form>
</body>
</html>
.aspx.vb file
Imports System
Imports System.Data
Imports System.Data.SqlClient
Imports System.IO
Partial Class testExcel
Inherits System.Web.UI.Page
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
GetData()
End Sub
Public Function GetData()
Dim myConnection As SqlConnection = New SqlConnection(ConfigurationManager.ConnectionStrings("IncidentConnectionString").ToString)
Const strSQL As String = "usp_incidentstatus_SELECT" 'Using a Stored Procedure
Dim MyDataAdapter As SqlDataAdapter = New SqlDataAdapter(strSQL, myConnection)
Dim MyDataSet As DataSet = New DataSet
MyDataAdapter.Fill(MyDataSet) Gridview1.DataSource = MyDataSet
Gridview1.DataBind()
End Function
Protected Sub Btn_Export_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles Btn_Export.Click
Response.ClearContent()
Response.AddHeader("content-disposition", "attachment; filename=MyExcelFile.xls")
Response.ContentType = "application/excel"
Dim sw As StringWriter = New StringWriter
Dim htw As HtmlTextWriter = New HtmlTextWriter(sw)
[COLOR=red]
Gridview1.RenderControl(htw)
[/color]
Response.Write(sw.ToString())
Response.End()
End Sub
End Class
Mark Buckley