Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do you resize a form to fit its content automatically?

Tags:

c#

.net

winforms

I am trying to implement the following behaviour:

On a form there is a tabcontrol. On that tabcontrol there is a treeview. To prevent scrollbars appearing, I would like the form to change its size according to the contents of the treeview when displayed for the first time.

If the treeview has too many nodes to be displayed on the default size of the form, the form should change it's size so that there is no vertical scrollbar on the treeview (up to a maximum size allowed by the size of the screen).

What I need to know is, if it is possible to achieve this behaviour through the properties of the controls. I'm sure this can be achieved by calculating and settings the sizes of the elements programmatically, but I would like to know if there is a way to achieve this by settings like AutoSizeMode etc.

[UPDATE]

It's the first dialog a user of my application sees: It's a dialog to select the database to work with. It's a list of databases, with a tabcontrol, buttens etc. If the list is too long, scrollbars appear and a colleague of mine wants them to disappear.

like image 782
Inno Avatar asked May 11 '11 10:05

Inno


People also ask

How do I resize a form?

By dragging either the right edge, bottom edge, or the corner, you can resize the form. The second way you can resize the form while the designer is open, is through the properties pane. Select the form, then find the Properties pane in Visual Studio. Scroll down to size and expand it.


1 Answers

Use the AutoSize and AutoSizeMode properties.

http://msdn.microsoft.com/en-us/library/system.windows.forms.form.autosize.aspx

An example:

private void Form1_Load(object sender, EventArgs e) {     // no smaller than design time size     this.MinimumSize = new System.Drawing.Size(this.Width, this.Height);      // no larger than screen size     this.MaximumSize = new System.Drawing.Size(Screen.PrimaryScreen.Bounds.Width, Screen.PrimaryScreen.Bounds.Height, (int)System.Windows.SystemParameters.PrimaryScreenHeight);      this.AutoSize = true;     this.AutoSizeMode = AutoSizeMode.GrowAndShrink;      // rest of your code here... } 
like image 88
Derek Johnson Avatar answered Sep 23 '22 19:09

Derek Johnson