I had named the user interface controls:
Private Sub btnAdd_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnAdd.Click lblSum.Text = txtFirstNumber.Text + txtSecondNumber.Text End Sub
The problem is that txtFirstNumber.Text + txtSecondNumber.Text is a string expression, so the numbers the user entered were treated as strings and concatenated instead of being added. (VB treats the + operator as a synonym for &).
I needed a way to convert the data types of the inputs from string to numeric. VB.NET has a number of intrinsic (built-in) functions for converting data from one type to another. One of those is the CInt function which converts string data to numeric data. I modified the event handler to convert the string input to numeric data as follows:
That seemed reasonable, but it introduced a syntax error. I now had a numeric expression on the right hand side of the assignment statement and the Text property on the left hand side is a string.Private Sub btnAdd_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnAdd.Click lblSum.Text = CInt(txtFirstNumber.Text) + CInt(txtSecondNumber.Text) End Sub
To fix that error, I used the CStr function to convert the type of the result to a string before assigning it to lblSum.Text.
The addition program worked after that change was made.Private Sub btnAdd_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnAdd.Click lblSum.Text = CStr(CInt(txtFirstNumber.Text) + CInt(txtSecondNumber.Text)) End Sub
We have seen two VB.NET functions for data type conversion:
VB has several functions for data type conversion, including the following:CInt(<string expression>)andCStr(<numeric expression>)
Type | Conversion function |
Byte | CByte |
Short | CShort |
Integer | CInt |
Long | CLng |
Single precision | CSng |
Double precision | CDbl |
String | CStr |
Note that even with Option Strict On, some automatic type conversions are allowed. For example, if you write:
Dim A as single Dim B as double A = B B = AA = B has a syntax error because you are trying to convert a double precision number to single precision. Like putting a big foot in a small shoe.
B = A is OK because no information is lost when you convert a single precision number to double precision. A small foot has plenty of room in a big shoe -- no information is lost.