How to Access the Value of an Array

aman_VB

Member
Joined
Apr 27, 2010
Messages
23
Programming Experience
1-3
I tried to initialize an array in a Public Sub, but then when I try to access the array's value from Button1 click event, it shows blank.

VB.NET:
Public Class Form1
    Public myArray()

    Public Sub SimpleArray()
        ReDim Preserve myArray(10)
        For i = 0 To myArray.Length - 1
            myArray(i) = i * 3
        Next
    End Sub

    Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
        'SimpleArray()
        'Can I access the value of the myArray without calling the Sub?
        ReDim Preserve myArray(10)
        MessageBox.Show(myArray(4))
    End Sub
End Class

Thanks in advance.
A
 
First up, NEVER declare anything without a type. You should turn Option Strict On and then the compiler won't let you. It looks like you want to store Integers in your array so you should declare it as an Integer array:
VB.NET:
Public Class Form1
    [COLOR="red"]Public myArray() As Integer[/COLOR]

    Public Sub SimpleArray()
        ReDim Preserve myArray(10)
        For i = 0 To myArray.Length - 1
            myArray(i) = i * 3
        Next
    End Sub

    Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
        'SimpleArray()
        'Can I access the value of the myArray without calling the Sub?
        ReDim Preserve myArray(10)
        MessageBox.Show(myArray(4))
    End Sub
End Class
Secondly, if you know how many elements the array is going to have when it's declared then specify that and create the array when you declare the variable:
VB.NET:
Public myArray(10) As Integer
You then don't need to ReDim at all.

Now, if you want to assign values to the elements of the array then you need some way of assigning each element. If you know the actual values then you can assign a literal array:
VB.NET:
Public myArray As Integer() = {0, 3, 6, 9, 12, 15, 18, 21, 24, 27, 30}
If you have to calculate the values then you need to use a method of some description. In many cases that will need to be a method in which you actually calculate and assign each value, as you've shown. In some cases though, where there's a pattern to the values, you can use a method that returns an array and call it the line that does the assignment. This will create the same array as you have in your code:
VB.NET:
Public myArray As Integer() = Array.ConvertAll(Enumerable.Range(0, 11).ToArray(), Function(i) i * 3)
Enumerable.Range creates a list of 11 numbers starting at 0 and that is then turned into an array. Array.ConvertAll then creates a new array where each element is the result of passing the corresponding element in another array to a function. The function in this case is one that takes an Integer 'i' and returns (i * 3).
 
Back
Top