Loop Question

J

Jeff

....another beginner question - using visual web 2005 with VB

I have 20 labels - lbl1 through lbl20

I have a listbox containing values 1 through 20

I need to make label 1 through the selected value of the listbox visible, but the rest of the labels invisible

I'm assuming that the best way to do this is with 2 loops in the listbox click event something like:


for i = 1 to listbox1.selectedvalue
lbl i .visible = true
next

for i = listbox1.selectedvalue+1 to 20
lbl i.visible = false
next


....but I'm not sure how to actually code this.

Can someone point me in the right direction?

Thanks in advance

Jeff
 
G

GhostInAK

Hello Jeff,

Were it me I would use the TAG proeprty.. just because I dont like concatinating
control names.. Start with the first label and set it's tag proeprty to 1,
then the next to 2, and so on..

Then your loop will be something like this (assuming all numbers from 1 through
listbox1.selectedvalue are to be made visible and all others invisible..) :
Dim tControl as Control = Nothing
Dim tCount as Integer = 0
For Each tControl In Me.Controls
tCount = 0
Integer.TryParse(tControl.Tag, tCount)
If 0 < tCount Then
If tCount <= ListBox1.SelectedValue
tControl.Visible = True
Else
tControl.Visible = False
End If
End If
Next


The above code does not touch control within containers.. you can figure
that part out.

-Boo
 
B

Branco Medeiros

Jeff wrote:
I have 20 labels - lbl1 through lbl20
I have a listbox containing values 1 through 20
I need to make label 1 through the selected value of the
listbox visible, but the rest of the labels invisible
I'm assuming that the best way to do this is with 2 loops
in the listbox click event something like:


for i = 1 to listbox1.selectedvalue
lbl i .visible = true
next

for i = listbox1.selectedvalue+1 to 20
lbl i.visible = false
next
<snip>

Consider keeping the labels in an array, declared at the top level of
the form:

<aircode>
Private mLabels() As Label = New Label() { _
Lbl1, Lbl2, Lbl3, Lbl4, Lbl5, _
Lbl6, Lbl7, Lbl8, Lbl9, Lbl10, _
Lbl11, Lbl12, Lbl13, Lbl14, Lbl15, _
Lbl16, Lbl17, Lbl18, Lbl19, Lbl20 _
}
</aircode>

Then in the event that actually toggles the visible property, you can
use one or two loops, whatever suits you:

<aircode>
'Gets the relevant item
Dim Index As Integer = Integer.Parse(ListBox1.SelectedValue.ToString)



'One Loop
For I As Integer = 0 to mLabels.Length - 1
mLabels(I).Visible = I < Index
Next

'Two loops
For I As Integer = 0 to Index-1
mLabels(I).Visible = True
Next

For I As Integer = Index to mLabels.Length-1
mLabels(I).Visible = False
Next
</aircode>

Regards,

Branco.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top