Button[] buttons = new Button[10];
private void Form2_Load(object sender, EventArgs e)
{
for(int i = 0; i < buttons.Length; i++)
{
buttons[i] = new Button();
buttons[i].Text = (i+1).ToString();
buttons[i].Location = new Point(i * 30+90, 16);
buttons[i].Size = new Size(30, 30);
buttons[i].Parent = this;
buttons[i].Click += new System.EventHandler(this.buttons_Click);
this.Controls.Add(buttons[i]);
}
}
private void buttons_Click(object sender, EventArgs e)
{
Button button = (Button)sender;
MessageBox.Show(button.Text);
}
我这里是动态添加了10个按钮并给每个按钮的Text属性赋值为其编号。