Search code examples
vb.netformswinformspanel

VB.NET usercontrols to remove main form controls


I have a main form which has a button and a FlowLayoutPanel. Also I created a UserControl which has some buttons and other controls.

When I click the button in my main form it adds my usercontrol to the panel (as many times as clicked):

Private Sub btnAdd_Click(sender As Object, e As EventArgs) Handles btnAdd.Click
    Dim ctrl As New DownloadControls
    FlowLayutPanel1.Controls.Add(ctrl)
End Sub

That works fine. For example, I have added 5 instances of that UserControl to the panel in main form, now I want to delete any one of those using the remove button which is on each instance of added usercontrols (DownloadControls) and keep the Panel items organized.

How can I achieve that?


Solution

  • You can create a new RemoveClicked event for your user control and raise it when the user clicked on remove button. Then you can handle that event your form to remove the control.

    Code for your user control:

    Public Event RemoveClicked As EventHandler
    Public Sub OnRemoveClicked(e As EventArgs)
        RaiseEvent RemoveClicked(Me, e)
    End Sub
    
    Private Sub btnRemove_Click(sender As Object, e As EventArgs) Handles btnRemove.Click
        OnRemoveClicked(EventArgs.Empty)
    End Sub
    

    Code for your form:

    Private Sub btnAdd_Click(sender As Object, e As EventArgs) Handles btnAdd.Click
        Dim ctrl As New DownloadControls
        AddHandler ctrl.RemoveClicked, AddressOf ctrl_RemoveClicked
    
        Me.FlowLayutPanel1.Controls.Add(ctrl)
    End Sub
    
    Private Sub ctrl_RemoveClicked(sender As Object, e As EventArgs)
        Me.FlowLayutPanel1.Controls.Remove(DirectCast(sender, Control))
    End Sub
    

    You can learn more about handling and raising events: