C# – How to get AutoSizing for forms with dynamic controls

cnetwinforms

I have a Form with a TabControl on it.

Onto the TabControl TabPages are dynamically added (FYI: It's about configuration settings for different dynamical loaded modules).

Now I would like to have a way to get the Form – and/or the TabControl on the Form – to adjust its size according to the size of the added TabPage.

While writing this I realize that this could be someway more complicated than I thought: Since the different TabPages can be different in size the Form does have to change its size whenever another TabPage is selected or I have to set it to the size of the biggest TabPage once which seems to be the best approach.

Of course I could set the size programmatically by setting width and height to fitting values but first I need to know if there is no automated way to solve my problem and if not what is the best approach to realize this.

I already tried AutoSize=true which didn't solve my problem. 😉

I'm working with Visual Studio 2005 .Net 2.0 and C#.

Best Answer

First off it's generally considered bad UI practice to have a magically resizing form when all a user is doing is switching tabs.

With that said, I don't think you can do what you're asking to without writing code.

However it should be easy enough to determine the size of the largest control you'll be adding to the tab control, then sizing the form (before its displayed) accordingly. If you set the Anchor properties of the tab control to Ttop,left,right,bottom or set its dock to fill, you'll get the tab control to resize with the form... Of course you'll need to account for the visual padding when computing the form size from a house control.