Reputation: 351
I thought I understood how for loops and arrays worked but for some reason when I try to use them together I'm not getting what I expected. Basically I want to create a for loop to increment the the index of the array and assign each element in the array the number entered from the user. In C++ it would look something like this:
int array[11];
for(int i=0; i<12; i++)
{
array[i]=valueEntered;
}
Now I'm trying to recreate this in Visual Basic. This is what I have:
Dim gasArray(11) As Decimal
For i As Integer = 0 To 11 Step 1
gasArray(i) = Val(priceTB.Text)
priceLB.Items.Add(Val(priceTB.Text))
priceTB.Clear()
Next
but my price list box (priceLB) prints out only the first number entered and 0's for the rest of the array. Any help here would be greatly appreciated.
Simple fix using a global counting variable outside of sub.
Dim gasArray(11) As Decimal
gasArray(i) = Val(priceTB.Text)
i += 1
priceLB.Items.Add(Val(priceTB.Text))
priceTB.Clear()
If i > 11 Then
enterBtn.Enabled = False
priceTB.Enabled = False
End If
Upvotes: 0
Views: 4705
Reputation: 67207
While reading your case, I understood that you need to add 10 different numbers in an array from a single text box. Ok as @rcs said priceTB.Clear()
will empty the text box after the first iteration.
So i recommend you to use inputbox in your case. It will help you to get 10 different values in 10 iterations of that loop.
Dim gasArray(9) As Decimal
For i As Integer = 0 To gasArray.length - 1
gasArray(i) = Val(InputBox("Enter a value", "Hello", String.Empty))
priceLB.Items.Add(gasArray(i))
Next
Upvotes: 0
Reputation: 7197
Why do you call priceTB.Clear()
? I think this will clear the text box, and hence the rest of the array becomes 0.
Upvotes: 3