Windows Phone Developers

Wednesday, April 21, 2010

How to assign an ArrayList to ListBox in .NET (C#)

How to add ArrayList items to ListBox (VB.NET/C#) / How to Add Objects to ListBox using C# (.NET)

Let us consider an userform with a listbox. We now need to assign the Arraylist to the Listbox.

We go back to our Teamexample. We have a class called ClassTeam with following properties


     class ClassTeam
    {
        #region declarations
        public enum playerType { ClassA, ClassB, ClassC, Contract }
        private playerType _PlayerType;
        string _Name;
        int _Age;
        string _Phone;


        #endregion

        #region properties
        public playerType PlayerType
        {
            //accessor
            get { return _PlayerType; }

            //mutator
            set
            {
                _PlayerType = value;
            }

        }

        public string Name
        {
            get { return _Name; }

            set
            {
                _Name = value;
            }
        }

        public string Phone
        {
            get { return _Phone; }

            set
            {
                _Phone = value;
            }
        }

        public int Age
        {
            get { return _Age; }

            set
            {
                _Age = value;
            }
        }
        #endregion

        #region public methods
        public string SetPlayer()
        {

            return null;
        }
        #endregion

        #region ClassTeam Construct
        public ClassTeam(playerType PT, string sName, int iAge, string sPhone )
        {
            PlayerType = PT;
            _Name= sName;
            _Age = iAge;
            _Phone = sPhone;
        }

    #endregion

    }




Now we create objects of the above class and add it to an Arraylist


            ArrayList Team = new ArrayList();
            ClassTeam CT = new ClassTeam(ClassTeam.playerType.Contract, "Sachin", 23, "33420242");
            Team.Add(CT);
            CT = new ClassTeam(ClassTeam.playerType.Contract, "Sourav", 23, "33420242");
            Team.Add(CT);
            CT = new ClassTeam(ClassTeam.playerType.Contract, "Dravid", 23, "33420242");

            Team.Add(CT);
 

The arraylist 'Team' will nowcontain three ClassTeam objects.

Assign the ArrayList as datasource to the listbox and set the displaymember and valuemember



            listBox1.DataSource = Team;
            listBox1.DisplayMember = "Name";
            listBox1.ValueMember = "Phone";


Some methods of ListBox will not be available when use DataSource. Digg Technorati Delicious StumbleUpon Reddit BlinkList Furl Mixx Facebook Google Bookmark Yahoo
ma.gnolia squidoo newsvine live netscape tailrank mister-wong blogmarks slashdot spurl StumbleUpon

No comments:

Post a Comment