C# Hide all labels/ controls

10,610

Solution 1

It sounds like you could just hide them all in the designer, and then you wouldn't have to deal with hiding them at runtime.

If you do have to hide them at runtime, then you can grab all controls on the Form of a certain type with a little LINQ:

foreach (var lbl in Controls.OfType<Label>())
    lbl.Hide();

You could even filter the controls based on their name, so you only hide the ones you want to hide:

foreach (var lbl in Controls.OfType<Label>().Where(x => x.Name != "lblAlwaysShow"))
    lbl.Hide();

If they're also tucked inside of other controls, like Panels or GroupBoxes, you'll have to iterate through their ControlCollections too:

foreach (var lbl in panel1.Controls.OfType<Label>())
    lbl.Hide();

foreach (var lbl in groupBox1.Controls.OfType<Label>())
    lbl.Hide();

Solution 2

try this:

 foreach(Label l in this.Controls.OfType<Label>())
 {
    l.Visible=false;
 }

 this.myControl.Visible=true;

Solution 3

You can try this too with less code. It works another form controls (etc. Textbox, Button...)

foreach (Control lbl in Controls)
{
 if ((lbl) is Label)
 {
  lbl.Hide();
 }
}
Share:
10,610
John
Author by

John

Updated on June 23, 2022

Comments

  • John
    John almost 2 years

    Is it possible within a windows form using C# to hide all specific controls upon form load, e.g. labels or buttons and then chose to show the ones that I wan't to be shown?

    I've got a program which contains a lot of buttons and labels but I only want one or two shown upon load and I feel doing this method of label1.Hide(); for every label seems inefficient but instead I could just show labels I want when I want. Maybe using a loop, something like this:

    foreach (Label)
    {
        this.Hide();
    }
    
  • John
    John almost 9 years
    Hiding the controls in the designer didn't occur to me at the time, however the first one did the trick as well, i'm going to try both to see what suits my program the best, thanks!