Looping though elements in vb.net

扶醉桌前 提交于 2021-02-11 13:48:06

问题


Is there a way I can loop though multiple elements with number based names, changing their properties?

Example:

Here are an example set of elements on my form:

Element1
Element2
Element3
Element4
Element5

This is the kind of thing i was thinking of:

For i = 1 To 5
    Element + i .BackColor = Color.Maroon 
Next

This is just because I have a large number of elements, which i would like to change the properties of during the application running.

Thanks for any answers.


回答1:


Sure, replace Me.Controls with another control collection if that is not the right one.

Label example:

For i = 1 To 5
  Dim lb = TryCast(GameInterface.Controls("Element" & i.ToString), Label)
  If lb IsNot Nothing Then lb.BackColor = Color.Maroon 
Next



回答2:


If it is for labels on form then try this: replace parent with Parent control

Private Sub SetControls()
        Dim xControl As Control
        For Each xControl parent.Controls
            If (TypeOf xControl Is Label ) Then
                xControl.backcolor= Color.Maroon
            End If
        Next xControl
End Sub


来源:https://stackoverflow.com/questions/26563958/looping-though-elements-in-vb-net

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!