Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

adding a textbox server control from code behind?

Tags:

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?

like image 352
Zoro Avatar asked Jan 20 '23 15:01

Zoro


2 Answers

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);
like image 113
Darin Dimitrov Avatar answered Jan 26 '23 04:01

Darin Dimitrov


The error message is telling you that your TextBox control must be added to the <form> element in the page instead of the page itself. Try:

Page.Form.Controls.Add(txt);
like image 29
Frédéric Hamidi Avatar answered Jan 26 '23 04:01

Frédéric Hamidi