怎么動態生成控件?
單擊button1在panel上動態新建了多個label,現在想要點擊選擇某個動態新建的label,按button2,可以把這個label刪掉在button1_Click事件中,創建label,代碼:
Label lb1 = new Label(); lb1.Name = "panel"+j; lb1.BackColor = Color.Transparent; lb1.BorderStyle = BorderStyle.FixedSingle; Panel1.Controls.Add(lb1);
為這些label增加Click事件
Label lb1 = new Label(); lb1.Name = "panel"+j; lb1.BackColor = Color.Transparent; lb1.Click += new EventHandler(label_Click); lb1.BorderStyle = BorderStyle.FixedSingle;Panel1.Controls.Add(lb1);string name = "";private void label_Click(object sender, EventArgs e){ Label lbl = sender as Label; name = lbl.Name;}
然后在Button2的Click中:
private void button2_Click(object sender, EventArgs e){ Label lbl = Panel1.Controls[name]; if(lbl != null) Panel1.Controls.Remove(lbl);}