The Flexible ArrayList

Team Fly 

Page 35

The Flexible ArrayList

The ArrayList, new in VB.NET, offers a variety of helpful features not typical of ordinary arrays. For one thing, it can dynamically resize itself, so you don't have to resort to ReDim and other techniques that an ordinary array can demand.

Here's one way to use an ArrayList to add values:

 Dim MyArray as new ArrayList   myArray.Add (''key")   myArray.Add ("Name")   myArray.Add ("Address") Msgbox (MyArray(2)) 

Both array and ArrayList .NET classes can sort, search, reverse, and otherwise manipulate their data. The ArrayList, however, takes the idea of an array to new levels. One problem with arrays is that you can't easily add or delete items. If you want to remove, say, the tenth item in an array, you must write some code that loops through the array, moving each value down one in the index list from the tenth item up to the final element.

The ArrayList has built-in facilities to automatically handle any resizing and re-indexing that's needed if you insert or delete elements.

Put a ListBox and a Button on a form. Then type in the code in Listing 2.6, which illustrates how you can remove an element by using the RemoveAt method and specifying an index number.

LISTING 2.6: USING THE REMOVEAT METHOD TO DELETE AN ARRAY ELEMENT

Public Class Form1

    Inherits System.Windows.Forms.Form


    Public arrList As New ArrayList()


    Private Sub Form1_Load(ByVal sender As System.Object, _
ByVal e As System.EventArgs) Handles MyBase.Load
        arrList.Add("ET" )
        arrList.Add("Pearl Harbor" )
        arrList.Add("Rain" )

        ListBox1.Items.AddRange(arrList.ToArray)

    End Sub

    Private Sub Button1_Click(ByVal sender As System.Object, _
ByVal e As System.EventArgs) Handles Button1.Click

Team Fly 


Visual Basic  .NET Power Tools
Visual Basic .NET Power Tools
ISBN: 0782142427
EAN: 2147483647
Year: 2003
Pages: 178

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net