views:

314

answers:

4

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
+2  A: 

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.

driis
+1  A: 

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.

M.A. Hanin
+1  A: 

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.

Paulo Santos
Can you make it any more difficult?
AMissico
Thank you, I'll embed the lbl in a panel to check only those lbl
Marcx
@AMissico And the difficulty of this code is where exactly?
Paulo Santos
Reading and maintenance. Hard-coded. Too much code, too much room for error, too hard for someone to fix, too hard to refactor when need. Just too difficult. What happens when some changes the name of a control, or changes the type, not using LINQ? Just to name a few.
AMissico
Moreover, since this is VB.NET, then using RegEx is overkill and wasteful as it requires 64KB in the Large Object Heap. Better to use VB's LIKE operator.
AMissico
I really dont think matching on label names is a good way to do this.
driis
+1  A: 

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.

AMissico