Reputation: 498
This is the problem: I add a lot of buttons, pictureboxes, textboxes and other controls like this:
btnStart = new Button();
bla bla bla text text text...
And I have been adding more. So, I have learned that I can remove them one by one:
Controls.Remove(btnStart);
But what I do want to know is, if there is a way to remove all of them at once, not specifying every single one of them when I want to remove them. Basically I want to create new:
private void ClrScr() { //Help??? }
Which will remove all controls once called from this form (Everything is done in one form). Can anyone help out? I'm still quite new at this.
Upvotes: 2
Views: 522
Reputation: 25799
Controls.Clear( )
should do it.
Edit:
As pointed out below - Controls.Clear( )
can result in memory leaks. Have a look at this answer: How to Clear() controls without causing a memory leak
Upvotes: 3
Reputation: 28091
If you want to remove all childcontrols of your mainform just use Controls.Clear()
If you have some fixed controls you do not want to remove, then add the dynamic generated controls to a Panel. Then you can call mypanel.Controls.Clear()
to only remove those controls.
EDIT: It seems like Controls.Clear causes memory leaks, so you might use this answer from Hans Passant.
Upvotes: 1