13

I am creating a collapsible panel element, which would essentially be a panel element with a button element and a panel element below the button. Clicking the button causes the neighboring panel to have Visible = false. I would like to resize the containing panel when the child panel is set to invisible.

I have done this manually, by setting the Size property to be the sum of the widths and heights of the visible elements (either the button or the button and the child panel.)

I am curious to know though if there was a way to force the resize of the containing panel without manually calling Size.

I guess I'm looking for the inverse of the property Dock=Fill, which automatically resizes elements based on the size of their containing element.

Thanks in advance.

user420667
  • 6,552
  • 15
  • 51
  • 83
  • I think that is it. Maybe you can use the FlowLayoutPanel to automatically adjust the panels inside its client area, but I think what you are doing is correct. – mhttk Sep 27 '11 at 20:46
  • What's the point of resizing it when nobody can see it? – Hans Passant Sep 27 '11 at 21:06
  • @Hans Passant: Sorry, the question may have been worded funnily. There are two panels. One is the one that goes invisible, and the other contains the button and the invisible panel. The outer panel needs to shrink when the inner panel goes invisible, otherwise it's not collapsing, it's just disappearing but still taking up the same space it used to. I was trying to do something along the lines of what you see in Visual Studio Forms Toolbox when you expand and collapse say the "Common Controls" part. – user420667 Sep 27 '11 at 21:23

2 Answers2

12

How about doing:

panel1.Size = new Size(0, 0);
panel1.AutoSize = true;

and then instead of changing the visibility, do this:

panel1.Controls.Remove(panel2);

and when you want to bring it back:

panel1.Controls.Add(panel2);

(panel1 is the back-panel)

ispiro
  • 26,556
  • 38
  • 136
  • 291
  • 1
    Great thinking. So AutoSize was the property I was looking for. The only thing is is that this should be followed by a panel2.BringToFront() or it will throw off the docking order. – user420667 Sep 27 '11 at 21:46
5

I just tried the answer given by ispiro. You dont need to remove and add the control. Setting Visible can work. It depends on when you perform the layout. If panel2 performs the layout before panel1, panel2 will not resize. To make it easier, use the parents PerformLayout instead.

It's used like this:

panel1.ResumeLayout(false);
panel2.ResumeLayout(false);
this.ResumeLayout(false);
this.PerformLayout();
Neuron
  • 5,141
  • 5
  • 38
  • 59
Jeson Martajaya
  • 6,996
  • 7
  • 54
  • 56