I have 10 labels named lbl1
, lbl2
, ... lbl10
I'd like to change their propriety (using a cicle) with the cicle index
for i as integer=1 to 10 step 1
lbl (i) = PROPRETY开发者_如何转开发 'I know this is wrong but it's what I would do...
end for
I'm using a workaround, but I'm looking for a better way..
Dim exm(10) As Label
exm(1)=lbl1
exm(2)=lbl2
...
exm(10)=lbl10
for i as integer=1 to 10 step 1
exm (i) = PROPRETY
end for
Your "workaround" is a fine way to do it. You need to have your controls in some kind of collection, in order to iterate through them.
Perhaps you can use array initializers in order to initialize the array more cleanly (less code): Object and array initializers in VB .NET
You could go through the Controls collection, and do your action for each Label you find, but that is probably not what you want - since that would get you all of the labels on the form.
Taking M.A. Hanin's answer as a base you could simply do something like:
(From l in Me.Controls _
Where RegEx.IsMatch(l.Name, "^lbl[0-9]+") AndAlso TypeOf l is Label
Order By l.Name).ForEach(Function(l) SetPropertyForLabel(l))
Sub SetPropertyForLabel(lbl as Label)
' Do some stuff '
lbl.Text = lbl.Name
End Sub
This way you can use a regular expression to filter the name of tour labels (the one provided matches the pattern you gave on the O.P.) and perform the action on a custom method.
If the labels are contained in a Form or some other container, you can use a query similiar to this:
Dim myLabels = (From g As Label In Me.Controls Select g _
Where Mid(g.Name, 1, 3) = "lbl" Order By g.Name)
Then iterate through the collection, applying your property.
You work around is actually the recommended technique. You may want to use a List(Of Label) and a For...Each statement. This will eliminate the hard-coding and ease maintenance.
精彩评论