JavaEar 专注于收集分享传播有价值的技术资料

Create a server control from code behind using literalcontrol

I'm actually trying to create a Panel from codebehind with some server control inside, to do that I'm using a LiteralControl but the LiteralControl does not work with server control and that is what I need in this case. How can I do this. Please help.

I have something like this:

Panel pnl = new Panel();

pnl.Controls.Add(new LiteralControl("<label>SomeBanner: </label>"));

pnl.Controls.Add(new LiteralControl("<asp:TextBox ID='TextBox1' runat='server' Width='65px'/>"));

As I said, the first add (label) works perfectly but the second add does not works because I'm trying to create a server control using the LiteralControl which does not support this action.

How can I do this or what is the best practice in this case?


  1. The purpose of the LiteralControl is to send literal HTML to the client. Rather, you're looking to add a TextBox control to the Panel.

    Panel pnl = new Panel();
    pnl.Controls.Add(new LiteralControl("<label>SomeBanner: </label>"));
    TextBox tb = new TextBox();
    tb.ID = "TextBox1";

    While you're at it, I'd be tempted to use the Label control for your "SomeBanner" text. That would let you associate the Label and the Textbox (Label.AssociatedControlID), which has some advantages for end-user usability.