如何在 vb.net 中获取对象的名称

How to get the object's name in vb.net

我正在尝试在表单中动态添加和删除对象。我被困在如何获取要删除的对象的唯一标识符上。

        'Collection of controls
        For Each ctl In Me.Controls
            'Get control type
            If TypeOf ctl Is Label Then
                'Get control name/index id/text or any property of current ctl
                'How do I continue from here?
                'Me.Controls.Remove(ctl)
            End If
        Next

提前感谢solutions/suggestions。 如果可以,我想知道解决方案的解释。

如果你们需要知道我是如何动态添加对象的,这里是:

        For i = 1 To Spots
            Dim newLabel As New Label
            Dim newLoc As Integer = iLoc + (i * 30)

            With newLabel
                .Name = "lblSpot" & i
                .Text = "Spot " & i
                .Size = New Size(100, 20)
                .Location = New Point(3, newLoc)
            End With

            AddHandler Me.Load, AddressOf frmParking_Load
            Me.Controls.Add(newLabel)
        Next

您可以将 ctl 转换为 Label,然后使用 .Name 找到要删除的控件

不建议在更改收集时使用 For Each,所以这是您想要的代码

Dim i = 0
While i < Me.Controls.Count
    Dim c = Me.Controls(i)
    If TypeOf c Is Label Then
        Dim Lbl As Label = CType(c, Label)
        If Lbl.Name.Contains("lblSpot") Then
            Me.Controls.Remove(c)
        End If
    End If
End While