. . Next syntax looks like this:
For Each element As datatype In collection
statements
Exit For
Next element
If you have an array (or any other type of collection) of strings, for example, you could
iterate over each string using the following code:
Dim StringArray(1) As String
StringArray(0) = "Cat"
StringArray(1) = "Dog"
For Each Item As String In StringArray
Console.WriteLine("{0}", Item)
Next
Within the first line of the For Each . . . Next loop, you declare the type of your iterator
variable. In this example, it??™s a string. Following the declaration of the iterator type is the identifier
for the collection to iterate over. You can use the For Each . . . Next loop with any
object that implements the IEnumerable interface, making it perfect for actions such as looping
over rows in an ADO DataTable or elements in an ArrayList.
The elements within the collection used in a For Each . . . Next statement must be able
to be converted to the iterator type. If the value being evaluated can be converted to the iterator
type, VB performs the conversion implicitly. If the conversion fails, the For Each . . .
Next statement throws an InvalidCastException at run time. For example, this modification to
the previous example causes an OverflowException runtime error on the second array element
because VB implicitly tries to convert it from Long to Integer:
Dim anArray(1) As Long
anArray(0) = 2
anArray(1) = 3473928374736
For Each Item As Integer In anArray
Console.
Pages:
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84