VB -> Adding Numbers

  • Thread starter Thread starter Hareth
  • Start date Start date
H

Hareth

Scenerio:

label1.text = 0
textbox1.text = 0

textbox2.text = textbox1.text + label1.text

It turns out it isnt adding the numbers, it attaches the new number next to
the old number

if label1.text = 1 then textbox1 is = 2 then 1+2 = 3 ....it writes 1+2= 12
INSTEAD of 3
 
Hi,

The + operator in VB adds variables according to their types, not their
values. You are adding two strings together so it concatenates them. To do
what you want use:

textbox2.text = CStr(CInt(textbox1.text) + CInt(label1.text))

Be sure to specifiy Option Explicit On and Option Strict On at the top of
your code file so the IDE can tell you when you are doing something illegal
or weird. Like trying to add a string to an integer. Good luck! Ken.
 
Hareth said:
label1.text = 0
textbox1.text = 0

textbox2.text = textbox1.text + label1.text

It turns out it isnt adding the numbers, it attaches the new number next to
the old number

Add these lines on top of your source file:

\\\
Option Explicit On
Option Strict On
///

Then use this code:

\\\
Label1.Text = CStr(0)
TextBox1.Text = CStr(0)
TextBox2.Text = CStr(CInt(TextBox1.Text) + CInt(Label1.Text))
///

The labels' 'Text' property is of type string, and '+' will be used as
string concatenation operator when dealing with strings.
 
This is probably the most fundamental thing to understand about data types.
When you type into a textbox, no matter what you type, it is treated as text
(string) since you typed it into a "text"box. When you use the "+" operand,
it is treated as string addition (concatenation), rather than numeric
addition.

You need to convert the values to a numeric type before doing the math. You
should also check to see IF the values typed into the textboxes are, in
fact, numeric BEFORE you attempt to convert them, since "Green" doesn't
convert to a numeral. VS.NET's range or regular expression validators can
ensure that only numerals are entered.
 
Hey Herfried,

Something tells me our code looks a lot alike! Ken.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Back
Top