Click here to Skip to main content
Licence 
First Posted 22 Nov 2005
Views 24,005
Bookmarked 23 times

Attach Dynamic Controls to the ASP.NET form correctly

By | 22 Nov 2005 | Article
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>);

Voila! It should now work fine.

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

About the Author

Sundeep Phatak

Web Developer

Australia Australia

Member



Sign Up to vote   Poor Excellent
Add a reason or comment to your vote: x
Votes of 3 or less require a comment

Comments and Discussions

 
You must Sign In to use this message board. (secure sign-in)
 
Search this forum  
 FAQ
    Noise  Layout  Per page   
  Refresh
Questioncreate dynamic textboxes in web Content Form in asp.net? PinmemberShama Shahzadi1:24 14 Aug '11  
GeneralShort and sweet PinmemberDon Zocchi9:05 2 Feb '06  
GeneralUse an instance field PinmemberWouter van Vugt5:33 23 Nov '05  

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

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

Permalink | Advertise | Privacy | Mobile
Web04 | 2.5.120517.1 | Last Updated 23 Nov 2005
Article Copyright 2005 by Sundeep Phatak
Everything else Copyright © CodeProject, 1999-2012
Terms of Use
Layout: fixed | fluid