Results 1 to 3 of 3

Thread: add numbers in textboxes

  1. #1

    Thread Starter
    Lively Member
    Join Date
    Mar 2010
    Posts
    78

    add numbers in textboxes

    Hi

    how do I add numbers from two different textboxes, and then show the result into one of them?

    I tried this, but it won't work
    Dim add_box As String
    add_box = txt_box.Text
    Dim derv_total As String
    derv_total = txt_derv_total.Text

    txt_derv_total.Text = derv_total + add_box
    add_box is the box into which the user inputs a new number
    txt_derv_total is the box that will hold the total accumulated.

    thanks

  2. #2
    Super Moderator Shaggy Hiker's Avatar
    Join Date
    Aug 2002
    Location
    Idaho
    Posts
    39,038

    Re: add numbers in textboxes

    Yeah, I'll bet you were a bit surprised by the result of that calculation.

    Textboxes hold strings. You can't add strings, but the + operator is overloaded to perform concatenation on strings. What you were probably hoping would happen would be that the strings would magically turn into numbers and get added. Sometimes that happens, though the magic is an inefficient implicit conversion that you should be avoiding anyways. There are two solutions, either of which is ok:

    1) Use either Integer.TryParse, Decimal.TryParse, or Double.TryParse to convert the string into a number and perform the calculation on the number. This is an explicit conversion, and .TryParse is the only safe way to convert user entered text. There are other, faster, easier, ways to convert a string to a number, but you have to be sure the string can be converted before you can use them, which is something you never know with user entered text. Look up .TryParse for examples. One or more examples are written every day on this forum, so I don't want to bother writing another. MSDN is another good source for an example.

    2) Use NumericUpDown controls rather than textboxes. The NUD only allows numbers to be entered, and the .Value property returns the value as a Decimal, so you don't need to do any conversions.
    My usual boring signature: Nothing

  3. #3
    Addicted Member MetalInquisitor's Avatar
    Join Date
    Sep 2012
    Posts
    143

    Re: add numbers in textboxes

    Maybe you should read about the very basics of VB.NET before starting coding anything.

    http://homeandlearn.co.uk/NET/vbNet.html

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  



Click Here to Expand Forum to Full Width