Resize panel to fit contained elements in windows forms

36,798

Solution 1

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)

Solution 2

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();
Share:
36,798
user420667
Author by

user420667

Develop mainly in C# for ASP.NET, and JavaScript with jQuery. Currently looking into Silverlight. Have used Matlab, C, C++, Java, Python, Prolog. Still wanting to learn COM and calling various external dlls. Always hoping to make the workflow more efficient. (Wordpress) blog to come.

Updated on July 05, 2022

Comments

  • user420667
    user420667 almost 2 years

    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
    user420667 over 12 years
    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.