I have a control that can only be implemented in specific situations (eg: it can only be added to the ControlCollection of a specific panel or form). To achieve this, I have overridden the OnParentChanged method of the control to see if the parent has implemented a given interface:
Public Class MyControl
Private MyParentControl As IMyControlInterface
Protected Overrides Sub OnParentChanged(ByVal e As System.EventArgs)
If MyBase.Parent IsNot Nothing Then
Me.MyParentControl = TryCast(MyBase.Parent, IMyControlInterface)
If Me.MyParentControl Is Nothing Then
Throw New Exception("Control can only be added to an object that implements IMyControlInterface.")
End If
End If
MyBase.OnParentChanged(e)
End Sub
End Class
I am trying to enable this code so that the control can be dragged from the controls panel of the Visual Basic designer to the design surface. I have defined the panel as:
Public Class MyControlPanel
Inherits Panel
Implements IMyControlInterface
...
End Class
and the form is designer-generated (ie: a PartialClass extension of the form), to wit:
Public Class Form1
Implements IMyControlInterface
...
End Class
For some reason, when I drag MyControl to the form from the controls panel, it invokes the exception. However, when I drag MyControlPanel to the form, and then drag MyControl onto MyControlPanel1 (the name given by the designer), it accepts the dragged control.
I do not understand why one invocation accepts the add, while the other does not. Does anyone have any idea about this?
I thank you in advance for your help...