HOW TO DO THIS IN C#?

Pravesh Singh

Total Post:412

Points:2888
Posted by  Pravesh Singh
C# 
 922  View(s)
Ratings:
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

  }

  1. Tanuj Kumar

    Post:134

    Points:940
    Re: How to do this in c#?

    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;

    }

  1. Ankit Singh

    Post:341

    Points:2389
    Re: How to do this in c#?

    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;

Answer

NEWSLETTER

Enter your email address here always to be updated. We promise not to spam!