|
Jan 14, 2001
Arrays 3
In this article, we shall study the use of loops to traverse arrays and
adding and removing items from a list of elements
Using Loops to Traverse an Array
You can use the For...Next loop that we studied in previous articles to move
through, or traverse, an array. This can be useful when you want to
change or report values in an array.
Example:01 Private Sub cmdTrav_Click()
02 Dim i%
03 Dim newarray%(19) As Integer
04 Dim startmessage$
05 Dim MidMsg$
06 Dim LoopMsg$
07 Dim FullMsg$
08
09 `Every element is assigned value
10 `by using a loop to traverse to each element
11 `in the array.
12 For i% = 0 To 19
13 `We triple the value
14 `of i%
15 newarray%(i%) = i% * 3
16 Next i%
17
18 `Create the startmessage$ string
19 startmessage$ = "The element is: "
20 MidMsg$ = ", The value is: "
21 `The array is traversed again
22 `to display the string message
23 For i% = 0 To 19
24 LoopMsg$ = LoopMsg$ & startmessage$ & CStr(i%)
25 LoopMsg$ = LoopMsg$ & MidMsg$ & newarray(i%)
26
27 `Concatenate the loop message to the
28 `full message.
29 FullMsg$ = FullMsg$ & LoopMsg$
30
31 End Sub
Selecting Items from a List
To understand how Visual Basic determines the value of a string selected in the List of a ListBox or ComboBox, you need to understand that a List is an array of strings.
We declare an array as follows:
Dim ArrayName(Subscript) As DataType
Therefore, if you declared a four-element array as NewArray(3), you would list the elements in that array as follows:
NewArray(0)
NewArray(1)
NewArray(2)
NewArray(3)
If you want to determine the value assigned to the second element, you could use the following statement (remember, by default the first element is NewArray(0)):
NewValue = NewArray(1)
Removing Items from a List
You remove a string from a list in a ListBox or ComboBox by using the
RemoveItem method:
Object.RemoveItem Index
In this syntax
- Object is the Name property of the ListBox or ComboBox.
- RemoveItem is the Visual Basic keyword for the method used to remove items
from a list.
- Index is the position in the List property of the string that you
want to remove from the control. To remove a selected item from a list, use
the ListIndex property of the control.
In the next article, we shall have a discussion on Variable scope and
duration.
Go To Page:
1
The copyright of the article Arrays III in Learning Visual Basic is owned by . Permission to republish Arrays III in print or online must be granted by the author in writing.
|