Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can you add child controls to a HtmlGenericControl?

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
}
like image 200
Petras Avatar asked Jul 12 '11 05:07

Petras


2 Answers

"An exception is thrown in the debugger only - the page itself renders as though nothing had happened."

That's fine in that InnerText won't work if there are child controls; that is by design because it doesn't want to render the whole hierarchy of controls at that time for various performance, lifecycle, and side affect reasons.

"... something definitely does happen, as in a larger portion of code, controls are not being rendered as they should."

What does that mean? What is rendering incorrectly in the "larger portion" of code? My guess is that is a problem somewhere else and not related to what you have in your question here.

So I think you're fine. Ignore the exception in InnerText on the parent control. You need to ask a new Question regarding whatever issue you are having with the "larger portion" of your code.

like image 73
Jon Adams Avatar answered Oct 22 '22 14:10

Jon Adams


i think an easy solution to avoid this error can be to render the child HtmlGenericControl into a string and then adding it to the parents inside the InnerHtml attribute. something like this:

HtmlGenericControl parent = new HtmlGenericControl("div");
HtmlGenericControl child = new HtmlGenericControl("div");
StringWriter stringWriter = new StringWriter();
HtmlTextWriter twr = new HtmlTextWriter(stringWriter);
child.RenderControl(twr);
string rendered=stringWriter.ToString().Replace("\r","").Replace("\n","").Replace("\t","");
parent.InnerHtml =  rendered;
like image 33
Bobby5193 Avatar answered Oct 22 '22 13:10

Bobby5193