简体   繁体   中英

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?

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:

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM