Search code examples
c#winformsvisual-studiobuttonprogrammatically-created

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.


Solution

  • 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);
    }