Asim Sajjad
Asim Sajjad

Reputation: 2534

How to remove Parent of Control

I am removing button control from one list to another listh and following error occures

"Specified element is already the logical child of another element. Disconnect it first"

any idea how to remove that exception.

Upvotes: 2

Views: 5882

Answers (2)

Stremlenye
Stremlenye

Reputation: 595

Try this:

public partial class Form1 : Form
{
        private void button1_Click(object sender, EventArgs e)
        {
            Util.PlaceControlToContainer(this.button1, this.panel2);
        }
}
public static class Util
{
   public static void PlaceControlToContainer(Control control, Control container)
   {
       lock (control)
       {
          if (control.Parent != null)
          {
              control.Parent.Controls.Remove(control);
          }
          container.Controls.Add(control);
       }
   }
}

Upvotes: 1

Jon Cage
Jon Cage

Reputation: 37458

Should be fairly easy:

  1. Get the list of controls from your parent control.
  2. Call the Remove function on that list to remove your control.

So something like this:

myListControl.Controls.Remove(myControlToRemove);

Upvotes: 4

Related Questions