none
Remove Control by its name ? RRS feed

  • Question

  • The code below removes a control , associated with the index given :

    Me.Controls.Remove(1)

    But this only works when the index of wanted control is known. What about removing controls by their name ?



    • Edited by Kevin993 Friday, March 29, 2019 9:58 PM
    Friday, March 29, 2019 9:57 PM

Answers

  • In this case the following removes a button by type and name

    Dim buttonName As String = "Button1"
    Dim button = Controls.OfType(Of Button).FirstOrDefault(Function(control) control.Name = buttonName)
    If button IsNot Nothing Then
        Controls.Remove(button)
    End If

    Or simply by name

    Dim buttonName As String = "Button1"
    Dim button = Controls.OfType(Of Control).FirstOrDefault(Function(control) control.Name = buttonName)
    If button IsNot Nothing Then
        Controls.Remove(button)
    End If

    One more thing, if the control is on another control such as a panel use this language extension

    Public Module Extensions
        <Runtime.CompilerServices.Extension>
        Public Iterator Function Descendants(Of T As Class)(ByVal control As Control) As IEnumerable(Of T)
            For Each child As Control In control.Controls
    
                Dim childOfT As T = TryCast(child, T)
                If childOfT IsNot Nothing Then
                    Yield childOfT
                End If
    
                If child.HasChildren Then
                    For Each descendant As T In child.Descendants(Of T)()
                        Yield descendant
                    Next
                End If
            Next
        End Function
    End Module

    Then

    Dim button = Descendants(Of Button)().ToList().FirstOrDefault(Function(control) control.Name = "Button1")
    If button IsNot Nothing Then
        button.Parent.Controls.Remove(button)
    End If


    Please remember to mark the replies as answers if they help and unmarked them if they provide no help, this will help others who are looking for solutions to the same or similar problem. Contact via my Twitter (Karen Payne) or Facebook (Karen Payne) via my MSDN profile but will not answer coding question on either.

    NuGet BaseConnectionLibrary for database connections.

    StackOverFlow
    profile for Karen Payne on Stack Exchange


    Friday, March 29, 2019 10:15 PM
    Moderator