tags:

views:

80

answers:

1

I have a control that I need to restrict the types of child controls that it can contain during design time (dragging a new control onto an existing control on the form designer). I tried to do this by overriding the OnControlAdded event:

Protected Overrides Sub OnControlAdded(ByVal e As System.Windows.Forms.ControlEventArgs)
    MyBase.OnControlAdded(e)

    If e.Control.GetType() IsNot GetType(ExpandablePanel) Then
        MsgBox("You can only add the ExpandablePanel control to the TaskPane.", MsgBoxStyle.Exclamation Or MsgBoxStyle.OkOnly, "TaskPane")

        Controls.Remove(e.Control)
    End If
End Sub

This seems to work, however I get an error message from Visual Studio immediately after the control is removed:

'child' is not a child control of this parent.

What does this mean? How can I accomplish this without errors occurring?

A: 

Generally you want to handle this in two places: the ControlCollection and in a custom designer.

In your control:

[Designer(typeof(MyControlDesigner))]
class MyControl : Control
{
    protected override ControlCollection CreateControlsInstance()
    {
        return new MyControlCollection(this);
    }

    public class MyControlCollection : ControlCollection
    {
        public MyControlCollection(MyControl owner)
            : base(owner)
        {
        }

        public override void Add(Control control)
        {
            if (!(control is ExpandablePanel))
            {
                throw new ArgumentException();
            }

            base.Add(control);
        }
    }
}

In your custom designer:

class MyControlDesigner : ParentControlDesigner
{
    public override bool CanParent(Control control)
    {
        return (control is ExpandablePanel);
    }
}
Mike LaSpina