1.11M Members

Adding the results of two text boxes (Visual Basic Express Edition)

 
0
 

I know I'm just missing the mark here, but what I am trying to accomplish is simply adding the results of two text boxes.

Example:
Form has two text boxes and 1 label
The user enters a number (any number from 0 - 10) into each textbox
when the user 'leaves' textbox2, label1 is updated with the total of adding textbox1 and textbox2 together

My Code:

PublicClass Form1
Private Sub TextBox2_Leave(ByVal sender As Object, ByVal e As System.EventArgs) Handles TextBox2.Leave
Label1.Text = TextBox1.Text + TextBox2.Text
End Sub
EndClass

Given my current code, when I enter a 2 in textbox1 and a 3 in textbox2, Label1 updates to show 23 (while I can see WHY that happens, thats not what I was hoping for). I know I'm missing something, just not sure "what". Any help is appreciated. (and yes, I am a VB noob)

 
0
 

You'll need to convert the value of the text fields into numbers before performing the addition operation. Currently you are adding two strings of text, which concatenates them.

 
0
 

how would i go about doing that please?

 
0
 

Search your IDE's help, or failing that Google. These should be your first port of call before a forum. Try the format "[language type]" "[what you are trying to do]". For example "Visual Basic" "convert string to int".
You could even try going through a tutorial, there will be one included with your IDE.

 
1
 

There are several ways.
1. Dim x As Integer = CInt(TextBox1.Text)
2. Dim y As Integer = Val(TextBox1.Text)
3. Dim z As Integer = CType(TextBox1.Text, Integer)
If you are working with hexidecimal or octal then use val because it knows what &h and &o means. The others throw an error. Also is the only one that if you put it in a label (textbox) then "123.45" will appear as "123.45". If you do as shown above then y is defined as an integer so will only show as "123".
So, I would do this as I would not know what will be placed in the textboxes:

Label1.Text = TextBox1.Text + TextBox2.Text

would be

Label1.Text = Val(TextBox1.Text) + Val(TextBox2.Text)
 
0
 

DavidRyan: I just wasn't sure what the proper phrasing was to do a google search, but you are correct in that sense.

Waynespangler: Thank you for that informative example, I will give it a shot. The only things that will be put into the boxes are whole numbers from 0 to 10 (its a bowling score system). Haven't totally decided how to treat the full math aspect of it as yet, but gotta crawl before you walk. :)

You
This article has been dead for over six months: Start a new discussion instead
Post:
Start New Discussion
Tags Related to this Article