Sam
Sam

Reputation: 303

How to re-size a form to contain its controls in C#?

screenshot

I am new to C# and I am using windows forms.

As shown in screenshot I have Form1 which has flowLayoutPanel1 and ButtonCancel.

When Form1 loads, number of buttons are added into the flowLayoutPanel1 (the number of buttons is changing and it is not fixed).

 private void Form1_Load(object sender, EventArgs e)
    {
        for (int i = 0; i <= 1; i++)
            {

            Button btn = new Button();
            btn.Name = i.ToString();  
            btn.Width = 104;
            btn.Height = 63;
            btn.FlatStyle = FlatStyle.Popup;              
            flowLayoutPanel1.Controls.Add(btn);

            }
 }

Problem:

The problem is that there is a gap that I want to remove, to do that I have to reduce Form1 Height according to the number of the added buttons but I do not know how to resize Form1 Height based on the number of added buttons.

For example, if 2 buttons are added I want Form1 to shrink to fit the 2 buttons and if 8 buttons are added I want Form1 to expand to fit the 8 buttons without leaving gap.

Is there any Form property allows Form1 to expand and shrink according to the number of added buttons?

Thank you

Upvotes: 1

Views: 116

Answers (2)

MatSnow
MatSnow

Reputation: 7537

The following should work

  • Put a TableLayoutPanel with one column and two rows on the Form
  • Set the Dock-property of the TableLayoutPanel to Fill
  • Set the Size-Type of the first row of the TableLayoutPanel to Percent -> 100%
  • Set the Size-Type of the second row of the TableLayoutPanel to Absolute -> 63 Pixel
  • Put the FlowLayoutPanel inside the first row
  • Put the Cancel-Button inside the second row
  • Set the AutoSize-property of Form, TableLayoutPanel and FlowLayoutPanel to True
  • Set the AutoSizeMode-property of Form, TableLayoutPanel and FlowLayoutPanel to GrowAndShrink

Upvotes: 1

pilot13
pilot13

Reputation: 36

If you enable docking then it will resize automatically

Upvotes: 1

Related Questions