Hi I have been writing VB.Net for a few weeks,
it has been going well but I am now stuck.

I have multiple user controls on a form and I need a way to remove a selected one. I was hoping that something like this would do it

Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
Me.Controls.RemoveByKey("UserControl")
refresh_Form()
End Sub

Private Sub Button2_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button2.Click
Me.Controls.RemoveByKey("UserControl1")
refresh_Form()
End Sub

But this only works for Button1, I am guessing this is because each instance is not called. “UserControl” and “UserControl1”. I have added the user controls using code and was wondering if there is anything I could do at the point of adding them, to idenfy them for later on. (i.e give them a name I could use later on)

Sorry if this is a daft question, it’s all fairly new to me.
Many thanks in advance

Try this:

If Me.Controls.Contains(UserControl1) Then
            Me.Controls.Remove(UserControl1)
        End If

Thanks for the reply,

This is what I ended up using.
Live and learn

Public Class Form1
    Public Mycontrol As New UserControl
    Public Mycontrol1 As New UserControl

    Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
        Add_controls()
    End Sub

    Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
        Remove_controls(Me.Mycontrol)
    End Sub
End Class

Module Module1
    Sub Add_controls()
        'add two user controls'
        Form1.Mycontrol.Location = New Point(0, 0)
        Form1.Controls.Add(Form1.Mycontrol)

        Form1.Mycontrol1.Location = New Point(60, 60)
        Form1.Controls.Add(Form1.Mycontrol1)
    End Sub
    Sub Remove_controls(ByVal _Countrol As Control)
        'remove a control'
        If Form1.Controls.Contains(_Countrol) Then
            Form1.Controls.Remove(_Countrol)
        End If
    End Sub
End Module
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.