I've been having a big issue with child and parent objects in vb.net (more specifically, in a VB.net Windows Forms Application). In the example code, I have assigned the contents of PieceArray (which each correspond to a PictureBox on the screen), and have added these values to a parent called Checkerboard (which is another PictureBox on which the other elements are placed upon).
For this code, it is very important that I use the Me.Controls() function, as it allows me to store a string with the same name as an object, and call the object from that string.
Public PieceArray(7) As PictureBox
PieceArray(0) = WK1
PieceArray(1) = WQ1
PieceArray(2) = WB1
PieceArray(3) = WB2
PieceArray(4) = WN1
PieceArray(5) = WN2
PieceArray(6) = WR1
PieceArray(7) = WR2
For x = 0 To 7
Checkerboard.Controls.Add(PieceArray(x))
Next
Me.Controls(WR1).Location = New Point(0,0)
However, I have found that I am unable to access the objects once I have assigned them to a parent. I have tried multiple lines, such as:
'Me.Controls(WR1).Location = New Point(0,0)
'Me.Controls("WR1").Location = New Point(0,0)
'Me.Controls(Checkerboard(WR1)).Location = New Point(0,0)
'Checkerboard.Controls(WR1).Location = New Point(0,0)
'Checkerboard.Controls("WR1").Location = New Point(0,0)
However, the same issue persists. Please could someone advise me on this?
Note: I should add that if I put the line
Me.Controls("WR1").Location = New Point(0,0)
Before the for loop, the code performs perfectly, meaning that Me.Controls() can work on strings for the variable names, just not for ones that have a parent.
Control.Controls
only returns the controls immediately contained within Control. In order to use the Controls property you'd need to run that on the "parents" instead of Me
. Instead you can use the Control.Controls.Find
function
Me.Controls.Find(WR1, True).Single().Location = New Point(0, 0)
' True as the second argument indicates you want to search all children