[c#] How do you resize a form to fit its content automatically?

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.

This question is related to c# .net winforms

The answer is


From MSDN:

To maximize productivity, the Windows Forms Designer shadows the AutoSize property for the Form class. At design time, the form behaves as though the AutoSize property is set to false, regardless of its actual setting. At runtime, no special accommodation is made, and the AutoSize property is applied as specified by the property setting.


This technique solved my problem:

In parent form:

frmEmployee frm = new frmEmployee();
frm.MdiParent = this;
frm.Dock = DockStyle.Fill;
frm.Show();

In the child form (Load event):

this.WindowState = FormWindowState.Maximized;

I User this Code in my project, Useful for me.

    private void Form1_Resize(object sender, EventArgs e)
    {
        int w = MainPanel.Width; // you can use form.width when you don't use panels

        w = (w - 120)/4; // 120 because set 15px for each side of panels
                         // and put panels in FlowLayoutPanel
                         // 4 because i have 4 panel boxes
        panel1.Width = w;
        panel2.Width = w;
        panel3.Width = w;
        panel4.Width = w;
    }

enter image description here


You could calculate the required height of the TreeView, by figuring out the height of a node, multiplying it by the number of nodes, then setting the form's MinimumSize property accordingly.

// assuming the treeview is populated!
nodeHeight = treeview1.Nodes[0].Bounds.Height;

this.MaximumSize = new Size(someMaximumWidth, someMaximumHeight);

int requiredFormHeight = (treeView1.GetNodeCount(true) * nodeHeight);

this.MinimumSize = new Size(this.Width, requiredFormHeight);

NB. This assumes though that the treeview1 is the only control on the form. When setting the requiredFormHeight variable you'll need to allow for other controls and height requirements surrounding the treeview, such as the tabcontrol you mentioned.

(I would however agree with @jgauffin and assess the rationale behind the requirement to resize a form everytime it loads without the user's consent - maybe let the user position and size the form and remember that instead??)


I used this code and it works just fine

const int margin = 5;
        Rectangle rect = new Rectangle(
            Screen.PrimaryScreen.WorkingArea.X + margin,
            Screen.PrimaryScreen.WorkingArea.Y + margin,
            Screen.PrimaryScreen.WorkingArea.Width - 2 * margin,
            Screen.PrimaryScreen.WorkingArea.Height - 2 * (margin - 7));
        this.Bounds = rect;

If you trying to fit the content according to the forms than the following will help. It helps me while I was trying to fit the content on the form to fit when ever the forms were resized.

this.contents.Size = new Size(this.ClientRectangle.Width, this.ClientRectangle.Height);


This might be useful. It resizes a new form to a user control, and then anchors the user control to the new form:

Form f = new Form();
MyUserControl muc = new MyUserControl();
f.ClientSize = muc.Size;
f.Controls.Add(muc);
muc.Anchor = AnchorStyles.Top | AnchorStyles.Bottom | AnchorStyles.Left | AnchorStyles.Right;
f.ShowDialog();

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...
}

By using the various sizing properties (Dock, Anchor) or container controls (Panel, TableLayoutPanel, FlowLayoutPanel, etc.) you can only dictate the size from the outer control down to the inner controls. But there is nothing (working) within the .Net framework that allows to dictate the size of a container through the size of the child control. I also missed this a few times and tried the AutoSize property, but it never worked.

So all you can do is trying to get this stuff done manually, sorry.


Examples related to c#

How can I convert this one line of ActionScript to C#? Microsoft Advertising SDK doesn't deliverer ads How to use a global array in C#? How to correctly write async method? C# - insert values from file into two arrays Uploading into folder in FTP? Are these methods thread safe? dotnet ef not found in .NET Core 3 HTTP Error 500.30 - ANCM In-Process Start Failure Best way to "push" into C# array

Examples related to .net

You must add a reference to assembly 'netstandard, Version=2.0.0.0 How to use Bootstrap 4 in ASP.NET Core No authenticationScheme was specified, and there was no DefaultChallengeScheme found with default authentification and custom authorization .net Core 2.0 - Package was restored using .NetFramework 4.6.1 instead of target framework .netCore 2.0. The package may not be fully compatible Update .NET web service to use TLS 1.2 EF Core add-migration Build Failed What is the difference between .NET Core and .NET Standard Class Library project types? Visual Studio 2017 - Could not load file or assembly 'System.Runtime, Version=4.1.0.0' or one of its dependencies Nuget connection attempt failed "Unable to load the service index for source" Token based authentication in Web API without any user interface

Examples related to winforms

How to set combobox default value? Get the cell value of a GridView row Getting the first and last day of a month, using a given DateTime object Check if a record exists in the database Delete a row in DataGridView Control in VB.NET How to make picturebox transparent? Set default format of datetimepicker as dd-MM-yyyy Changing datagridview cell color based on condition C# Inserting Data from a form into an access Database How to use ConfigurationManager