Reparent a control in C#

[reparent]

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 Example   Follow me on Twitter   RSS feed   Donate




This entry was posted in controls and tagged , , , , , , , . Bookmark the permalink.

Leave a Reply

Your email address will not be published. Required fields are marked *