[英]How can I create a button programmatically in C# window app?
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?在 Form1_Load 方法中,我应该编写什么代码来创建一个简单的按钮?
private void Form1_Load(object sender, System.EventArgs e)
{
}
So that on Load the button would show?所以在加载按钮会显示?
As you said it is Winforms, you can do the following...正如您所说的是Winforms,您可以执行以下操作...
First create a new Button
object.首先创建一个新的
Button
对象。
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.您遇到的问题是您试图在 Form_Load 事件上设置它,在那个阶段表单还不存在并且您的按钮被覆盖。 You need a delegate for the
Shown
or Activated
events in order to show the button.您需要
Shown
或Activated
事件的委托才能显示按钮。
For example inside your Form1
constructor,例如在你的
Form1
构造函数中,
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);
}
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);
}
I couldnt manage to create a button.我无法创建一个按钮。 When i write the part of;
当我写的部分;
this.Controls.Add(testbutton); this.Controls.Add(testbutton);
i couldnt find the "Controls" part .我找不到“控制”部分。 it has red line under it.
它下面有红线。 Do you know how to fix it?
你知道如何解决吗?
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";
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.