[c#] How to add buttons dynamically to my form?

I want to create 10 buttons on my form when I click on button1. No error with this code below but it doesnt work either.

private void button1_Click(object sender, EventArgs e)
{
    List<Button> buttons = new List<Button>();
    for (int i = 0; i < buttons.Capacity; i++)
    {
        this.Controls.Add(buttons[i]);   
    }
}

This question is related to c# winforms button dynamic

The answer is


You could do something like this:

Point newLoc = new Point(5,5); // Set whatever you want for initial location
for(int i=0; i < 10; ++i)
{
    Button b = new Button();
    b.Size = new Size(10, 50);
    b.Location = newLoc;
    newLoc.Offset(0, b.Height + 5);
    Controls.Add(b);
}

If you want them to layout in any sort of reasonable fashion it would be better to add them to one of the layout panels (i.e. FlowLayoutPanel) or to align them yourself.


You can't add a Button to an empty list without creating a new instance of that Button. You are missing the

Button newButton = new Button();  

in your code plus get rid of the .Capacity


First, you aren't actually creating 10 buttons. Second, you need to set the location of each button, or they will appear on top of each other. This will do the trick:

  for (int i = 0; i < 10; ++i)
  {
      var button = new Button();
      button.Location = new Point(button.Width * i + 4, 0);
      Controls.Add(button);
  }

use button array like this.it will create 3 dynamic buttons bcoz h variable has value of 3

private void button1_Click(object sender, EventArgs e)
{
int h =3;


Button[] buttonArray = new Button[8];

for (int i = 0; i <= h-1; i++)
{
   buttonArray[i] = new Button();
   buttonArray[i].Size = new Size(20, 43);
   buttonArray[i].Name= ""+i+"";
   buttonArray[i].Click += button_Click;//function
   buttonArray[i].Location = new Point(40, 20 + (i * 20));
    panel1.Controls.Add(buttonArray[i]);

}  }

I had the same doubt and came up with the following contribution:

 int height = this.Size.Height;
 int width = this.Size.Width;

 int widthOffset = 10;
 int heightOffset = 10;

 int btnWidth = 100;  // Button Widht
 int btnHeight = 40;  // Button Height

 for (int i = 0; i < 50; ++i)
 {
     if ((widthOffset + btnWidth) >= width)
     {                    
         widthOffset = 10;
         heightOffset = heightOffset + btnHeight

         var button = new Button();
         button.Size = new Size(btnWidth, btnHeight);
         button.Name = "" + i + "";
         button.Text = "" + i + "";
         //button.Click += button_Click; // Button Click Event
         button.Location = new Point(widthOffset, heightOffset);

         Controls.Add(button);

         widthOffset = widthOffset + (btnWidth);
     }

     else
     {                        
         var button = new Button();
         button.Size = new Size(btnWidth, btnHeight);
         button.Name = "" + i + "";
         button.Text = "" + i + "";
         //button.Click += button_Click; // Button Click Event
         button.Location = new Point(widthOffset, heightOffset);

         Controls.Add(button);

         widthOffset = widthOffset + (btnWidth);
      }
  }

Expected Behaviour:
This will generate the buttons dinamically and using the current window size, "break a line" when the button exceeds the right margin of your window.


You aren't creating any buttons, you just have an empty list.

You can forget the list and just create the buttons in the loop.

private void button1_Click(object sender, EventArgs e) 
{     
     int top = 50;
     int left = 100;

     for (int i = 0; i < 10; i++)     
     {         
          Button button = new Button();   
          button.Left = left;
          button.Top = top;
          this.Controls.Add(button);      
          top += button.Height + 2;
     }
} 

Two problems- List is empty. You need to add some buttons to the list first. Second problem: You can't add buttons to "this". "This" is not referencing what you think, I think. Change this to reference a Panel for instance.

//Assume you have on your .aspx page:
<asp:Panel ID="Panel_Controls" runat="server"></asp:Panel>


private void button1_Click(object sender, EventArgs e)
    {
        List<Button> buttons = new List<Button>();


        for (int i = 0; i < buttons.Capacity; i++)
        {
            Panel_Controls.Controls.Add(buttons[i]);   
        }
    }

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

Examples related to button

How do I disable a Button in Flutter? Enable/disable buttons with Angular Disable Button in Angular 2 Wrapping a react-router Link in an html button CSS change button style after click Circle button css How to put a link on a button with bootstrap? What is the hamburger menu icon called and the three vertical dots icon called? React onClick function fires on render Run php function on button click

Examples related to dynamic

Please help me convert this script to a simple image slider Declare an empty two-dimensional array in Javascript? Compiling dynamic HTML strings from database Changing datagridview cell color dynamically What is the difference between dynamic programming and greedy approach? Dynamic variable names in Bash Dynamically Add C# Properties at Runtime How to generate a HTML page dynamically using PHP? Change UITableView height dynamically How to create own dynamic type or dynamic object in C#?