0

So I've made an attempt to create a very simple roulette game by creating each possible outcome as an individual label, however when running my code I'm getting the unhandled exception appear and I can see where it coming from to an extent.

However I am unsure of what to do in order to make this work, I'm new to programming so any suggestions would be great. Thank you, here is my code:

Function code:

Public Class Random_Number_Gen

Public Function GetRandom()
    Dim Min As Integer = 0
    Dim Max As Integer = 37

    Static Generator As New System.Random()
    Return Generator.Next(Min, Max)
End Function

End Class

Class code:

Public Class Roulette
Dim aLabel() As Label = {Lbl0, Lbl1, Lbl2, Lbl3, Lbl4, Lbl5, Lbl6, Lbl7, Lbl8, Lbl9, Lbl10,
Lbl11, Lbl12, Lbl13, Lbl14, Lbl15, Lbl16, Lbl17, Lbl18, Lbl19, Lbl20, Lbl21, Lbl22, Lbl23,
Lbl24, Lbl25, Lbl26, Lbl27, Lbl28, Lbl29, Lbl30, Lbl31, Lbl32, Lbl33, Lbl34, Lbl35, Lbl36}

Private Sub BtnSpin_Click(sender As Object, e As EventArgs) Handles BtnSpin.Click
    'Calls the function from GetRandom() returning a random number
    Dim oRandomNumber As New Random_Number_Gen
    LblNumber.Text = oRandomNumber.GetRandom()

    For i As Integer = 0 To 36
        If LblNumber.Text = aLabel(i).Text Then
            aLabel(i).BackColor = Color.LightBlue
        End If
    Next
End Sub

I am receiving the exception from the second line within the For Next loop.

  • 2
    Look at the array - it is full of Nothing because you tried to fill it before there were any labels (rather when they were still Nothing). The form is a class, it doesnt create the controls until the constructor runs, you try to fill the array when the form initializes. See the link – Ňɏssa Pøngjǣrdenlarp Apr 07 '16 at 14:04
  • You also dont need that Random wrapper/helper. A form level object is all you need. – Ňɏssa Pøngjǣrdenlarp Apr 07 '16 at 14:11
  • Thanks Plutonix for the fast response, I understand. I've placed the variable of aLabel() within the Private Sub BtnSpin_Click and this has sorted the issue. Thanks again for your help! – Charlie Brown Apr 07 '16 at 14:12
  • 1
    There is a dedicated VB answer. I think this is covered under **Forms and Controls** or similar. The concept you are missing is that there is a difference between *declaring* and array and *initializing* it. They can happen at different times - in this case they need to. – Ňɏssa Pøngjǣrdenlarp Apr 07 '16 at 14:14
  • You only need to initialize the array once, not every time the button clicks. move the assignment (`aLabel = {Lbl0,...`) to form load - at that point all the controls have been created – Ňɏssa Pøngjǣrdenlarp Apr 07 '16 at 14:37

0 Answers0