Thursday, April 3, 2008

An ArrayList, at first glance might be kind of hard to get your head around,
if you're a beginner programmer, or coming from the Classic ASP/HTML world. But,
at its base, it's just a list of items in memory, and can be treated as an
object, but it's not a control, like a ListBox. It has properties and methods,
and the count of the items is Zero-based. For instance, let's say we have an
arraylist consisting of 5 colors (Blue, Red, Green, Orange and Pink). Since
ArrayLists are Zero-based, the numbering of the items starts with zero and ends
with 4.


To create an ArrayList, first, we must dimension it:

 



Dim
MyArrayList as ArrayList



Then, to create a space for it in memory:




MyArrayList
=New Arraylist



Next, we must populate the ArrayList. This can be done any one of many ways.
It can be done manually:



MyArrayList.add("Blue") 
MyArrayList.add("Red")
MyArrayList.add("Green")


or, we can populate it from a database table, using a DataReader, like so:



While objDR.Read()
MyArrayList.add(objDR("FieldName"))
End While


Once it's populated, then, we can 'hook it up' with a server control, like a
ListBox or DropDownList:




DropDownList.datasource
=MyArrayList
DropDownList.databind



There are many properties and methods, and I won't even begin to go into them
all since this, like the title says, is the 'Beginner's ArrayList',
but if you go to the Quickstart Tutorials, you will find a very
useful tool near the bottom of the TOC on the left, under Sample Applications,
called 'A Class Browser Application'. Look under the
System.Collections Class to find it's many properties and methods.


I will go into a few, just to show you a few common things that can be done
with the ArrayList. As you probably have figured, from the tutorial so far,
there is definitely a Count property. And, as logically as it sounds, it
can be accessed like this:




Label1.text = MyArrayList.Count



We can iterate through the list, parsing or manipulating the items, but since
it's zero based, if we use a For/Next loop, we must do it like this:



for x=0 to MyArrayList.Count-1
'manipulate the items
next


We can use this to put the items of an ArrayList into a string:



Dim sNewString as String
for x=0 to MyArrayList.Count-1
'We step through the arraylist, one at a time
'Here we create the string, adding each item, followed by a comma
sNewString+=MyArrayList(x).ToString & ","
next


We can sort the ArrayList, in ascending order, easily like this:




MyArrayList.Sort



And, conversely, we can sort them descending like this:




MyArrayList.Reverse



As you've seen earlier, to add an item, we just call the 'Add' Method, and it
also has a 'Remove' method to - you guessed it - Remove an item from the
ArrayList. Also, it has an Item property, which uses the numbered position in
the ArrayList as a parameter, and can be accessed like this:




Label1.text=MyArraList.Item(3)


No comments: