Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles / web / ASP.NET

Does Not Allow Child Controls Error

3.31/5 (13 votes)
16 Aug 2007CPOL1 min read 1   207  
When you create a custom drop-down-list that inherits from System.Web.UI.WebControls.DropDownList and when you try to add controls (e.g., Me.Controls.Add(myControl)), you will get a does not allow child controls error. Here is the fix.

Screenshot - does-not-allow-child-controls.gif

Introduction

I was trying to create a custom control that inherits from DropDownList with required field validation. My original intention was to embed RequiredFieldValidator on my custom drop-down-list control so that when I add a drop-down-list on my ASPX page, I don't have to re-code the RequiredFieldValidator all the time.

When I tried to add the required field validator as a child-control of the drop-down-list, I got the "does not allow child controls" error message as shown. Seems that the out-of-the-box drop-down-list does not allow child controls to be added.

Using the Code

I always have this principal when I do programming: "The biggest error on your application is normally caused by the-easiest-to-fix section". I spent hours yesterday to get this working, and guess what....the fix is very-very simple! Here it is. The code is in VB.NET.

What you have to do is override the CreateControlCollection method of the base class and create a new instance of it and pass the current class (Me for VB.NET, or this for C#).

VB
''' <summary>
''' Override the CreateControlCollection to overcome the "does not allow child controls".
''' </summary>
''' <returns></returns>
''' <remarks></remarks>

Protected Overrides Function CreateControlCollection() As System.Web.UI.ControlCollection
    Return New ControlCollection(Me)
End Function

That's it! You can then do the following:

VB
MyBase.Controls.Add(ctrValidator)

Points of Interest

Quiet easy, huh!? If you have the same problem when inheriting from out-of-the-box controls, this will be the fix.

Hope this helps.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)