4

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?

2 Answers 2

5

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);
Sign up to request clarification or add additional context in comments.

Comments

4

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);

5 Comments

I got it..Thanks you for answer Frédéric Hamidi .
sorry to be digging up a dinosaur, but is it possible to wrap any of this in HTML? this works, but i want to be able to put the form into a table so its formatted nice
@Dan, absolutely, you can nest the <form> element in an <asp:Table> element in your page's markup. It should work just fine.
thanks for the reply. I meant dynamically. Im using a loop to generate the form controls. They are being added to the form, but none of the dynamic elements have the table html so they dont format correctly
@Dan, well, it depends on what you want to do. You can nest a instance of Table into the form (in the same way as the TextBox), but traditionally the <form> element is present in the page markup, not generated dynamically. If that's the case, then relocating the form inside a newly added table may work, but I never had to test it.

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.