问题
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