There are a number of way you can put data into each position of an array. The code we just wrote for the two buttons had known values stored into each position. We knew we that we wanted the numbers 1 to 5 to be stored into our Integer array, and we knew that we wanted the text "This is a String Array" stored into our String array.
But you don't have to know what the values are. You can assign values straight from a Textbox into the position of your array. Like this:MyNumbers(1) = Val(Textbox2.Text)
etc
MyNumbers(1) = Textbox2.Text
etc
Well, obviously not. You can use code to assign values to your array. Here is an example where we don't type out values for all positions of an array. It's the times table again. This time we'll use an array. And we'll write a line of code to assign values to each position of the array.
- First, add another Button to your form.
- Set the Text Property to "Times TableArray"
- Add a Textbox to your Form
- Set the Text Property to a blank string (in other words, delete Textbox1 from the Text property)
- Add a Label near the Textbox
- Set the Text property of the Label to "Which Times Table do you want?"
- Now double click your new button to get at the code window. Add the following code:
Dim times As Integer
Dim StoreAnswer As Integer
Dim i As Integer
ListBox1.Items.Add(times & " times " & i & " = " & numbers(i))
At the top of the code we set up three normal Integer variables, i, times and StoreAnswer. (We didn't really need the StoreAnswer variable, but it is here to make the code more readable.) We also set up an array. (Notice that we set it to 10. This actually gives us 11 positions in the array. But we're only putting something in positions 1 to 10. This is because it is more convenient for us, and for our Loop.)
The second time around the loop, the variable i will hold a value of 2. So the second position of our array, numbers(2), will again be assigned whatever is in the variable StoreAnswer
We go round and round the loop assigning values to all ten positions of our array.
The other two lines of code inside the array just work out the times tables, and Adds the answer to the List Box. Study them, and make sure you understand how they work.
But the point of this is to demonstrate that you can use code to assign a value to a position in an array.
In the next part, we'll take a look at situations where you don't know how many items will be in an array.