Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# Hide all labels/ controls

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();
}
like image 701
John Avatar asked Sep 20 '25 09:09

John


2 Answers

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();
like image 56
Grant Winney Avatar answered Sep 22 '25 04:09

Grant Winney


try this:

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

 this.myControl.Visible=true;
like image 35
Ormoz Avatar answered Sep 22 '25 03:09

Ormoz