控件的动态生成与操作
事件的三要素:事件源,事件数据,事件处理程序
例如:
//sender-事件源,EventArgs-事件数据,函数体就是处理程序
private void button1_Click(object sender, EventArgs e)
{
Button btn = sender as Button; //把事件源具像化。
MessageBox.Show(btn.Text); //显示事件源的文本。
}
案例:动态生成一个按钮布局,并作出一个模拟抽奖的过程
private void Form4_Load(object sender, EventArgs e) { BuildLayout();//构建网格布局 AddButtonToTableLayout(); //向网格布局中加按钮 } private void AddButtonToTableLayout() { Random rand = new Random(); for (int i = 0; i < 400; i++) { //动态构建按钮 Button btn = new Button(); //初始化按钮的属性 btn.Text = i.ToString(); btn.Dock = DockStyle.Fill; tableLayoutPanel1.Controls.Add(btn); if (rand.Next(100) % 3 == 0) { btn.Tag = 1; } else if (rand.Next(100) % 5 == 0) { btn.Tag = 100; } else if (rand.Next(100) % 10 == 0) { btn.Tag = 500; } else { btn.Tag = 0; } //初始化按钮的事件 btn.Click += btn_Click; } } void btn_Click(object sender, EventArgs e) { Button btn = sender as Button; int n = (int)btn.Tag; if (n != 0) { btn.BackColor = Color.Red; btn.ForeColor = Color.Yellow; btn.Text = n.ToString(); btn.Font = new Font("黑体", 12, FontStyle.Bold); } btn.Enabled = false; } private void BuildLayout() { //清掉原来的两列 tableLayoutPanel1.ColumnStyles.Clear(); //添加20个新列 tableLayoutPanel1.ColumnCount = 20; for (int i = 0; i < 20; i++) { ColumnStyle style = new ColumnStyle(SizeType.Percent, 5); tableLayoutPanel1.ColumnStyles.Add(style); } //添掉原来的两行 tableLayoutPanel1.RowStyles.Clear(); //添加20个新行 tableLayoutPanel1.RowCount = 20; for (int i = 0; i < 20; i++) { RowStyle style = new RowStyle(SizeType.Percent, 5); tableLayoutPanel1.RowStyles.Add(style); } }