如何对多个对象进行分组

时间:2018-08-21 01:34:03

标签: vb.net

我一直在寻找一种将多个对象组合在一起以更改公共值的方法,但是没有成功。我被迫做这样的事情:

Label10.Visible = True
Label11.Visible = True
Label12.Visible = True
Label13.Visible = True
Label14.Visible = True
RectangleShape8.Visible = True
RectangleShape9.Visible = True
RectangleShape10.Visible = True
RectangleShape11.Visible = True

Ect,是否有一种方法可以分组或声明多个对象以同时引用所有对象?我尝试声明,但未成功。感谢您的高级帮助。

2 个答案:

答案 0 :(得分:1)

您可以使用以下内容:

Dim RectangleShapeGroup() As String = {"RectangleShape8", "RectangleShape9", "RectangleShape10", "RectangleShape11"}
Dim LabelGroup() As String = {"Label10", "Label11", "Label12", "Label13", "Label14"}

For Each ctrl As Control In Me.Controls
    If Array.IndexOf(RectangleShapeGroup, ctrl.Name) > -1 Or Array.IndexOf(LabelGroup, ctrl.Name) > -1 Then
        ctrl.Visible = True
    End If
Next

如果要显示所有Label控件,可以使用以下命令:

For Each ctrl As Control In Me.Controls
    If TypeOf ctrl Is Label Then
        ctrl.Visible = True
    End If
Next

...或名称以LabelRectangleShape开头的所有控件:

For Each ctrl As Control In Me.Controls
    If ctrl.Name.StartsWith("Label") Or ctrl.Name.StartsWith("RectangleShape") Then
        ctrl.Visible = True
    End If
Next

答案 1 :(得分:0)

只需将控件添加到List(Of ControlType),然后遍历即可更改任何属性。此代码适用于Windows窗体。如果这是另一种类型的申请,请在您的问题中注明。

Private lstLabels As New List(Of Label) From {Label10, Label11, Label12, Label13, Label14}

    Private Sub MakeLabelsVisible()
        For Each l In lstLabels
            l.Visible = True
        Next
    End Sub