Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to create a class that clears the screen of buttons and other controls?

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);
        }

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading