Search code examples
vb.netnumericupdown

Visual Basic How would I Increment and Decrement a variable with 3 NumericUpDown component (Or Another Method)?


So this is currently what I have on a form:

form

An example of a users input : (E.g NumericUpDown1 = 3, NumericUpDown2 = 1, NumericUpDown3 = 3)

An example of the computer output : (Points left would = 2, Reasoning : 9- (3+1+3) = 2)

What I want to do with these components is every time "up" is pressed on a NumericUpDown I want the points variable to decrease by 1 ( Vise-Versa when down is pressed). The major problem I face is I don't know how to check if a NumericUpDown has been pressed up or down.

If you guys know of a different and better way to do this ill 100% be trying that because this way looks horrible.


Solution

  • Just like other controls the NumericUpDown has events that can contain your code. The ValueChanged event should work as long as the user uses the up down arrows since the event fires when the user presses these arrows. However, the user can type in an amount in and the event will not fire until the user clicks somewhere else on the form. So you might want to move the code to a button "Update Points" instead of the ValueChanged event.

    Private Sub NumericUpDowns_ValueChanged(sender As Object, e As EventArgs) Handles NumericUpDown1.ValueChanged, NumericUpDown2.ValueChanged, NumericUpDown3.ValueChanged
            Dim pointsAvailable = CInt(lblPoints.Text)
            Dim pointsUsed = NumericUpDown1.Value + NumericUpDown2.Value + NumericUpDown3.Value
            lblPoints.Text = (pointsAvailable - pointsUsed).ToString
    End Sub