Home > database >  Have variables turn into an objects name
Have variables turn into an objects name

Time:01-21

I'm trying to create a grid using PictureBoxes. A PictureBox name is pb11 (for 1,1 coordinates), pb21 etc.

I'm trying to do something like this:
pb(variable) or (variable)

The variable would be for example 11 or in example 2 pb11.

So rather than having to do this

If squaretobecoloured = 11 Then
    pb11.BackColor = Color.Red
ElseIf squaretobecoloured = 12 Then
    pb12.BackColor = Color.Red
End If

and continue it 100 times
Instead I would rather do something like this

pb(squaretobecoloured).BackColor = Color.Red

Just to clarify the picture boxes are from the toolbar and aren't created within the program.

CodePudding user response:

.Net languages do not convert strings to variables like that. Instead, you need to add your existing Pictureboxes to an array. This will allow you to reference them by index:

Dim pbGrid(,) As PictureBox = {
    {pb11, pb12},
    {pb21, pb22}
}

Note that the arrays will be 0-indexed instead of 1-indexed. Now you can do something like this:

pbGrid(0, 1).BackColor = Color.Red

or

Dim row As Integer = 0
Dim column As Integer = 1
pbGrid(row, column).BackColor = Color.Red

CodePudding user response:

This is easy enough to do with the recurse option of Controls.Find():

squaretobecoloured = 11
Dim ctl As Control = Me.Controls.Find("pb" & squaretobecoloured, True).FirstOrDefault
If Not IsNothing(ctl) AndAlso TypeOf ctl Is PictureBox Then
    Dim pb As PictureBox = DirectCast(ctl, PictureBox)
    pb.BackColor = Color.Red
Else
    MessageBox.Show("PB #" & squaretobecoloured & " not found!")
End If

If you want to combine this with the approach proposed by Joel Coehoorn, then you could build the 2D array in the Load() event of the Form by using nested loops for the X,Y values and searching for the PBs by name as I've done, then adding the found PBs into the correct locations of your 2D array. This way you can design the grid via the IDE on your Form and the code would automatically find them all at run-time instead of you hard-coding the names of all them into the 2D array.

CodePudding user response:

Try this:

For i = 0 To 100
    Me.Controls("pb" & i).BackColor = Color.Red
Next
  •  Tags:  
  • Related