Reputation: 141
I have labels named: label1
, label2
, ...label16
. I want to assign a random number to all of them.
Something like this could work but I don't know the syntax:
for i = 1 to 16
label(i).text = Math.Ceiling(Rnd() * 99)
next
Your suggestions would be appreciated.
Upvotes: 0
Views: 103
Reputation: 15091
Private Sub Button2_Click(sender As Object, e As EventArgs) Handles Button2.Click
Dim labels As New List(Of Label) From {Label1, Label2, Label3, Label4}
For Each l As Label In labels
l.Text = rand.Next(99).ToString
Next
End Sub
To use your approach
Declare a variable for the Random class outside your method (a Form level variable).
Create a List of labels.
Loop through all the labels in your list and set the .Text property with the .Next method of the Random class.
Upvotes: 1
Reputation:
Getting a random Integer
Use the Random class instead of the Rnd function to get a random Integer
within a specified range in the Random.Next(Int32, Int32)
method. Declare a class variable of Random
type:
Private ReadOnly rand As New Random
Finding a range of controls
This code snippet iterates over the Controls
collection of the container, returns - if any - the Label
controls where their names are equals to a range of names starts from label1
to label16
, and finally, assign a random Integer
to their Text
properties:
Private Sub TheCaller()
For Each lbl In Controls.OfType(Of Label).
Where(Function(x) Enumerable.Range(1, 16).
Any(Function(y) x.Name.ToLower.Equals($"label{y}")))
lbl.Text = rand.Next(1, 100).ToString
Next
End Sub
Just in case, if the Label
controls are hosted by different containers, then you need a recursive function to get them:
Private Function GetAllControls(Of T)(container As Control) As IEnumerable(Of T)
Dim controls = container.Controls.Cast(Of Control)
Return controls.SelectMany(Function(x) GetAllControls(Of T)(x)).
Concat(controls.OfType(Of T))
End Function
And call it as follows:
Private Sub TheCaller()
For Each lbl In GetAllControls(Of Label)(Me).
Where(Function(x) Enumerable.Range(1, 16).
Any(Function(y) x.Name.ToLower.Equals($"label{y}")))
lbl.Text = rand.Next(1, 100).ToString
Next
End Sub
Upvotes: 1
Reputation: 43574
You can use this using Controls.Find
:
For i As Integer = 1 To 16
Dim arrCtrl() As Control = Me.Controls.Find("label" & i, True)
If arrCtrl.Length = 1 AndAlso TypeOf arrCtrl(0) Is Label Then
DirectCast(arrCtrl(0), Label).Text = Math.Ceiling(Rnd() * 99)
End If
Next
Upvotes: 2