c# 以编程方式创建后删除标签
本文关键字:删除 标签 创建 方式 编程 | 更新日期: 2023-09-27 18:37:21
当我在数据库上搜索时,我使用以下代码在 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;
}
}
您可以使用ControlCollection.Remove
和LINQ:
var label = this.Controls.OfType<Label>().FirstOrDefault(l => l.Name == "TheID");
if(label != null)
this.Controls.Remove(label);
找到你的cotrol,然后:
if(label != null)
label.Dispose();
您可以使用以下代码更轻松地删除标签:
this.Controls.Remove(label1);
.
this
是当前的形式。 Controls
是位于表单上的标签、按钮等。 Remove()
删除目标控件。