KSR5
KSR5

Reputation: 81

ArrayList in VB 2010 - What's wrong with my code?

I was just wondering if anyone could point out where I am going wrong with this code. I am working with an ArrayList called Nouns and have code which adds the word that's picked from the ArrayList to another ArrayList called NewArray().

The trouble is, when the Sub is called from a label_click event, it doesn't keep the words stored in the NewArray where the code NewArray.Add(WordChosen) is. I found this from debugging it, using breakpoints and stepping.

The code for this part is here:

Sub GetNoun()

    Dim Nouns As ArrayList = New ArrayList(16)
    Nouns.Add("France")
    Nouns.Add("Bird")
    Nouns.Add("Doctor")
    Nouns.Add("City")
    ...

    Dim lblArray As Label() = {lblOne, lblTwo, lblThree, lblFour}

Start:
    Dim WordChosen As String
    WordChosen = Nouns(Random.Next(16))

    If NewArray.Contains(WordChosen) Then
        GoTo Start
    Else
        Dim LabelChosen As Label
        LabelChosen = lblArray(Random.Next(4))
        LabelChosen.Text = WordChosen
        Nouns.Remove(WordChosen)
        NewArray.Add(WordChosen)
    End If
End Sub

What could I do to keep the words within the dynamic ArrayList? I hope this makes sense and isn't a duplicate, but I am stuck for ideas.

Upvotes: 1

Views: 126

Answers (1)

SLaks
SLaks

Reputation: 887385

Your list is a local variable.

Each time you call the function, you get a fresh new variable.

You should move it to the class to create a single field, and initialize it in the constructor.

Upvotes: 2

Related Questions