Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I create a button programmatically in C# window app?

In the Form1_Load method what code should I write to create a simple button?

 private void Form1_Load(object sender, System.EventArgs e)
 {

 }

So that on Load the button would show.

like image 228
Kurt Camilleri Avatar asked Jun 15 '26 18:06

Kurt Camilleri


1 Answers

As you said it is Winforms, you can do the following...

First create a new Button object.

Button newButton = new Button();

Then add it to the form inside that function using:

this.Controls.Add(newButton);

Extra properties you can set...

newButton.Text = "Created Button";
newButton.Location = new Point(70, 70);
newButton.Size = new Size(50, 100);

Your issue you're running to is that you're trying to set it on Form_Load event, at that stage the form does not exist yet and your buttons are overwritten. You need a delegate for the Shown or Activated events in order to show the button.

For example inside your Form1 constructor,

public Form1()
{
    InitializeComponent();
    this.Shown += CreateButtonDelegate;
}

Your actual delegate is where you create your button and add it to the form, something like this will work.

private void CreateButtonDelegate(object sender, EventArgs e)
{
    Button newButton = new Button();
    this.Controls.Add(newButton);
    newButton.Text = "Created Button";
    newButton.Location = new Point(70, 70);
    newButton.Size = new Size(50, 100);
}
like image 71
Adrian Avatar answered Jun 17 '26 07:06

Adrian



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!