c#以编程方式创建后删除标签

c# Delete label after create programmatically

当我搜索数据库时,我使用下面的代码在 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); 

找到你的控件,然后:

if(label != null)
          label.Dispose();

您可以使用以下代码更轻松地删除标签:

this.Controls.Remove(label1);.

this 是当前形式。 Controls 是位于表单上的标签、按钮等。 Remove() 删除目标控件。