Click here to Skip to main content
15,891,828 members
Articles / Web Development / ASP.NET
Article

Attach Dynamic Controls to the ASP.NET form correctly

Rate me:
Please Sign up or sign in to vote.
1.51/5 (16 votes)
22 Nov 2005 32.9K   22   3
Attach Dynamic controls to the Page.Controls collection without using a placeholder control.

Introduction

Ever tried to create web controls dynamically and add them to the Controls collection of the Page class? Most probably, you would have ended up with an error saying "Control '<control name>' of type '<control type>' must be placed inside a form tag with runat=server."

Reason


ASP.NET doesn't place the dynamically generated controls within the

<form 
runat="server">
</form>

tags.

Resolution


1. Check your in-front file for the ID of the form element. For our example, let the ID be "Form1"
2. In your code-behind, use the following syntax to get a handle to the corresponding HtmlForm object:

HtmlForm form1 = this.FindControl("Form1") as HtmlForm;

3. Add the dynamically generated controls to the controls collection of this control:

form1.Controls.Add(<some control object>);

<p>Voila! It should now work fine. 
</p>

License

This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here


Written By
Web Developer
Australia Australia
This member has not yet provided a Biography. Assume it's interesting and varied, and probably something to do with programming.

Comments and Discussions

 
Questioncreate dynamic textboxes in web Content Form in asp.net? Pin
Shama Shahzadi14-Aug-11 1:24
Shama Shahzadi14-Aug-11 1:24 
GeneralShort and sweet Pin
Don Zocchi2-Feb-06 9:05
Don Zocchi2-Feb-06 9:05 
GeneralUse an instance field Pin
Wouter van Vugt23-Nov-05 5:33
Wouter van Vugt23-Nov-05 5:33 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.