I am working on a UserControl
and I am looking for a way to prevent developer to place this UserControl
more than one time into a form. All this in Design Time. In other words, how can I detect if my UserControl
is already placed into ParentForm
or not, in Design Time(!!!), and prevent the second placement if there is already one there?
I tried something like this example below... First I am not sure if this is the "correct" way and second I can't find how to remove or stop the placement of UserControl
in case there is already one.
Again, all this, in Design Time!!!
Private Sub MyUserControl_Load(sender As Object, e As EventArgs) Handles MyBase.Load
Dim _Count As Integer
Dim _UserControl As MyUserControl
For Each _UserControl In Me.ParentForm.Controls
If _UserControl.Name.Contains("MyUserControl") Then
_Count += 1
End If
Next
If _Count > 1 Then
MsgBox("Control have been placed.")
Else
MsgBox("Control haven't placed yet.")
End If
End Sub
Finnaly I ended to this...
Private Sub Me_ParentChanged(sender As Object, e As EventArgs) Handles Me.ParentChanged
Dim _ParentForm = DirectCast(Me.FindForm, Control)
Dim _ControlName As String
If _ParentForm IsNot Nothing Then
For Each _Control As Control In _ParentForm.Controls
If TypeOf _Control Is MyUserControl AndAlso _Control IsNot Me Then
Throw New ArgumentOutOfRangeException("", "You can place only one " & _ControlName & " control per form.")
End If
_Control = _ParentForm.GetNextControl(_Control, True)
Next
End If
End Sub