Friday, September 24, 2010

GridView must be placed inside a form tag with runat=server

I was creating an online test and I wanted to email the test results by topic to an email distribution list. I have a panel which has two child controls, a label with an overall % correct and a gridview with percentages by topic.

A few simple lines of code would typically handle this:

string listRecipients = ConfigurationManager.AppSettings["candidateTestEmailList"].ToString();
StringBuilder sb = new StringBuilder(2000);
pnlResults.RenderControl(new HtmlTextWriter(new System.IO.StringWriter(sb)));

//---------------------------------------------------------------------
// Send to the mail handler class
//---------------------------------------------------------------------
MailHandler mh = new MailHandler();
mh.SendMail(listRecipients, "Test Results " + tbName.Text, sb.ToString());

But I was getting the error...Gridview must be placed inside a form tag with runat=server. And of course it is, and the panel and the label are not throwing a similar error. I found this nifty fix:

public override void VerifyRenderingInServerForm(Control control)
{ 
return;
}

found it here: http://blogs.x2line.com/al/archive/2004/10/08/576.aspx