以下代码用于循环添加5个按钮,请解释这5个按钮怎么名称都是button2而不会报错,如果采用单独添加按钮,则需要修改button2不同名才可以,这是怎么回事情了?
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
int x = 20;int y = 20;
for(int i=0;i<=5;i++)
{
Button button2 = new Button();
button2.Location = new System.Drawing.Point(x, y);
button2.Size = new System.Drawing.Size(80, 40);
button2.Text = " ";
button2.Name = "button2";
button2.Click += new System.EventHandler(button2_Click);
Controls.Add(button2);
x = x + 100;
y = y + 0;
}
}
private void button2_Click(object sender, EventArgs e)
{
Button btn = (Button)sender;
btn.Text = "重写添加的按钮";
}
}