-1

how do I keep my variable working when I Click Button1? Can someone help me?

Public Class Form2
    Private Sub Form2_Load(sender As Object, e As EventArgs) Handles MyBase.Load
        Dim Number As Integer
        Randomize()
        Number = Int(Rnd() * 10000000) + 1
        Label2.Text = Number
    End Sub
    Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
        If TextBox1.Text = Number Then
            MsgBox("Correct")
        Else
            MsgBox("Not Correct")
        End If
    End Sub
End Class
  • 3
    `Dim Number As Integer` should be a field of the class `Form2` – Tim Schmelter Oct 15 '18 at 14:33
  • Don't use `Randomize` and `Rnd` in VB.NET. Create an instance of the `Random` class and call its `Next` method. Also, you reallu ought to turn `Option Strict On`, both in the project properties and the IDE options, so that it is `On` by default in future projects. – jmcilhinney Oct 15 '18 at 15:15
  • The word that no one has mentioned yet is "member". You should be declaring a member variable, also known as a field, rather than a local variable, i.e. declare it outside of any method so that it can be seen from all methods. You should do some reading on scope. When something is declared inside a block then it can only be seen inside that block. – jmcilhinney Oct 15 '18 at 15:16

1 Answers1

4

Take your variable and move it as a class variable.

Public Class Form2
    Private Number As Integer ' <-----

    Private Sub Form2_Load(sender As Object, e As EventArgs) Handles MyBase.Load
        Randomize()
        Number = Int(Rnd() * 10000000) + 1
        Label2.Text = Number
    End Sub

    Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
        If TextBox1.Text = Number Then
            MsgBox("Correct")
        Else
            MsgBox("Not Correct")
        End If
    End Sub

End Class

With your example, it seems reasonable to do that but I suggest you don't take the habit of doing it to much. I've seen people put almost everything as class variable.

Also, put Option Strict On. It'll save you some headache in the future, as your program gets more complex.

the_lotus
  • 12,668
  • 3
  • 36
  • 53