I have a label that I want to be put on top of a picture box. I want it to have a transparent background.
Upon searching for answers here, I found this solution that worked:
infoText1.Parent = bg1; infoText1.BackColor = Color.Transparent;
However, when I tried to run the project, the label moved to the very bottom of the picture box.
The Location
of a control is relative to its parent so if you change the Parent
, you change it's position relative to the form by the amount that the new parent is offset from the old. The way to compensate for this is to get the absolute position of the control before you change the Parent
, then change the Parent
, then put it back in that same absolute position. You can do that like so:
'Get the screen coordinates of the child control's Location.
Dim screenLocation = childControl.PointToScreen(Point.Empty)
'This would do the same thing:
'Dim screenLocation = 'childControl.Parent.PointToScreen(childControl.Location)
'Change the Parent.
childControl.Parent = newParent
'Set the child control's Location to those same screen coordinates.
childControl.Location = newParent.PointToClient(screenLocation)
If you haven't already, you should position the Label
exactly where you want it in the designer and then that code will maintain that position while changing the parent.