Title: Reparent a control in C#
Changing a control's parent is easy. Simply set its Parent property to the control that should contain it.
This example uses the following code.
// Move the Button from one GroupBox to the other.
private void btnReparentMe_Click(object sender, EventArgs e)
{
if (btnReparentMe.Parent == groupBox1)
{
// Move into GroupBox2.
btnReparentMe.Parent = groupBox2;
}
else
{
// Move into GroupBox1.
btnReparentMe.Parent = groupBox1;
}
}
The program compares the Button's current parent with the two GroupBoxes and moves the Button into the one that does not currently contain it.
The control's other properties remain the same. In particular, the control's Location property is the same so the Button has the same position in its new parent that it had in it old parent.
Download the example to experiment with it and to see additional details.
|