How can I select a random control?

NKN

Member
Joined
Dec 9, 2011
Messages
19
Programming Experience
Beginner
I have a number of pictureboxes in my form, Some of them are named "Picturebox_Enemy1"; "Picturebox_Enemy2"... "Picturebox_EnemyN".
I want to select a random picturebox containing in its name "Enemy". how can i do that?
 
Dim rng As New Random

Dim allPictureBoxes = Controls.OfType(Of PictureBox)()
Dim enemyPictureBoxes = allPictureBoxes.Where(Function(pb) pb.Name.Contains("Enemy"))
Dim ramdomisedPictureBoxes = enemyPictureBoxes.OrderBy(Function(pb) rng.NextDouble())
Dim randomPictureBox = randomisedPictureBoxes.First()
Succinctly:
Dim rng As New Random
Dim randomPictureBox = Controls.OfType(Of PictureBox)().
                                Where(Function(pb) pb.Name.Contains("Enemy")).
                                OrderBy(Function(pb) rng.NextDouble()).
                                First()
 
I got this error:

An error occurred creating the form. See Exception.InnerException for details. The error is: Public member 'Where' on type '<OfTypeIterator>d__aa(Of PictureBox)' not found.
 
This is the code i have:

Public Class Form1


Dim rng As New Random


Dim allPictureBoxes = Controls.OfType(Of PictureBox)()
Dim enemyPictureBoxes = allPictureBoxes.Where(Function(pb) pb.Name.Contains("Enemy"))
Dim ramdomisedPictureBoxes = enemyPictureBoxes.OrderBy(Function(pb) rng.NextDouble())
Dim randomPictureBox = ramdomisedPictureBoxes.First()






Private Sub Form1_Load(sender As System.Object, e As System.EventArgs) Handles MyBase.Load


Dim rng As New Random
Dim randomPictureBox = Controls.OfType(Of PictureBox)().
Where(Function(pb) pb.Name.Contains("Enemy")).
OrderBy(Function(pb) rng.NextDouble()).
First()




End Sub




Private increment, increments, current As Integer, myCtrl As Control






Private Sub StartMovingControl()
myCtrl = randomPictureBox
increment = 2
increments = 16
current = 0
Timer1.Start()
End Sub


Private Sub Timer1_Tick(sender As Object, e As EventArgs) Handles Timer1.Tick
myCtrl.Top -= increment
current += 1
If current = increments Then
If increment > 0 Then
increment = -increment
current = 0
Else
Timer1.Stop()
End If
End If
End Sub






End Class
 
You can't declare and assign those variables at the class level like that. The code I provided was intended to be used where you need to use the PictureBox. You could (and probably should) create the Random object at the class level but the rest would be placed in a Button Click event handler or the like.
 
Back
Top