在c#中如何删除动态生成的控件?? 10
Label label1, label2;
foreach (string key in gm.Game.CurrentLevel.Monsters.Keys)
{
UIContainer monsterContainer = new UIContainer();
pic = new PictureBox();
//背景色为透明
pic.BackColor = Color.Transparent;
pic.SizeMode = PictureBoxSizeMode.AutoSize;
//初始位置是怪物对象的初始位置
pic.Location = gm.Game.CurrentLevel.Monsters[key].OriginalLocation;
//怪物图片
pic.Image = gm.Game.CurrentLevel.Monsters[key].Image;
//右键指定
pic.ContextMenuStrip = this.cmsAttack;
//保存怪物key
pic.Tag = key;
//描绘到窗体
this.Controls.Add(pic);
//保存一个容器对象
monsterContainer.Pic = pic;
label1 = new Label();
//显示原始生命值长度
label1.Size = new Size(gm.Game.CurrentLevel.Monsters[key].OriginalBlood, 20);
label1.AutoSize = false;
label1.BackColor = Color.Red;
label1.BorderStyle = BorderStyle.FixedSingle;
//位置在PictureBox上方
label1.Location = new Point(
gm.Game.CurrentLevel.Monsters[key].OriginalLocation.X,
gm.Game.CurrentLevel.Monsters[key].OriginalLocation.Y - 25
);
this.Controls.Add(label1);
monsterContainer.LabelBlood = label1;
label2 = new Label();
//显示当前生命值
label2.Size = new Size(gm.Game.CurrentLevel.Monsters[key].CurrentBlood, 20);
label2.AutoSize = false;
label2.BackColor = Color.Yellow;
label2.BorderStyle = BorderStyle.FixedSingle;
label2.Location = new Point(
gm.Game.CurrentLevel.Monsters[key].OriginalLocation.X,
gm.Game.CurrentLevel.Monsters[key].OriginalLocation.Y - 25);
this.Controls.Add(label2);
monsterContainer.LabelHurt = label2;
//放在最顶层
label2.BringToFront();
UIMappings.Add(key, monsterContainer);
} 展开
我打个比方他在form1的panel1里面,我不知道他叫什么名字,但是知道他上面显示的是“加载”,现在我要移除他:
foreach(control ctl in this.panel1.controls) //遍历panel1中所有控件
{
if(ctl is button)//挑选出是按钮类型的
{
if(ctl.text=="加载") //挑选出上面显示是“加载”的按钮
{
this.panel1.controls.remove(ctl); //移除他
}
}
}
删除的时候这么写
foreach(Control i in ctrls)
{
this.Control.Remove(i);
i.Dispose();
}
单击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);
}