0
public class TextBoxDerived : System.Web.UI.WebControls.TextBox
{
 protected override void OnLoad(EventArgs e)
 {
   this.Controls.Add(new LiteralControl("Hello"));
 }
}

The above code does not seem to do anything?

I was hoping something like

Hello
<input type"textbox" />

to be rendered in HTML.

1
  • It seems to me that you are going the wrong way about this. There are other ways to achieve this. Why have you chosen this approach? Commented May 13, 2011 at 9:40

1 Answer 1

1

A TextBox is not a CompositeControl, so it's children won't be rendered automatically.

What you could do, for example, is overwriting the Render method and manually rendering the control beforehand.

If you want to, as I assume, provide a textbox label and not some literal content, maybe using a HtmlGenericControl with a span or div tag would be more suitable, in order to automatically render escaped text.

protected override void Render(HtmlTextWriter writer)
{
    var label = new HtmlGenericControl("span");
    label.InnerText = "Hello";
    label.RenderControl(writer);

    base.Render(writer);
}
Sign up to request clarification or add additional context in comments.

3 Comments

Thanks, this is the solution I came up with. If I created a new instance of system.web.ui.webcontrols.webcontrol() (which textbox derives from) all child controls would be added. Can you explain this?
@maxp Actually, I think I was mistaken about the requirement for CompositeControl - by default WebControl also renders its child controls. I took a look at the TextBox Render() method in Reflector and see that it doesn't actually call base.Render() (which would render the child controls), but instead manually renders the begin tag, text and end tag.
To clarify, I should probably add that having "child" controls wouldn't make sense to solve your problem either way, as a child control would be rendered as a child node within the TextBoxes' <input> tag, which would be illegal anyway.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.