Zebra0.com

visual-basic variables

Let's suppose we want a program that will count the number of times you click a button.
The code shown below will not work because the value of counter is reset to 0 each time the function executes.

Public Class Form1
    Private Sub BtnCounter_Click(sender As Object, e As EventArgs) Handles BtnCounter.Click
        Dim counter As Integer = 0
        counter += 1
        Me.Text = counter
    End Sub
End Class

Instead, we need to declare the variable as static so that the value is maintained throughout the execvution of the program:

Public Class Form1
    Private Sub BtnCounter_Click(sender As Object, e As EventArgs) Handles BtnCounter.Click
        Static counter As Integer = 0
        counter += 1
        Me.Text = counter
    End Sub
End Class

NEXT: Variables