Can you add child controls to a HtmlGenericControl?

Viewed 16401

I have a very simple operation where I try to add a HtmlGenericControl to another HtmlGenericControl :

protected void Page_Load(object sender, EventArgs e)
{

  HtmlGenericControl div = new HtmlGenericControl("div");
  HtmlGenericControl p = new HtmlGenericControl("p");

  div.Controls.Add(p);//exception occurs
}

An exception is thrown in the debugger only - the page itself renders as though nothing had happened. However something definitely does happen, as in a larger portion of code, controls are not being rendered as they should.

enter image description here

The actual exception is:

{InnerText = '((System.Web.UI.HtmlControls.HtmlContainerControl)(div)).InnerText' threw an exception of type 'System.Web.HttpException'}

I can't understand why this is happening, as you should be able to add controls to each other in this manner.

Note that from the first answer, I tried again with IDs but it still doesn't work:

enter image description here

I have some more information. When using a Placeholder control as the parent, there is no exception:

protected void Page_Init()
{
  PlaceHolder ph = new PlaceHolder();
  HtmlGenericControl p = new HtmlGenericControl("p");

  ph.Controls.Add(p);//no problem
}
8 Answers
Related