VB Arrays

VB Arrays

Arrays


Array variables are defined in Visual Basic using the same notation as with simple variables but with parenthesis after the variable name.

Example:

Dim score (10) As Integer

defines score as an array variable with eleven elements

score(0) = 2
score(1) = 5
score(2) = 3
...
score(10) = 4

The number inside the parenthesis (always an integer) is the subscript and refers to the index number of the array variable.

The number of elements in the array is always one more than the array parameter to allow for zero-based indexing.

This is done to accomodate earlier versions of Visual Basic which might be migrated to the VB.NET.

The upper bound of the array is the largest index number the array can be subscripted. In the above example the upper bound is 10.

The number of elements of the array is 11 (one more than the upper bound number) or the size.

Array elements are all the same type -- you cannot mix up Integer element types with other types in the same array.

The default initial value of each subscripted variable is the same as with an ordinary variable. For String types the keyword Nothing is the default value. For numeric types, the value zero is the default.

Scope rules for array declarations are the same as those for variables. An array declared in the Declarations section of the Code window is class level.

Fixed size array
                       
This code snippet will display:

Element 0 is John
Element 1 is Mary
Element 2 is Sue
Element 3 is Cornelius

The method GetUpperBound() applied to an array name returns the upper bound of the array. The parameter zero indicates that the upper bound for the first dimension is used.

Fixed size array initialized at declaration


The ReDim statement resizes a previously defined array but also loses its current contents.



The latter part shows:

Element 0 is
Element 1 is
Element 2 is
Element 3 is
Element 4 is Sam
Element 5 is
Element 6 is

Multi-dimensional arrays are declared in Visual Basic as

Dim sngMatrix(3, 3) as Single

or

Dim sngMatrix( , ) as Single = { {1, 2, 3} , {4, 5, 6}, {7, 8 ,9 } }

Passing an array as a parameter to a Subor a Functionis done by using the array name without a trailing set of empty parenthesis as an argument. The corresponding parameter in the Declaration statement for the procedure must consist of an array name witha trailing empty set of parenthesis



Control arrays are arrays consisting of controls such as labels, textboxes, buttons.

Control array examples:

Dim lblTitle(10) as Label
Dim txtName(10) as TextBox
Dim btnAmount(10) as Button



The ArrayList class can be used in VB.NET for any type of object combination.



Output from above:




Array sorting is done with the Array.sort() method call.

posted @ 2015-06-17 00:05  xymum  阅读(264)  评论(0编辑  收藏  举报