I am reusing the same code for clearing the screen many times in my program, and I thought about turning it into a class, but I still don't get how classes work and how to properly make one.
My code to clear buttons and other controls is as follows:
List<RichTextBox> _richTextBoxes = this.Controls.OfType<RichTextBox>().ToList();
List<Button> _buttons = this.Controls.OfType<Button>().ToList();
List<Label> _labels = this.Controls.OfType<Label>().ToList();
List<TextBox> _textBoxes = this.Controls.OfType<TextBox>().ToList();
foreach (var rich in _richTextBoxes)
{
this.Controls.Remove(rich);
}
foreach (var button in _buttons)
{
this.Controls.Remove(button);
}
foreach (var label in _labels)
{
this.Controls.Remove(label);
}
foreach (var textBox in _textBoxes)
{
this.Controls.Remove(textBox);
}
CodePudding user response:
As others already mentioned, it's a rare practice to remove/create all controls of a container (Form, Panel, etc) at runtime, and a possible waste of PC resources.
Of course you can use:
Form.Controls.Clear();
Or
Panel.Controls.Clear();
But, what's wrong with placing all your controls in a Panel
, for example, and simply hiding said panel? seen you get the same result in a more efficient way
If you opt for this, it's as simple as this line:
Panel.Visible = false; // or true
CodePudding user response:
I am reusing the same code for clearing the screen many times in my program
The bigger question is why you want to do that?
Though a legitimate programming scenario, given that "but I still don't get how classes work
" , it is unlikely you are at the dynamic-UI-apps stage based on say dynamic selection of a database table.
Consider creating multiple forms via the Designer and don't modify them at runtime. That's alot easier if dynamic UIs isn't really a requirement.
An easier way to change things at runtime
Otherwise if you are super keen to continue with changing things at runtime, consider placing all the controls in a child Panel belonging to the form.
Then you can just call Clear():
myPanel.Controls.Clear(); // Job done