none
How to add the values of two variables on button click?

    Question

  • I'm relatively new to all of this and am trying to make a simple program that adds a number (that the user enters into a textbox) to a total sum, which is then displayed in another textbox, however all that seems to happen is that the last number I enter is displayed rather than being added and the total being displayed.

    This is the code I'm using;

    Dim Sum As Integer

    Sum = Sum + MoneyTextbox.Text

    TotalTextbox.Text = Sum

    I hope this is the right place to ask this kind of stuff, again new to all of this and this is my first time posting to the forums. 

    I'd appreciate anyone who can help me :)

    Sunday, February 28, 2016 1:36 PM

Answers

  • The first thing you need to do is to transform the text into a numerical value suitable for adding.

    Something like:

    Sum = Sum + Cint(MoneyTextbox.Text)

    However, nothing says the text must be convertible, you need to check if the text is numeric with something like:

            If IsNumeric(MoneyTextbox.Text) = True Then
                Sum = Sum + CInt(MoneyTextbox.Text)
            else
                'It is good form to warn the user that the
                'value is not able to convert into number
                MessageBox.Show("Please enter a valid integer)
            End If

    Also you must start thinking of decimals etc.... and maybe force the textbox to be what you really want, i.e. prevent the decimal sign (.) to be entered.... that's another question :)

    Sunday, February 28, 2016 1:50 PM

All replies

  • The first thing you need to do is to transform the text into a numerical value suitable for adding.

    Something like:

    Sum = Sum + Cint(MoneyTextbox.Text)

    However, nothing says the text must be convertible, you need to check if the text is numeric with something like:

            If IsNumeric(MoneyTextbox.Text) = True Then
                Sum = Sum + CInt(MoneyTextbox.Text)
            else
                'It is good form to warn the user that the
                'value is not able to convert into number
                MessageBox.Show("Please enter a valid integer)
            End If

    Also you must start thinking of decimals etc.... and maybe force the textbox to be what you really want, i.e. prevent the decimal sign (.) to be entered.... that's another question :)

    Sunday, February 28, 2016 1:50 PM
  • Thank you so much! This has fixed everything :)
    Sunday, February 28, 2016 1:53 PM
  • Glad to have helped...mark it as answered and Vote on the post :)
    Sunday, February 28, 2016 1:54 PM