How to add buttons dynamically to my form?

前端 未结 8 1854
盖世英雄少女心
盖世英雄少女心 2020-12-01 12:34

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 se         


        
相关标签:
8条回答
  • 2020-12-01 13:15

    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]);
    
    }  }
    
    0 讨论(0)
  • 2020-12-01 13:18

    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);   
        }
    }
    
    0 讨论(0)
提交回复
热议问题