Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to add buttons dynamically to my form?

Tags:

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]);   
    }
}
like image 386
kmetin Avatar asked Dec 22 '11 18:12

kmetin


People also ask

How do you create a dynamic button?

This example demonstrates how do I add a button dynamically in android. Step 1 − Create a new project in Android Studio, go to File ⇒ New Project and fill all required details to create a new project. Step 2 − Add the following code to res/layout/activity_main. xml.

How do I create a dynamic button in HTML?

In vanilla JavaScript, you can use the document. createElement() method to programmatically create an HTML button element and set its required attributes. Then to append the button to a container, you can use the Node. appendChild() method.

What are dynamic buttons?

Dynamic buttons are a special type of button in Opus toolbars that behave differently in and out of Customize mode. In Customize mode they appear like any other button, and can be edited as normal - but in normal operation, the button itself disappears and is replaced by a dynamic list of items.


2 Answers

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;
     }
} 
like image 84
Igby Largeman Avatar answered Oct 02 '22 03:10

Igby Largeman


It doesn't work because the list is empty. Try this:

private void button1_Click(object sender, EventArgs e)
{
    List<Button> buttons = new List<Button>();
    for (int i = 0; i < 10; i++)
    {
        Button newButton = new Button();
        buttons.Add(newButton);
        this.Controls.Add(newButton);   
    }
}
like image 21
alf Avatar answered Oct 02 '22 01:10

alf