Microsoft.NET

……………………………………………….Expertise in .NET Technologies

ArrayLists

Posted by Ravi Varma Thumati on September 21, 2009

ASP.NET Collections are data structures that are similar to Visual Basic arrays, functioning as script storage areas for collections of data values. Collections can supply arrays of values for use in script processing; they can be used as intermediate data stores for imported values that are bound to controls. There are three types of Collections under ASP.NET: ArrayLists, HashTables, and SortedLists. This tutorial discusses ArrayLists; follow-up tutorials cover HashTables and SortedLists.

Using ArrayLists

An ArrayList is an sequence of storage locations, each containing a single data value. After an ArrayList is created in a script, its data values are available for script processing or they can be bound to a list control to automatically generate the items in the list. When an ArrayList is bound to an <asp:RadioButtonList>, for example, the individual buttons with their labels and values are produced automatically in the same manner in which an external data source is bound to the control.

 ArrayList1

Figure C-1. Using an ArrayList for data binding.

The following code creates an ArrayList of color names when the page is loaded. The ArrayList is then bound to a RadioButtonList to supply its values, producing a set of buttons like those shown in the above illustration. Any of the list controls—RadioButtonList, CheckBoxList, DropDownList, or ListBox—can be bound to an ArrayList.

Red
Green
Blue

Figure C-2. Binding an ArrayList to a RadioButtonList.

<SCRIPT Runat="Server">
Sub Page_Load
  Dim ColorList = New ArrayList
  ColorList.Add("Red")
  ColorList.Add("Green")
  ColorList.Add("Blue")
  RadioList.DataSource = ColorList
  RadioList.DataBind()
End Sub
</SCRIPT>
<form Runat="Server">
<asp:RadioButtonList Runat="Server"/>
</form>

Listing C-1. Code to bind an ArrayList to a RadioButtonList.

Creating ArrayLists

An ArrayList is created by assigning a New ArrayList() object to a reference variable, optionally specifying the number of entries in the list within the parentheses. Then, data values are added to the list with the list’s Add() method. Once the ArrayList is filled with data, its values can be used to support script processing, or the list can be bound to one of the list controls. An ArrayList is bound to the DataSource property of the control, and the control’s DataBind() method is called to bind the values. For controls that require them, DataTextField and DataValueField properties can be assigned from the array. The general formats for the statements involved in creating and binding an ArrayList are shown below.

Dim ArrayList = New ArrayList()
ArrayList.Add(value)
...
Control.DataSource = ArrayList
Control.DataTextField = "value"
Control.DataValueField = "value"
Control.DataBind()

Figure C-3. General formats for creating and binding an ArrayList.

An ArrayList can be defined without specifying the exact number of entries; e.g., New ArrayList() or New ArrayList without parentheses. An “undimensioned” array is necessary when creating it from an external data source containing an unknown number of data values. If a size is not specified, an ArrayList is initially configured for 16 entries; however, it expands as needed as data values are added to the list. Each time it expands, an additional 16 slots are provided. It can be compacted to its final size by using the ArrayList.TrimToSize() method to set the final size of the list to its final number of data values. It is not necessary to compact the list for it to work properly.

An ArrayList can be sorted with the ArrayList.Sort() method. Sorting in reverse order is accomplished by applying the ArrayList.Sort() method followed by the ArrayList.Reverse() method.

Items can be removed programmatically from the list by supplying the value of the item to delete: ArrayList.Remove(“value“). Entries in the list are indexed starting with 0. So, an item also can be deleted by supplying its index number: ArrayList.RemoveAt(index); or a range of items can be deleted by supplying the first and last index numbers of the range: ArrayList.RemoveRange(index1,index2). The ArrayList can be cleared of all entries with ArrayList.Clear().

The current capacity of the list (including empty elements) can be determined from its ArrayList.Capacity property, and the current number of data values in the list is given by its ArrayList.Count property.

Individual items in an ArrayList can be accessed by their indexes, beginning with 0. So, for example, the reference ArrayList(3) accesses the contents of the fourth element in the list. The entire contents of the list can be accessed through a For…Next or For Each…Next loop which iterates the elements of the array. The following scripts show two ways to access, in turn, all values stored in the previous ColorList array.

Dim i As Integer
For i = 0 to ColorList.Count - 1
  ...process ColorList(i)          '-- process array value
Next
Dim Element As String
For Each Element in ColorList
  ...process Element               '-- process array value
Next

Listing C-2. Code to iterate items in an ArrayList.

The iteration variable Element used in the second loop is declared as a string variable. This is because the values in the ArrayList are strings (color names). The iteration variable must be declared as the same type as the values in the ArrayList.

Editing an ArrayList

The contents of an ArrayList can be changed by a script after it has been initially populated with values. The following button, for example, adds three new colors to the ColorList array that is loaded with this page. In addition, the script reverse sorts the array and re-binds its values to the RadioButtonList in Figure C-2. After clicking the button, scroll up to look at the newly populated RadioButtonList.

Figure C-4. Editing an ArrayList.

<SCRIPT Runat="Server">
Sub EditArray (Src As Object, Args As EventArgs)
  ColorList.Add("Purple")
  ColorList.Add("Yellow")
  ColorList.Add("Brown")
  ColorList.Sort()
  ColorList.Reverse()
  ColorList.TrimToSize()
  RadioList.DataSource = ColorList
  RadioList.DataBind()
End Sub
</SCRIPT>
<form Runat="Server">
<asp:Button Text="Edit Array" Runat="Server"/>
</form>

Listing C-3. Code to edit an ArrayList.

Maintaining the View State of ArrayLists

If an ArrayList is bound to a list control and no further access to the array is needed, then it can be created one time only, the first time the page loads. The array values that are bound to the list control are available on subsequent page postings because the control itself takes part in the page’s View State. An ArrayList, however, does not participate in the page’s View State. Therefore, if access to the ArrayList is needed on subsequent page postings, then it needs to be recreated each time the page is loaded. This is the case in the previous example where ColorList is created the first time the page loads and its values are bound to the RadioButtonList; it is recreated when the button is clicked and a post-back operation takes place to edit the array. Thus, the script to create ColorList appears in the Page_Load subprogram so that it is run each time the page opens.

Rather than recreating an ArrayList from scratch each time the page is loaded, the original array can be assigned to a View State variable from which it is reconstituted each time the page is loaded. That is, even though an ArrayList itself does not take part in the page’s View State, it can be made to participate in the View State with assignment to this variable. The following script illustrates this idea.

<SCRIPT Runat="Server">
Sub Page_Load
  If Not Page.IsPostBack Then
    '-- Define and populate an ArrayList
    Dim ColorList = New ArrayList
    ColorList.Add("Red")
    ColorList.Add("Green")
    ColorList.Add("Blue")
    '-- Bind ArrayList to radio buttons
    RadioList.DataSource = ColorList
    RadioList.DataBind
    '-- Save ArrayList as View State variable
    ViewState("ColorList") = ColorList
  End If
  '-- Define new ArrayList and reconstitute from View State variable
  Dim ColorList = New ArrayList
  ColorList = ViewState("ColorList")
End Sub
</SCRIPT>

Listing C-4. Code to save an ArrayList in View State.

The first time the page is loaded, ColorList is created and populated as a new ArrayList, and it is bound to a RadioButtonList. The RadioButtonList maintains its bound values on page post-backs because all server controls take part in the page’s View State. Assuming, though, that access to the ArrayList is needed on subsequent page postings, it is saved as ViewState(“ColorList”) to also participate in the page’s View State. Subsequently, on each page post-back, a new ArrayList is created and repopulated from the View State variable.

Lookup Tables

One of the popular uses of an ArrayList is as a lookup table that can be searched by a script to find information. In the following example, a color name is chosen from a DropDownList. The index value of the selected item is used as the index location in an ArrayList of the hexadecimal value of the color.

RedGreenBlue

Figure C-5. Using an ArrayList for table lookup.

For this example, two ArrayLists are built. The first is populated with color names and bound to a DropDownList. The second is populated with matching hexadecimal values to serve as a memory-resident lookup table. The hexadecimal list is declared as a global variable because it is accessed in two separate subprograms. It is saved in View State since it is needed on page post-backs.

<SCRIPT Runat="Server">
Dim HexList As ArrayList
Sub Page_Load
  If Not Page.IsPostBack Then
    HexList = New ArrayList
    HexList.Add("#FF0000")
    HexList.Add("#008800")
    HexList.Add("#0000FF")
    ViewState("HexList") = HexList
    Dim ColorList = New ArrayList
    ColorList.Add("Red")
    ColorList.Add("Green")
    ColorList.Add("Blue")
    Colors.DataSource = ColorList
    Colors.DataBind()
  End If
  HexList = New ArrayList
  HexList = ViewState("HexList")
End Sub
Sub Get_Hex (Src As Object, Args As EventArgs)
  HexColor.Text = HexList(Colors.SelectedIndex)
  HexColor.Style("color") = HexList(Colors.SelectedIndex)
End Sub
</SCRIPT>
<form Runat="Server">
<asp:DropDownList Runat="Server"/>
<asp:Button Text="Find Hex" Runat="Server"/>
<asp:Label Runat="Server"/>
</form>

Listing C-5. Code to use an ArrayList for table lookup.

The ColorList ArrayList is built the first time the page loads and is bound to the Colors DropDownList. It is not necessary to build the ArrayList on every page post-back since the DropDownList is maintained in the page’s View State on subsequent page loads. ColorList is needed only one time, as the original data source for the DropDownList.

The HexList ArrayList, however, must be built every time the page loads, initially and on post-back when the “Find Hex” button is clicked. Therefore, HexList is initially saved as a View State variable and is recreated from this variable on each page load.

When the button is clicked, the Get_Hex subprogram is called. The purpose of this subprogram is to find the hexadecimal value that equates to the color name selected in the DropDownList. The values in an ArrayList are indexed starting with 0; so are the values in a DropDownList. Therefore, the index value of the selected color (Colors.SelectedIndex) can be used as the index of the matching hexadecimal value in the ArrayList: HexList(Colors.SelectedIndex). This matching value is displayed in the HexColor Label control. The color of the text is set to this same hexadecimal value.

Loading ArrayLists from External Data Sources

Previous examples show ArrayLists created through script, with individual values added as hard coded text. More likely, ArrayLists will be loaded from external data sources where changing values can be maintained without editing scripts. In the following example, an XML file supplies state names and state codes. The names are loaded into a DropDownList; the codes are loaded into an ArrayList. A matching code is displayed for a state name chosen from the DropDownList.

AlabamaAlaskaArizonaArkansasCaliforniaColoradoConnecticutDelewareFloridaGeorgia

Figure C-6. Using an ArrayList created from an XML file for table lookup.

This following listing shows the first portion of content from file StateCodes.xml. Element <name> is used to populate the DropDownList; element <code> is used to build the ArrayList.

<?xml version="1.0" ?>
<statecodes>
  <state>
    <name>Alabama</name>
    <code>AL</code>
  </state>
  <state>
    <name>Alaska</name>
    <code>AK</code>
  </state>
  <state>
    <name>Arizona</name>
    <code>AZ</code>
  </state>
  ...
</statecodes>

Figure C-6. XML file used to load an ArrayList

Script and HTML code for this application is shown below.

<%@ Import Namespace="System.Data" %>
<SCRIPT Runat="Server">
Dim CodesArray As ArrayList
Sub Page_Load
  If Not Page.IsPostBack Then
    '-- Import XML file into data set
    Dim StateCodes = New DataSet
    StateCodes.ReadXml("StateCodes.xml")                     
   '-- Bind state names to drop-down list
    StatesList.DataSource = StateCodes
    StatesList.DataTextField = "name"
    StatesList.DataValueField = "name"
    StatesList.DataBind()
    '-- Create array of state codes
    CodesArray = New ArrayList
    Dim Row As DataRow
    For Each Row in StateCodes.Tables("state").Rows
      CodesArray.Add(Row("code"))
    Next
    ViewState("CodesArray") = CodesArray
  End If
  '-- Rebuild array of state codes
  CodesArray = New ArrayList
  CodesArray = ViewState("CodesArray")         
End Sub
Sub Get_Code (Src As Object, Args As EventArgs)
  TheCode.Text = CodesArray(StatesList.SelectedIndex)
End Sub
</SCRIPT>
<form Runat="Server">
<asp:DropDownList Runat="Server"/>
<asp:Button Text="Find Code" Runat="Server"/>
<asp:Label Runat="Server"/>
</form>

Listing C-7. Code to load and use an XML file for table lookup.

Recall from earlier discussions that an XML file must be imported to the page as a DataSet in order to be in proper tabular (row and column) format for binding to controls and for iterating the items in this recordset. Therefore, the System.Data namespace must be imported to the page, and as repeated below, the file must be read into a DataSet. This importing into a DataSet takes place only the first time the page loads since names from the DataSet are bound to the DropDownList and codes from the DataSet are used to build the ArrayList. The DropDownList and ArrayList can be independently maintained on subsequent post-backs of the page.

'-- Import XML file into data set
Dim StateCodes = New DataSet
StateCodes.ReadXml(StateCodes.xml")

Listing C-8. Importing an XML file into a DataSet.

Next, the DataSet is bound to the DropDownList using state names (the name field imported from the <name> element) as the Text and Value properties of the list. Recall that if only one of these properties is assigned the other property takes on the same value by default.

'-- Bind state names to drop-down list
StatesList.DataSource = StateCodes
StatesList.DataTextField = "name"
StatesList.DataValueField = "name"
StatesList.DataBind()

Listing C-9. Binding a DataSet to a DropDownList.

Finally, the rows of the DataSet are iterated to build the CodesArray. The name of the DataSet table, “state,” is taken from the tags surrounding each group of state names and codes. An iteration variable, Row, is declared as a DataRow type and a For Each…Next loop is set up to iterates these DataRows in the DataSet table’s Rows collection. At each row, the value in the “code” column (taken from the XML tag name) is added as an element in the ArrayList. After the ArrayList is built, it is saved as a View State variable since it needs to be rebuilt on every page post-back, every time a table lookup is performed.

'-- Create array of state codes
CodesArray = New ArrayList
Dim Row As DataRow
For Each Row in StateCodes.Tables("state").Rows
  CodesArray.Add(Row("code"))
Next
ViewState("CodesArray") = CodesArray

Listing C-10. Script to iterate a DataSet to build an ArrayList.

Remember that items in the DropDownList and elements the ArrayList are indexed the same, beginning with 0. State names in the DropDownList have the same index value as their associated state codes in the ArrayList. Therefore, subprogram Get_Code uses the SelectedIndex of the DropDownList as the index for the matching code in the ArrayList.

Sub Get_Code (Src As Object, Args As EventArgs)
  TheCode.Text = CodesArray(StatesList.SelectedIndex)
End Sub

Listing C-11. Locating a ArrayList value matching a DropDownList selection.

The above examples show a few of the ways in which ArrayLists can be used to support page processing. They can be used in all of the variety of ways you use standard Visual Basic arrays, and then some. One of the issues surrounding ArrayLists, however, is that they are single dimensional. They store a list of single data values. This issue is partially resolved by HashTables and SortedLists, topics taken up in the following tutorials.

 

 

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

 
%d bloggers like this: