JefferyLR
JefferyLR

Reputation: 401

c# Delete label after create programmatically

I use the code below to create multiple new label on panel1 when i search on database. Any chance to remove the label if i delete one name on my database?

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;
    }
}

Upvotes: 0

Views: 8732

Answers (3)

You can remove a label more easily using this code:

this.Controls.Remove(label1);.

this is a current form. Controls is a labels, buttons, etc. located on form. Remove() removes the target control.

Upvotes: 0

user4419908
user4419908

Reputation:

Find your cotrol and then:

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

Upvotes: 0

Tim Schmelter
Tim Schmelter

Reputation: 460238

You can use ControlCollection.Remove and LINQ:

var label = this.Controls.OfType<Label>().FirstOrDefault(l => l.Name == "TheID");
if(label != null)
    this.Controls.Remove(label); 

Upvotes: 2

Related Questions