greg dorian
greg dorian

Reputation: 134

Remove all textbox from Panel control with Lambda Expression

I´m trying to remove textbox controls from a panel in a event Button click:

private void button2_Click(object sender, EventArgs e)
{
   panel1.Controls.OfType<TextBox>().ToList().Clear();
}

but it doesn´t work

Upvotes: 1

Views: 1631

Answers (2)

Justin Niessner
Justin Niessner

Reputation: 245479

If you want to remove the controls from the form rather than simply clear their contents (or removing them from a list that you just created), you need to remove them from the Panel. You can still accomplish this via a one-liner though:

panel1.Controls
      .OfType<TextBox>()
      .ToList()
      .ForEach(t => panel1.Controls.Remove(t));

Upvotes: 2

driis
driis

Reputation: 164341

The reason why your approach is not working, is that you are creating a new List, not connected to the panel (your ToList call), then clearing that list, effectively doing nothing.

You need to remove each item on the Controls collection directly:

 var textBoxes = panel1.Controls.OfType<TextBox>().ToList();
 foreach(var box in textBoxes)
     panel1.Controls.Remove(box);

Upvotes: 4

Related Questions