Export data from GridView to Excel

P

Peter

I am experimenting to export data from a GridView to an excel file. I am
using the code from the web.

But, I got one error message as below:
Control 'GridView1' of type 'GridView' must be placed inside a form tag with
runat=server

I did put the control tag inside the form tag. Please advise

Peter

aspx file as below:
<%@ Page Language="C#" CodeFile="Test2.aspx.cs"
Inherits="Test2" AutoEventWireup="true" %>
<html>
<head runat="server" >
<title>Code-Behind Page Model</title>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:Button id="Button2" runat="server" onclick="Button2_Click"
Text="Button" />

<asp:button runat="server" text="export to excel" onclick="doExport" /><br />
<br />
<asp:GridView runat="server" id="GridView1" AutoPostBack="true" />
</asp:Button>
</div>
</form>
</body>
</html>


code-behind file as below:
using System;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
public partial class Test2 : System.Web.UI.Page
{
protected void Button2_Click(object sender, EventArgs e)
{
string connectionString
= "server=ABC;database=XYZ, uid=john;pwd=doe";
System.Data.SqlClient.SqlConnection con
= new System.Data.SqlClient.SqlConnection(connectionString);
using (con)
{
con.Open();
string sql = "select * from table1";
System.Data.SqlClient.SqlDataAdapter da
= new System.Data.SqlClient.SqlDataAdapter(sql, con);

System.Data.DataSet ds = new System.Data.DataSet();
da.Fill(ds,"dsTable1");

GridView1.DataSource = ds;
GridView1.DataMember = "dsTable1";

GridView1.DataBind();

}

}

protected void doExport(object sender, EventArgs e) {

string connectionString
= "................";
System.Data.SqlClient.SqlConnection con
= new System.Data.SqlClient.SqlConnection(connectionString);
using (con)
{
Response.Clear();
Response.AddHeader
("contentdisposition",
"attachment;filename=test1.xls");
Response.Charset = "";
Response.Cache.SetCacheability(HttpCacheability.NoCache);
Response.ContentType = "application/vnd.xls";
System.IO.StringWriter stringWrite = new System.IO.StringWriter();
System.Web.UI.HtmlTextWriter htmlWrite
= new System.Web.UI.HtmlTextWriter(stringWrite);
GridView1.RenderControl(htmlWrite);
Response.Write(stringWrite.ToString());
Response.End();
}

}

}
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,770
Messages
2,569,583
Members
45,075
Latest member
MakersCBDBloodSupport

Latest Threads

Top