-1

I am having trouble getting some code to find a variable that I declare when the form opens. Here is my code:

Public Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
    Dim test As Double
    test = 1
End Sub
Public Sub Button2_Click(sender As Object, e As EventArgs) Handles Button2.Click
If test = 1 Then
        PictureBox1.Image = My.Resources.cbreak1
        test = 2
End If

Can anyone help me?

JezzaProto
  • 13
  • 5
  • 1
    test is declared within the method so it can't be referenced out of it. Its a context variable. At the end of the sub, test is destroyed. – Alessandro Mandelli Oct 31 '18 at 17:47
  • This is what's known as _Scope_ (in your case _Method Scope_ or _Procedure Scope_), which is very fundamental programming. I highly recommend you read up on how it works: [Scope in Visual Basic | Microsoft Docs](https://learn.microsoft.com/en-us/dotnet/visual-basic/programming-guide/language-features/declared-elements/scope) – Visual Vincent Oct 31 '18 at 22:03

1 Answers1

2

Your variable "test" is declared inside the method, it does not exist outside of it. If you need to, you have to declare it as part of the class.

Dim test As Double

Public Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
    test = 1
End Sub

Public Sub Button2_Click(sender As Object, e As EventArgs) Handles Button2.Click
    If test = 1 Then
        PictureBox1.Image = My.Resources.cbreak1
        test = 2
    End If
End Sub

As tempting as it might be, try not to declare all your variable in the class. In your case, it could just be a static variable.

the_lotus
  • 12,668
  • 3
  • 36
  • 53