当我在数据库上搜索时,我使用下面的代码在panel1上创建多个新标签。如果我在数据库中删除一个名字,是否有机会删除标签?
public void labelLocate(string name, string labelLocate, int x, int y)
{
// name is the ID in the database
var label = this.Controls.OfType<Label>().FirstOrDefault(l => l.Name == name);
if (label != null) this.Controls.Remove(label);
Label labelstring = new Label();
labelstring.Width = 0;
labelstring.Text = name;
labelstring.Name = name;
labelstring.AutoSize = true;
this.Controls.Remove(labelstring);
this.Controls.Add(labelstring);
labelstring.BorderStyle = System.Windows.Forms.BorderStyle.FixedSingle;
labelstring.TextAlign = System.Drawing.ContentAlignment.MiddleCenter;
labelstring.BringToFront();
switch (labelLocate)
{
case "Up": labelstring.Location = new Point(x + (panel1.Location.X + 3), (y - 20) + (panel1.Location.Y + 3));
break;
case "Down": labelstring.Location = new Point(x + (panel1.Location.X + 3), (y) + 5 + (panel1.Location.Y + 3));
break;
case "Left": labelstring.Location = new Point(x - 5 - (labelstring.Width) + (panel1.Location.X + 3), y + 5 + (panel1.Location.Y + 3));
break;
case "Right": labelstring.Location = new Point(x + 10 + (panel1.Location.X + 3), y + 5 + (panel1.Location.Y + 3));
break;
}
}
答案 0 :(得分:2)
您可以使用ControlCollection.Remove
和LINQ:
var label = this.Controls.OfType<Label>().FirstOrDefault(l => l.Name == "TheID");
if(label != null)
this.Controls.Remove(label);
答案 1 :(得分:0)
找到你的控件,然后:
if(label != null)
label.Dispose();
答案 2 :(得分:0)
您可以使用以下代码更轻松地删除标签:
this.Controls.Remove(label1);
。
this
是当前形式。 Controls
是位于表单上的标签,按钮等。 Remove()
删除目标控件。