Search code examples
vb.netwinformsuser-controls

Add control at runtime to user control's inner panel


I have a user control that contains 2 panels. Panel1 is the parent for Panel2 so Panel2 is placed inside the Panel1 container. Now, at runtime, I want to add controls to my user control. These new controls must be placed inside Panel2. Addings controls with myUserControl.Controls.Add would normally put the new controls into the user control itself and not inside Panel2. I would like Panel2 to be the default container for all controls that are added to the user control at runtime. How to do this?


Solution

  • You can override OnControlAdded, verify whether the UC Handle is already created (InitiaizeComponent() has already being executed, so all child Controls added in the Designer have already been added to the UC's Controls collection), then add the new Control to Panel2.Controls collection:

    Public Class MyUSerControl
        Inherits UserControl
    
        Protected Overrides Sub OnControlAdded(e As ControlEventArgs)
            If IsHandleCreated AndAlso e.Control IsNot Panel1 Then
                Panel2.Controls.Add(e.Control)
            End If
            MyBase.OnControlAdded(e)
        End Sub
    End Class
    

    Or, you could add a public method that performs this action:

    Dim btn1 = New Button() With {.Text = "Button1", .Name = "Button1"}
    Dim btn2 = New Button() With {.Text = "Button2", .Name = "Button2"}
    
    myUSerControl.AddControls(btn1)
    ' Or
    myUSerControl.AddControls({btn1, btn2})
    

    Public Class MyUSerControl
        Inherits UserControl
    
        Public Sub AddControls(ParamArray newControls As Control())
            Panel2.Controls.AddRange(newControls)
        End Sub
    End Class