Collapsible Forms made easy with WinForms, Layout Panels and AutoSize.

You know what a collapsible window is – it’s usually used to show advanced features or to show extra information about an error. Two examples:

When the error dialog opens, it shows only the basic information so as not to scare the user:

 

 

When the user clicks on Expand, she sees the extra information:

 

 

So how do you do this?

 

There are two ways I employed so far:

 

1. Quick and dirty: Use constant values when the “Collapse/Expand” button is clicked. Move controls around (namely, the ones containing the buttons at the bottom).

2. Plain dirty: Use hidden controls to act as “markers” – that way, you still have  visual control over where things collapse or expand to via the designer. Pretty easy to do, still need to move controls around and muck with resizing forms.

 

I usually use method two – it’s as fast as  doing the other one, but much easier to control.

 

But now I have a new favorite way of doing this..

 

By using a FlowLayoutPanel and autoresizing forms, you can get the form to do most of the work  of growing and shrinking all by itself. This is how you do it:

 

1. Set your form to AutoSize true, and the AutoSizeMode to GrowAndShrink.

2.  Place a FlowLayoutPanel in your form and make it dock-fill the form.

3. Set the panel’s AutoSize to true and it’s AutoSizeMode to GrowAndShrink. Set the FlowDirection to TopDown.

4. Resize your form to the siize you feel comfortable with.

5. Change the MaximumSize property of the form to be the width it currently has with some large number for height (so, if your form has a width of 340, change MaximumSize to be 340,1024). Do the same thing for the panel. If you don’t do this, the form will grow horizontally if labels you have need more space.

6. Add your controls – in the example above, there’s a label for the error message and a read-only textbox for the details.

7. Add your buttons (Okay and “Expand” probably) – you probably want to first add a panel and then add the buttons to that panel.

8. In your Expand/Collapse button, change the visibility of the Detail textbox.

9. In the VisibleChange event on the Detail textbox, change the text of the button (so it alternates between “Collapse” and “Expand” or something.

 

That’s it. WinForms will do the rest of the heavy lifting for you when the form is shown.

 

I am attaching a code sample.

 

WindowsApplication1.zip