Visual Basic Multidimensional Arrays

From Techotopia
Revision as of 20:07, 3 August 2007 by Neil (Talk | contribs)

Jump to: navigation, search

A multidimensional Visual Basic array is nothing more than an array in which each array element is itself an array. A multidimensional array can, therefore, be thought of as a table, where each element in the parent array represents a row of the table and the elements of each child array represent the columns of the row. In fact, Visual Basic does limit an array to two dimensions - up to 32 dimensions are supported.

In this chapter we will cover the creation and use of multidimentional arrays in Visual Basic. To learn how to use single dimensional arrays read Visual Basic Arrays.

Creating a Visual Basic Multidimensional Array

Continuing our table analogy, declaring a multidimensional array requires that both the number of rows and columns be defined when the array is created. As with standard arrays, multidimensional arrays are declared using the Dim keyword:

Dim strBooks(4, 2) As String

The above Visual Basic code excerpt creates a two dimensional String array of 5 rows and 2 columns.

Assigning Values to Multidimensional Array Elements

Values are assigned to array elements by specifying the index into each dimension. For example, in a two dimensional array, 0, 0 will references the element in the first column of the first row of the array. The following code initializes each element of our array:

Dim strBooks(4, 1) As String

strBooks (0, 0) = "Learning Visual Basic"
strBooks (0, 1) = "John Smith"
strBooks (1, 0) = "Visual Basic in 1 Week"
strBooks (1, 1) = "Bill White"
strBooks (2, 0) = "Everything about Visual Basic"
strBooks (2, 1) = "Mary Green"
strBooks (3, 0) = "Programming Made Easy"
strBooks (3, 1) = "Mark Wilson"
strBooks (4, 0) = "Visual Basic 101"
strBooks (4, 1) = "Alan Woods"

The above example creates a two dimensional array of 5 rows (remember that indexing starts at 0 so this array have elements from 0 to 4 inclusive) and two columns. Column 1 is the book title and column 2 the author.


Accessing Elements of a Multidimensional Array