Hi,
Hi someone can help me on this?
Currently I have a Listdata.aspx page with datagrid, I wish to export my datagrid content to excel with following code ( with button export click event):-
But when I run the code, it raise an error
-> Control 'ctl02_GridView1' of type 'GridView' must be placed inside a form tag with runat=server"
My Listdata.aspx page are place under MasterPage.aspx, which is inside Contentplace holder. how to solve this? I can't put my GridView1 in Master page, cause Listdata.aspx are inside contentplace holder of Master page. Please help
protected void btnExport_Click(object sender, EventArgs e)
{
PrepareGridViewForExport(GridView1);
ExportTerminationLog();
}
private void PrepareGridViewForExport(Control gv)
{
LinkButton lb = new LinkButton();
Literal l = new Literal();
string name = String.Empty;
for (int i = 0; i < gv.Controls.Count; i++)
{
if (gv.Controls[i].GetType() == typeof(LinkButton))
{
l.Text = (gv.Controls[i] as LinkButton).Text;
gv.Controls.Remove(gv.Controls[i]);
gv.Controls.AddAt(i, l);
}
else if (gv.Controls[i].GetType() == typeof(DropDownList))
{
l.Text = (gv.Controls[i] as DropDownList).SelectedItem.Text;
gv.Controls.Remove(gv.Controls[i]);
gv.Controls.AddAt(i, l);
}
else if (gv.Controls[i].GetType() == typeof(CheckBox))
{
l.Text = (gv.Controls[i] as CheckBox).Checked ? "True" : "False";
gv.Controls.Remove(gv.Controls[i]);
gv.Controls.AddAt(i, l);
}
if (gv.Controls[i].HasControls())
{
PrepareGridViewForExport(gv.Controls[i]);
}
}
}
private void ExportTerminationLog()
{
string attachment = "attachment; filename=Termination.xls";
Response.ClearContent();
Response.AddHeader("content-disposition", attachment);
Response.ContentType = "application/ms-excel";
StringWriter sw = new StringWriter();
HtmlTextWriter htw = new HtmlTextWriter(sw);
GridView1.RenderControl(htw);
Response.Write(sw.ToString());
Response.End();
}