ArrayList not populating correctly

Glitterati

Member
Joined
Mar 17, 2006
Messages
13
Programming Experience
Beginner
Or maybe it is but the data just isn't displaying properly. What I'm trying to accomplish is a "guessing game" for my nephew. He enters a number and is prompted as to whether the number is too high, too low or guessed correctly. Each guess along with the number of tries is then put in an arraylist and that arraylist is bound to a datagrid. The datagrid should display a running list of each guess entered along with number of guesses he's made. Currently the datagrid only displays the last value entered. It does not add items to the arraylist. Here is my code:

PrivateSub btnSubmit_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnSubmit.Click
Dim MyGuess AsNew Guess()
Dim rndVal AsInteger
Dim StoreGuesses AsNew ArrayList

rndVal =
Me.txtRandom.Text
MyGuess.NumTries = 0
MyGuess.GuessVal = scrNum1.Value
If MyGuess.GuessVal > rndVal Then
MsgBox("Too high. Please guess again.")
StoreGuesses.Add(MyGuess)
Else
If MyGuess.GuessVal < rndVal Then
MsgBox("Too low. Please guess again.")
StoreGuesses.Add(MyGuess)
Else
If MyGuess.GuessVal = rndVal Then
MsgBox("You guessed correctly! You rock!")
StoreGuesses.Add(MyGuess)
EndIf
EndIf
EndIf
dgGuesses.DataSource = StoreGuesses
MyGuess.NumTries = MyGuess.NumTries + 1
EndSub

I appreciate any help anyone can offer. I'm new to programming in general and thought a simple game would be a good way to learn! :)
 
That's because you create a new array list each time the sub runs. You need to move the Dim for your array list out of the sub so that it is at the module level.

-tg
 
Hey TechGnome,

Thanks for the reply! I really appreciate the help!

I did what you suggested and moved the Dim out of the sub and into the module level and now the datagrid gets populated after the first guess but then never again. Do I need to move something else into the Module level?

Thanks!
 
Back
Top