Search code examples
c#winformscheckboxdynamic-controls

Create checkboxes at runtime and fit them on form on the best possible way


I need to create N checkboxes on Winform but then I need to fit them inside of a form the best possible way depending on the form size.

Here is the code

  int x = 0;

  foreach (int i in Enumerable.Range(0, 5))
  {
      foreach (int j in Enumerable.Range(0, 4))
      {                   
          CheckBox b = new CheckBox();
          b.Appearance = Appearance.Button;
          b.Size = new System.Drawing.Size(80, 30);
          b.Location = new Point(i * 80, j * 30);
          b.Text = x.ToString();
          b.CheckedChanged += B_CheckedChanged;
          b.Tag = x.ToString("#00");

          this.Controls.Add(b);

          x++;
      }
   }

This piece of code creates 20 checkboxes in 5 columns and 4 rows, but I need now when user enters 34 to somehow find the best way to show those checkboxes. Let's say in maybe in 5 rows and and each row contain 8 checkboxes except the last which will contain last 2 checkboxes. What is the best approach to accomplish that?


Solution

  • You can use put all the chekbox in flowLayoutPanel control, Set flowlayoutpanel control Anchor so the flowlayoutpanel can auto change size when form size changed.