Search code examples
c#winformschildrenpanels

Prevent Child Components when Overlapping Panel


I have a WinForms application which has two panels which individually contain a usercontrol component (one in each panel). How ever, because both panels are the same size and in the same location, the top most panel becomes a child of the other panel. I want to be able to hide one panel and then show the other panel:

this.panel1.visibile = false;
this.panel2.visibile = true;

But when I hide panel1, the second panel is hidden as well.

How can I make panel2 a non-child of panel1?

I like to keep things simple because I'm new to C# Programming.


Solution

  • This is a common accident in the designer. Dropping the second panel on top of the first one will make it a child of the first panel. Two basic strategies to fix this:

    • View + Other Windows + Document Outline. Click the second panel in the list and drag it to the form. You'll need to fix up the Location property by hand by typing its value in the Property window.

    • Keep the upper left corner of the second panel just a bit to the left or top of the first panel. Put it in the right place in the form's constructor by assigning its Location property after the InitializeComponent() call.

    Check this answer for a control that works well at design time and lets you easily flip panels at runtime.