Nicole Erasga
Nicole Erasga

Reputation: 31

Multiple Click Incrementation

I am incrementing a variable (+1) everytime a PictureBox gets clicked but the count is stuck at 1, not going to 2 or 3 or 4 everytime the PictureBox is clicked.

    Dim AddIncrement As Integer
    AddIncrement = AddIncrement + 1
    Dim Menu As String = AddIncrement
    TextBox1.Text = Menu

Upvotes: 0

Views: 62

Answers (1)

Joel Coehoorn
Joel Coehoorn

Reputation: 415735

This is inside a method, right? With a signature that looks something like this:

Private Sub PictureBox1_Click(sender As Object, ByVal e As System.EventArgs) Handles PictureBox1.Click

This may not be 100% exact, but it should be close. So what you really have looks more like this:

Private Sub PictureBox1_Click(sender As Object, e As System.EventArgs) Handles PictureBox1.Click  
    Dim AddIncrement As Integer
    AddIncrement = AddIncrement + 1
    Dim Menu As String = AddIncrement
    TextBox1.Text = Menu
End Sub

Now we need to look at the AddIncrement variable. The Dim statement for this variable is inside the method. That is, it is redefined every time the method runs. Each method call is actually working with a different variable.

To fix it, move the variable declaration outside the method, to be at the Class/Module level:

Private AddIncrement As Integer = 0
Private Sub PictureBox1_Click(sender As Object, e As System.EventArgs) Handles PictureBox1.Click  
    AddIncrement += 1
    TextBox1.Text = AddIncrement.ToString()
End Sub

Upvotes: 1

Related Questions