Home > Net >  how to create a button that creates another button and show up immediately
how to create a button that creates another button and show up immediately

Time:11-02

I want to create a button that Creates other buttons and I want it to be able to create like infinite buttons on the screen I tried

Button button = new Button();
button.Location = new Point(100,100);
button.Text = "IT Woreked";
button.Size = new Size(26,26);
button.Visible = true;
Application.Restart();
this.Controls.Add(button);

and I believe it really adds it but it's not shown up so how do I add the button to the screen

CodePudding user response:

I think that is because you are putting all the new buttons in the same location. Also, remove the Application.Restart() part.

Button button = new Button();
button.Location = new Point(100,100); //change this to random or something 
button.Text = "IT Woreked";
button.Size = new Size(26,26);
button.Visible = true;
Application.Restart();//don't restart the application everytime you click!
this.Controls.Add(button);

You should also subscribe to the new buttons' OnClick event. You should create a local function that contains all the above code and subscribe to the new buttons. This way you can add buttons recursively. Say if the original button's name is button1, change its click method to something like this:

private void button1_Click(object sender, EventArgs e)
{
    Random random = new Random(System.Environment.TickCount);//random location everytime
    Button button = new Button();
    button.Text = "IT Woreked";
    button.Size = new Size(26, 26);// the size might be a bit small. You might want to increase it.
    button.Location = new Point(random.Next(0, this.Size.Width - button.Width), random.Next(0, this.Size.Height - button.Height)); //change this to random or something 
    button.Visible = true;
    this.Controls.Add(button);
    button.Click  = button1_Click;//when the new button is clicked, call this method.
}
  • Related