Multi Dimensional Arrays

The arrays you have seen so far are only one column arrays, 1 Dimensional arrays as they are known. A 1-D array holds one column of data:

array(0) = "0"
array(1) = "1"
array(2) = "2"
array(3) = "3"

Visually, it looks like this:

A 1 Dimensional array

So we have four rows with one value in each column.

Another type of array is a 2 Dimensional array. This holds data in a grid pattern, rather like a spreadsheet. They look like this:

A 2 Dimensional array

We still have 4 rows, but now we have 4 columns. The values in the image above represent the array positions. Before, we only had to worry about positions 0 to 3. We could then place a value at that position. Now, though, we can have values at position such as 0, 0, and 2, 1.

To set up a 2-D array in Visual Basic .NET you just add a second number between the round brackets:

Dim grid(3, 3) As Integer

Again, arrays start counting at 0, so the above declarations means set up an array with 4 rows and 4 columns.

To store values in the grid, you need both numbers between the round brackets:

grid(0, 0) = 1

This means fill row 0, column 0 with a value of 1. You could type out all your positions and values like this: (The left number between the round brackets is always the row number; the right number is always the columns.)

grid(0, 0) = 1
grid(1, 0) = 2
grid(2, 0) = 3
grid(3, 0) = 4

grid(0, 1) = 5
grid(1, 1) = 6
grid(2, 1) = 7
grid(3, 1) = 8

grid(0, 2) = 9
grid(1, 2) = 10
grid(2, 2) = 11
grid(2, 2) = 12

grid(0, 3) = 13
grid(1, 3) = 14
grid(2, 3) = 15
grid(3, 3) = 16

Typically, though, 2-D arrays are filled using a double for loop. The following code just places the numbers 1 to 16 in the same positions as in the example above:

Dim grid(3, 3) As Integer
Dim row As Integer
Dim col As Integer
Dim counter As Integer = 1

For row = 0 To 3

For col = 0 To 3

grid(row, col) = counter
counter = counter + 1

Next

Next

Notice how the outer loop goes from row = 0 to 3 and the inner loop goes from col = 0 to 3. This allows you to fill all the rows and columns in the array.

To display all the above values in a listbox, you could have this code:

Dim temp as String = ""

For row = 0 To 3

For col = 0 To 3

temp = temp & "-" & grid(row, col).ToString()

Next

ListBox1.Items.Add(temp)
temp = ""

Next

Again, we're using a double for loop to access the array.

2-D arrays are tricky to get the hang of, but they do come in useful from time to time.

Back to the VB NET Contents Page