Gio Borje
Gio Borje

Reputation: 21134

.NET Referencing similar controls

I have multiple toolstrip controls in my application and was looking for a way to hide them all at once.

E.g.

allToolStrips.Visible = false;

instead of

toolstrip1.Visible = false;
toolstrip2.Visible = false;
...
toolstripn.Visible = false;

I'm using C# if it matters.

Upvotes: 1

Views: 133

Answers (4)

AaronLS
AaronLS

Reputation: 38392

In addition to other's answers, consider coding it so that same code can also be used to flip the controls back to visible again if you are toggling them, so that you don't have the code duplicated:

void SetMenusVisibility(bool visible)
{
    //credit to Vivek for his loop
    foreach(Control ctrl in this.Controls)
    {           
             if(ctrl.GetType() ==typeof(ToolStrip))

             ctrl.Visible=visible;    

    }
}

Upvotes: 0

Vivek Bernard
Vivek Bernard

Reputation: 2073

easy one

foreach(Control ctrl in this.Controls)
{           
         if(ctrl.GetType() ==typeof(ToolStrip))

         ctrl.Visible=false;    

}

Upvotes: 5

Klaus Byskov Pedersen
Klaus Byskov Pedersen

Reputation: 121057

You can do it using linq. Something like this.

this.Controls.Select(c => c is ToolStrip).ToList().ForEach(ts => ts.Visible = false);

I haven't checked the syntax, but I think it's ok.

Upvotes: 1

RvdK
RvdK

Reputation: 19800

Put them in a vector and then hide them in a for each loop?

Upvotes: 2

Related Questions