Home > DeveloperSection > Forums > How to do this in c#?
Pravesh Singh

Total Post:411

Points:2881
Posted on    December-09-2014 11:43 PM

 .NET C# 
Ratings:


 2 Reply(s)
 663  View(s)
Rate this:

I have a List of MyClass and in the main page I have 10 controls which will display the information about that list of Items. What I want is to check the count of the items in the List and then make the excess controls invisible. Now I'm using this code but is there an easier way of doing this?

 

 if (myList.Count > 0)

 {

      Control1.MyClassInfo = myList[0];

      if (myList.Count > 1)

      {

           Control2.MyClassInfo = myList[1];

           if (myList.Count > 2)

           {

                // and like that till 10

           }

           else

           {

                Control3.Visible = false;

                Control4.Visible = false;

                // till 10

           }

       }

       else

       {

           Control2.Visible = false;

           Control3.Visible = false;

           // till 10

       }

  }

  else

  {

       Control1.Visible = false;

       Control2.Visible = false;

       Control3.Visible = false;

       // and then till 10

  }



Tanuj Kumar

Total Post:134

Points:940
Posted on    December-10-2014 5:43 AM

Well, just add your controls in a list (ordered).

Something like that

var controlList = new List<Control>{ Control1, Control2, Control3 /*etc*/};

var count = myList.Count;

for (var i = 0; i < controlList.Count; i++) {

  controlList[i].Visible = count > i;

}


Ankit Singh

Total Post:341

Points:2389
Posted on    December-10-2014 6:41 AM

You could create a list of your controls

List<Control> MyControls = new List<Control>{Control1, Control2,..,Control10};

and then

foreach(var C in MyControls)

    C.Visible=false;

for(int i=0; i<myList.Count; i++)

    C[i].Visible=true;


Don't want to miss updates? Please click the below button!

Follow MindStick