按C#入门经典上的代码输入的为什么不能编译

来源:百度知道 编辑:UC知道 时间:2024/06/17 17:36:50
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;

namespace WindowsApplication1
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}

private void button1_Click(object sender, System.EventArgs e)
{
((button)sender).Text = "Click!";
Button newButton = new Button();
newButton.Text = "New Button!";
newButton.Click += new EventHandler(newButton_Click);
Controls.Add(newButton);
}

private void newButton_Click(object sender, System.EventArgs e)
{
((Button)sender).Text = "Clicked!!";
}
}
}

代码是照书

因为你没有为新添加的button添加Click事件。下面这段代码是正确的:

namespace 动态添加控件
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}

private void button1_Click(object sender, EventArgs e)
{
Button newbutton = new Button();
newbutton.Text = "动态添加控件";
//为newbutton添加Click事件
newbutton.Click+=new EventHandler(newbutton_Click);
this.Controls.Add(newbutton);
}
private void newbutton_Click(object sender, EventArgs e)
{
MessageBox.Show("测试");
}
}
}

怎么会没变呢?按钮默认显示在左上角的 可能重叠在一起

private void button1_Click(object sender, System.EventArgs e)
{
((button)sender).Text = "Click!"; // button 改成 Button
Button newButton = new Button();
newButton.Text