Monday, October 13, 2008

Control 'GridView1' of type 'GridView' must be placed inside a form tag with runat=server.

I ran across this error when trying to export the grid view data to excel.
I do have a form tag setup runat=server. But it continue to fail.

Solution: Create an HtmlForm object and add the grid view to the form in code.





string style = @" ";

Response.ClearContent();

// Create form tag

HtmlForm form1 = new HtmlForm();

form1.Controls.Add(gvData);


Response.AddHeader("content-disposition", "myfilename.xls");

Response.ContentType = "application/excel";

StringWriter sw = new StringWriter();
StringWriter header= new StringWriter();


HtmlTextWriter htw = new HtmlTextWriter(sw);

gvData.RenderControl(htw);


// Style is added dynamically

Response.Write(style);

Response.Write(sw.ToString());

Response.End();



No comments:

Post a Comment