Adding a textbox server control from code behind

asp.net

I'm trying to add a new textbox server control to my page from code-behind.

TextBox txt=new TextBox();
txt.Width=100;
txt.Height=100;

Page.Controls.Add(txt);

When I write following Code, this error is thrown:

"Control 'ctl02' of type 'TextBox' must be placed inside a form tag with runat=server. "

What's the reason this error is thrown? How should this be done?

Best Answer

Inside the form you could put a placeholder at the location you want this textbox to appear:

<form runat="server">
    ...
    <asp:PlaceHolder ID="holder" runat="server" />
    ...
</form>

and then add the textbox to this placeholder:

TextBox txt = new TextBox(); 
txt.Width = 100; 
txt.Height = 100;
holder.Controls.Add(txt);
Related Topic