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

倖福魔咒の 提交于 2021-02-08 12:01:19

问题


I know that it easy to just drag and drop a button, however a lecturer insists on creating buttons programmatically.

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?


回答1:


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);
    newButton.Location = new Point(20, 50);
}



回答2:


on your eventload form put this code

 private void Form1_Load(object sender, EventArgs e)
    {
        Button testbutton = new Button();
        testbutton.Text = "button1";
        testbutton.Location = new Point(70, 70);
        testbutton.Size = new Size(100, 100);
        testbutton.Visible = true;
        testbutton.BringToFront();
        this.Controls.Add(testbutton);

    }



回答3:


It's simple :

private void Form1_Load(object sender, System.EventArgs e)
 {
     Button btn1 = new Button();
     this.Controls.add(btn1);
     btn1.Top=100;
     btn1.Left=100;
     btn1.Text="My Button";

 }


来源:https://stackoverflow.com/questions/47732560/how-can-i-create-a-button-programmatically-in-c-sharp-window-app

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!