Sign in to follow this  
mcaccountman

redundant code problems c#

Recommended Posts

mcaccountman    98

Hello, Im trying to find an easier way for making a decent amount of things visible / not visible. Preferrably an array that contains the names of said things but im not sure. This is what the redundant code is -- 

 

 button1.Visible = false;
                    button2.Visible = false;
                    button3.Visible = false;
                    button4.Visible = false;
                    pictureBox1.Visible = false;
                    pictureBox2.Visible = false;
                    pictureBox3.Visible = false;
                    pictureBox4.Visible = false;
 
-- just trying to find a more efficient way than to copy and paste it over and over again and change the name. thanks!

Share this post


Link to post
Share on other sites
Krypt0n    4721

can't you put all elements into an array?

you could still index individual ones with an enum if you want name e.g

if( UI[Element_Button1].Visible )....

 

but you could access all of them in a loop

..reset()

{

  for(int a=0;a<UI.length;a++)

    UI[a].Visible=false;

}

Share this post


Link to post
Share on other sites
ericrrichards22    2434
var controls = new Control[]{button1, button2, /* and so on...*/};
foreach(var control in controls){
    control.Visible=false;
}

That's probably the simplest, most concise way that you can do it.

 

Edit: forgot a var in the foreach.

Edited by ericrrichards22

Share this post


Link to post
Share on other sites
WoopsASword    963

Working in WPF or WFA, your window or parent control have children (differes for WPF, because it splits into visual and controls).

I guess this is simple WFA , therefore all you need is to get the controls from your window. 

Furthermore, you should create a groupbox to hold all your elements and then just call Visble=false on the groupbox. 

Share this post


Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

Sign in to follow this