Search code examples
asp.netwebformscustom-server-controls

Prevent other server controls as children of a custom ASP.NET control


Is there a way, other than creating a custom ControlBuilder class, to prevent server controls from being added as children in a custom ASP.NET control?

For example, let's say I am building my own Panel control:

<my:SpecialPanel ID="SpecialPanel1" runat="server">
    <!-- Allow valid HTML -->
    <input id="tbEmailAddress" type="text" />
</my:SpecialPanel>

I want to prevent users from adding server-side controls inside the SpecialPanel:

<my:SpecialPanel ID="SpecialPanel1" runat="server">
    <!-- WRONG - Throw an Exception -->
    <asp:TextBox ID="tbEmailAddress" runat="server" />
</my:SpecialPanel>

Any suggestions?


Solution

  • You could override the Control.AddParsedSubObject method:

    public class SpecialPanel : Control
    {
       protected override void AddParsedSubObject(Object obj) 
       {
          if (obj is Control) 
          {
             throw new InvalidOperationException(
                 "The 'SpecialPanel' control cannot contain server controls");
          }
       }
    }
    

    Related resources: