How to add buttons dynamically to my form?

前端 未结 8 1894
盖世英雄少女心
盖世英雄少女心 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:06

    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.

提交回复
热议问题