简体   繁体   中英

Can I remove a label, richtextbox in c#? when a button is clicked?

I have a dynamically created Label , RichTextBox via a button that is constructed via array.

Label dateLabel = new Label();
dateLabel.Text = dateArray[i];
dateLabel.Name = "date" + i;
dateLabel.Location = new Point(154, 5 + (50 * i));
dateLabel.Tag = dateLabel;
dateLabel.Size = new System.Drawing.Size(91, 20);
panel1.Controls.Add(dateLabel);

RichTextBox placeTravelLabel = new RichTextBox();
placeTravelLabel.Text = placeTravelArray[i];
placeTravelLabel.Name = "placeTravel" + i;
placeTravelLabel.Location = new Point(272, 5 + (50 * i));
placeTravelLabel.Tag = placeTravelLabel;
placeTravelLabel.Size = new System.Drawing.Size(148, 45);
placeTravelLabel.ReadOnly = true;
panel1.Controls.Add(placeTravelLabel);

Button clearButton = new Button();
clearButton.Name = "clearButton" + i;
clearButton.Text = "Remove";
clearButton.Location = new Point(1200, 5 + (30 * i));
clearButton.Click += new EventHandler(this.clearButton_Click);
panel1.Controls.Add(clearButton);

Now I want them to be remove something like this.

public void clearButton_Click(object sender, EventArgs e)
{
   dateLabel.Remove();
   placeTravelLabel.Remove();
}

Is this possible?

Yes, it is. Try

panel1.Controls.Remove(dateLabel);
panel1.Controls.Remove(placeTravelLabel);

You obviously need to hold the references to them when you create them (ie declare them as fields in your class) or mark them somehow (eg in Tag property) and enumerate panel1.Controls to find them later.

I think it should also be possible to use closure on local instances by defining button's click event as lambda to avoid declaring those controls as fields. I do not recommend this, as typical flow is more readable and straightforward. Having said that:

Label dateLabel = new Label();
//...
panel1.Controls.Add(dateLabel);

RichTextBox placeTravelLabel = new RichTextBox();
//...
panel1.Controls.Add(placeTravelLabel);

Button clearButton = new Button();
//...
clearButton.Click += new EventHandler((s, e) => 
    {
        panel1.Controls.Remove(dateLabel);
        panel1.Controls.Remove(placeTravelLabel);
    });
panel1.Controls.Add(clearButton);

This is pseudo code built up with LinqPad but should give you enough to work with.

I assume that you are working WinForms as there is no tag to say if it is Winforms of WPF, but this is the code that you need that would remove the label for you.

var frm = new Form();

var lbl = new Label();
lbl.Name = "myLable"
frm.Controls.Add(lbl)

frm.Controls.Remove(lbl)

if you ignore the first two lines of the declarations, you simply need `FormName.Controls.Remove(LabelName)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM