Click here to Skip to main content
14,362,769 members
Rate this:
Please Sign up or sign in to vote.
See more:
Array USStates is populated with the values as shown but if i want
to access this values within the array, how is it posssible.
Refrencing through USStates(1) dosent work.

USStates.Add(new USState("Alabama", "AL"));

<pre lang="cs">// Populate the list box using an array as DataSource.
           <b> ArrayList USStates = new ArrayList();</b>
           <b> USStates.Add(new USState(&quot;Alabama&quot;, &quot;AL&quot;))</b>;
            USStates.Add(new USState(&quot;Washington&quot;, &quot;WA&quot;));
            USStates.Add(new USState(&quot;West Virginia&quot;, &quot;WV&quot;));
            USStates.Add(new USState(&quot;Wisconsin&quot;, &quot;WI&quot;));
            USStates.Add(new USState(&quot;Wyoming&quot;, &quot;WY&quot;));
            ListBox1.DataSource = USStates;

            // Set the long name as the property to be displayed and the short
            // name as the value to be returned when a row is selected.  Here
            // these are properties; if we were binding to a database table or
            // query these could be column names.
            ListBox1.DisplayMember = &quot;LongName&quot;;
            ListBox1.ValueMember = &quot;ShortName&quot;;

public class USState
        private string myShortName;
        private string myLongName;

        public USState(string strLongName, string strShortName)

            this.myShortName = strShortName;
            this.myLongName = strLongName;

        public string ShortName
                return myShortName;

        public string LongName

                return myLongName;

Rate this:
Please Sign up or sign in to vote.

Solution 1

Please retrieve your data like below.You must cast the particular index value to UsState class.

ArrayList arrayList=new ArrayList();
            var usStateItem=new UsState("Us","Usa");
            UsState usState = (UsState)arrayList[0];

Hope this helps
Rate this:
Please Sign up or sign in to vote.

Solution 2

You may use the [] operator to access ArrayList items, e.g.
ArrayList al=new ArrayList();
Console.WriteLine("Item 1 is {0}", al[1]);
al[1] = "hoo";
Console.WriteLine("Now item 1 is {0}", al[1]);

Please consider using List<string></string> instead of the ArrayList.
Rate this:
Please Sign up or sign in to vote.

Solution 3

USState obj = (USState)USStates[0];
string longname= obj.LongName;
string shortname= obj.ShortName;

//if u create List instead of ArrayList

List<USState> USStates=new List<USState>();
string longname=USStates[0].LongName;
string shortname=USStates[0].ShortName;

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

CodeProject, 503-250 Ferrand Drive Toronto Ontario, M3C 3G8 Canada +1 416-849-8900 x 100