65.9K
CodeProject is changing. Read more.
Home

Attach Dynamic Controls to the ASP.NET form correctly

starIcon
emptyStarIcon
starIcon
emptyStarIconemptyStarIconemptyStarIcon

1.51/5 (11 votes)

Nov 23, 2005

viewsIcon

33272

downloadIcon

172

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.