Stefan Dunn
Stefan Dunn

Reputation: 5513

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.

Upvotes: 2

Views: 2908

Answers (2)

Hans Passant
Hans Passant

Reputation: 942237

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.

Upvotes: 2

Rotem
Rotem

Reputation: 21947

The designer will do this automatically because it assumes that when you drag one control over another, you want to make it a child of that control.

What I usually do to get around this is to create the control in a different place on the form, and then use the properties to manually match the positions of sizes of the two controls.

Upvotes: 0

Related Questions