clear a column of a TableLayoutPanel without loops?

220 views Asked by At

I have a TableLayoutPanel with two columns. I want to dynamically remove all controls from the second one. Is there a simple way? I really don't want tedious looping and things like that.

Edit: By "looping" I mean actually writing for-loops. LINQ solutions that loop behind the scenes are perfectly fine.

1

There are 1 answers

2
Mong Zhu On BEST ANSWER

It depends strongly on what you mean by: "clear a column". I chose to set the visibility to false for this example.

This looks really like a horrible hack:

// grab all controls from Colum 2 (index == 1)
List<Control> Col_2_Stuff = tableLayoutPanel1.Controls.OfType<Control>()
             .Where(x => tableLayoutPanel1.GetPositionFromControl(x).Column == 1).ToList();

// make them invisible
Col_2_Stuff.Select(c => { c.Visible = false; c = null; return c; }).ToList();

but it does the job

EDIT:

here is the line that actually removes them:

Col_2_Stuff.Select(c => { tableLayoutPanel1.Controls.Remove(c); return c; }).ToList();

inspired by @LarsTech: you can also call dispose and clear the list afterwards

Col_2_Stuff.Select(c => { tableLayoutPanel1.Controls.Remove(c); c.Dispose(); return c; }).ToList();

Col_2_Stuff.Clear();