I hope you could help me. I have been trying to export a Gridview to excel, but
there is an error that says "Control 'GridView1' of type 'GridView' must be
placed inside a form tag with runat=server. " I test the code with a DataGrid
and it works well, but I need to use it with a GridView, I´d like to know if
you could help, I have been searching for examples with this control, but I
could not find anyone.
Please help me is very urgent.
My code with out the function that I found to export a DataGrid to excel is the
following, I builded this code with the visual web developer 2005 beta:
"http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd">
http://www.w3.org/1999/xhtml" >
The function that I found to export a DataGrid to Excel is the following, I
changed the object DataGrid to Gridview, but the error that I show you above,
makes that it doesnt work:
protected void Button1_Click(object sender, EventArgs e)
{
//export to excel
Response.Clear();
Response.Buffer = true;
Response.ContentType = "application/vnd.ms-excel";
Response.Charset = "";
this.EnableViewState = false;
System.IO.StringWriter oStringWriter = new System.IO.StringWriter();
System.Web.UI.HtmlTextWriter oHtmlTextWriter = new
System.Web.UI.HtmlTextWriter(oStringWriter);
this.ClearControls(GridView1);
GridView1.RenderControl(oHtmlTextWriter);
Response.Write(oStringWriter.ToString());
Response.End();
}
private void ClearControls(Control control)
{
for (int i = control.Controls.Count - 1; i >= 0; i--)
{
ClearControls(control.Controls[i]);
}
if (!(control is TableCell))
{
if (control.GetType().GetProperty("SelectedItem") != null)
{
LiteralControl literal = new LiteralControl();
control.Parent.Controls.Add(literal);
try
{
literal.Text =
(string)control.GetType().GetProperty("SelectedItem").GetValue(control, null);
}
catch
{
}
control.Parent.Controls.Remove(control);
}
else
if (control.GetType().GetProperty("Text") != null)
{
LiteralControl literal = new LiteralControl();
control.Parent.Controls.Add(literal);
literal.Text =
(string)control.GetType().GetProperty("Text").GetValue(control, null);
control.Parent.Controls.Remove(control);
}
}
return;
}
I really hope you can help me
Thaks for ALL
Replies
Know the answer? Post it — somebody with the same question will find it here.