User Control Controls.Count Zero

In server user control, I simply record the number of child controls.

Is there a reason why the counter will be zero if the <%%> tags are used in the body of the control tags?

Here is my extremely simplified control:

public class Script : Control { public override void RenderControl(HtmlTextWriter writer) { writer.Write(this.Controls.Count.ToString()); } } 

When only literal data is transmitted, the count is considered equal to 1, as expected:

 <my:Script runat="server" ID="script3" > function foo(){} </my:Script> 

When transmitting literal data and some calculated data, the counter goes to zero:

 <my:Script ID="Script1" runat="server" > function foot(){} <%=String.Empty %> </my:Script> 

There is nothing special about String.Empty. Everything that I do here leads to zero.

Interestingly, other Control tags work just fine. Next counter 3:

 <my:Script runat="server" ID="Script2"> hi <asp:HyperLink runat="server" NavigateUrl="/" Text="hi" /> </my:Script> 

Is there any other way to get the child "content" of a user control? I think there is some way, like it, but I can only check the metadata for System.Web.UI.WebControls.Content - not an implementation.

+4
source share
2 answers

It turns out that the answer was much simpler than the approach I took in the first place. Just call the overridden RenderControl method with your own HtmlTextWriter, and then use the captured markup, but you want to.

 var htmlString = new StringBuilder(); var mywriter = new HtmlTextWriter(new StringWriter(htmlString)); base.RenderControl(mywriter); 

The displayed markup is now available in htmlString, regardless of the <%%> tags used in the control body.

+1
source

You cannot modify the Controls collection if your control has <%%> tags in the body (if you try to Add something, you will get an exception explaining just that). And for the same reason, the Controls collection is virtually empty. You can check if collections are empty due to <%%> tags using the Controls.IsReadOnly property.

+4
source

All Articles