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.
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:
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
}
"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.
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;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With