Search code examples
variablesbuttonglobaldeclare

Declare Global Variable inside a Button1_Click


I tried to google this abit but I could'nt find anything useful. So I in my form1_load I have this variable

Dim Myvariable As String

then in a button click I want

Myvariable = "Hello"

Problem is that my code tells me that Myvariable in the button_click is not declared which it is.

Thanks for any help.


Solution

  • Move variable as a field or property in Your form class. Here is example code:

    Public Class Form1
        Private MyVariable
    
        Private Sub Form1_Load(sender As System.Object, e As System.EventArgs) Handles MyBase.Load
            MyVariable = "Hello"
        End Sub
    
        Private Sub Button1_Click(sender As System.Object, e As System.EventArgs) Handles Button1.Click
            MessageBox.Show(MyVariable)
        End Sub
    End Class