For Each Loop Question
- I'm new to VB and am working on an assignment. There's a bonus question on For Each Loop which we haven't covered yet. What the question asks is, there are labels in a groupbox on a form. I need to add text to these labels at runtime using a For Each Loop. How would I code this?
Answers
Dim _iCounter as Integer = 1 For Each c As Control In GroupBox1.Controls If TypeOf (c) Is Label Then c.Text = "Department" & _iCounter _iCounter += 1 End If Next This will start from 1 and add te prefix to all the labels in the groupbox as per the sequence. If you want it to stop at 5 include an extra If condition
Ganesh Ranganathan
[Please mark the post as answer if it answers your question]
blog.ganeshzone.net- Marked As Answer byPhenomin Wednesday, November 04, 2009 5:13 PM
All Replies
for each control as label in whereyouhavethelabels
label.text = whateveryouwantittobe
next control
This is not the answer but the line you should go down. You need to write code to look at each control and if it is a label with the right name change the text to what you want
If you're not living on the edge, you're taking up too much room- hi,
hope it helps:
For Each c As Control In GroupBox1.Controls If TypeOf (c) Is Label Then c.Text = "this is a label in a groupbox" End If Next - Ok so the labels have to have the texts "Department 1" to "Department 5". How do I get it to increment the 1-5?
- If you want the wow factor :) just use LINQ:
For Each lbl As Label In (From o In GroupBox1.Controls Where TypeOf (o) Is Label Select o)
lbl.Text = "something"
Next
Please remember to mark the replies as answers if they help you. Dim _iCounter as Integer = 1 For Each c As Control In GroupBox1.Controls If TypeOf (c) Is Label Then c.Text = "Department" & _iCounter _iCounter += 1 End If Next This will start from 1 and add te prefix to all the labels in the groupbox as per the sequence. If you want it to stop at 5 include an extra If condition
Ganesh Ranganathan
[Please mark the post as answer if it answers your question]
blog.ganeshzone.net- Marked As Answer byPhenomin Wednesday, November 04, 2009 5:13 PM
For Each c As Control In GroupBox1.Controls For i As Integer = 1 To 5 If TypeOf (c) Is Label Then c.Text = "Department" & i End If Next i Next <br/><br/><br/>
If you're not living on the edge, you're taking up too much room
You could use LINQ as follows
Dim DepartmentLabels = From l In GroupBox1.Controls.Cast(Of Control)() _ Where TypeOf l Is Label And l.Text.Contains("Department") _ Order By l.Text
KSG- You can do a for each directly over a LINQ query. See my previous post below. No need to declare a variable for this particular porpuse.
Please remember to mark the replies as answers if they help you. - Worked like a charm. This made sense to me. At first it didn't work and had no errors but couldn't understand why, then I realized it was a panel, not a groupbox... Thanks to everyone for their input. Help by all much appreciated.


