• 0

[VB.NET] How to make an integer value add up / down using buttons?


Question

So basically I have a label and 2 buttons. Button A adds up 1 and button B subtracts 1.

I can't figure out why when you press the button it doesn't continue to add up / subtract down every time you press the button.

HELLLLLLLLLLLLLLLLLLP!

EDIT: I know I said integer in topic name, its supposed to be double but yeah same problem none the less.


Private Sub btnAddReg_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnAddReg.Click
' Add Regular
Dim dblRegTot As Double
dblRegTot = dblRegTot + 1
lblRegular.Text = CStr(dblRegTot)
End Sub
Private Sub btnRemReg_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnRemReg.Click
' Remove Regular
Dim dblRegTot As Double
dblRegTot = dblRegTot - 1
lblRegular.Text = CStr(dblRegTot)
End Sub
[/CODE]

4 answers to this question

Recommended Posts

  • 0

Your variables called dblRegTot are local to the function they're declared. They only exist for the duration of the function. Also, even though they have the same name, the one declared in btnAddReg_Click is a completely different variable from the one declared in btnRemReg_Click.

You need to use a variable - just one - that exists outside the functions, at the class level. That way, the value is preserved between calls to functions, and all functions within the class can add or substract to that variable. i.e.:


Public Class YourForm
Private dblRegTot = 0.0
Private Sub btnAddReg_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnAddReg.Click
' Add Regular'
dblRegTot = dblRegTot + 1
lblRegular.Text = CStr(dblRegTot)
End Sub
Private Sub btnRemReg_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnRemReg.Click
' Remove Regular'
dblRegTot = dblRegTot - 1
lblRegular.Text = CStr(dblRegTot)
End Sub
End Class
[/CODE]

  • 0
  On 13/12/2011 at 00:17, Stoffel said:

Because dblRegTot gets reset to 0 every time you run the Sub

If you would take the value of lblRegular and add or subtract 1 from that it will work

Yes!

That worked! Thank you much!

  On 13/12/2011 at 00:23, Dr_Asik said:

Your variables called dblRegTot are local to the function they're declared. They only exist for the duration of the function. Also, even though they have the same name, the one declared in btnAddReg_Click is a completely different variable from the one declared in btnRemReg_Click.

You need to use a variable - just one - that exists outside the functions, at the class level. That way, the value is preserved between calls to functions, and all functions within the class can add or substract to that variable.

Yes, I was going to do this. I just wanted to simplify this question but you guys both helped out a lot.

This topic is now closed to further replies.
  • Recently Browsing   0 members

    • No registered users viewing this page.