我知道只需拖放按钮就很容易,但是讲师坚持以编程方式创建按钮。
在Form1_Load方法中,我应该编写什么代码来创建一个简单的按钮?
private void Form1_Load(object sender, System.EventArgs e)
{
}
那么在加载时按钮会显示?
答案 0 :(得分:1)
如你所说它是Winforms,你可以做以下......
首先创建一个新的Button
对象。
Button newButton = new Button();
然后使用以下命令将其添加到该函数内的表单中:
this.Controls.Add(newButton);
您可以设置的额外属性......
newButton.Text = "Created Button";
newButton.Location = new Point(70,70);
newButton.Size = new Size(50, 100);
您遇到的问题是您尝试在Form_Load事件上设置它,在该阶段该表单尚不存在且您的按钮被覆盖。您需要Shown
或Activated
个活动的代表才能显示该按钮。
例如,在Form1
构造函数中,
public Form1()
{
InitializeComponent();
this.Shown += CreateButtonDelegate;
}
您的实际代表是您创建按钮的位置并将其添加到表单中,这样的内容将起作用。
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);
}
答案 1 :(得分:1)
放置此代码
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);
}
答案 2 :(得分:-1)
很简单:
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";
}