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();
int num = 1; //聲明變量
for (int i = 0; i < 3; i++)
{
for (int j = 0; j < 3; j++)
{
Button btn = new Button(); //動態創新按鈕,創建實例
btn.Text = num.ToString(); //將num的值賦值給按鈕的text屬性,num自增
btn.Width = 24; //設置控件的長度
btn.Height = 20; //設置控件的寬度
btn.Top = i * 20 + 3; //設置控件距離容器頂部的位置
btn.Left = j * 24 + 5; //設置控件距離容器左邊的位置
Controls.Add(btn); //將控件顯示在容器中
btn.Click+=new EventHandler(btn_Click);
num++;
}
}
Label lab = new Label();
lab.Top = 68;
lab.Left = 29;
lab.Name = "LableTxt";
Controls.Add(lab);
}
private void btn_Click(object sender, EventArgs e)
{
Button b = (Button)sender;
Label newlable = (Label)Controls.Find("LableTxt", true)[0];
newlable.Text = "你單擊了" + b.Text + "號按鈕";
b.Text = "*";
}
}
}