The Text property of a TextBox or Label contains the value that we see in the control. These values are Strings, which are stored in ASCII. These values can be copied directly into and from String variables in an event procedure, since String variables are also stored in ASCII. For example, given the following form:
with TextBoxes named txtFirst and txtLast, and Label lblFull, we can write the following code:
Private Sub btnOK_Click(...) Handles btnOK.Click Dim first As String Dim last As String Dim full As String first = txtFirst.Text last = txtLast.Text full = first & " " & last lblFull.Text = full End Sub
Notice that we can copy the values from the TextBoxes directly into String variables. We use the concatenation operator & to create a new String which contains the first name, then a blank, then the last name. We can copy this new String directly from the variable to the Label in the form.
Numeric variables (Integer and Double) are stored in as binary numbers. Their values are not stored in ASCII like String variables. The Text property of a TextBox or Label can be a number, but it is still stored in ASCII. The Text property must be converted to numeric format (binary) when we copy it into a numeric variable. To convert a value from String to Integer we use the CInt function. To convert a value from String to Double, we use the CDbl function.
Similarly, if we have a numeric variable, and we want to display its value in a TextBox or Label, we must convert the value from binary to ASCII. To convert a value from a numeric form (either Integer or Double) to String, we use the CStr function. For example, given the following form:
with TextBoxes named txtNum1, txtNum2 and txtNum3, and Label lblSum, we can write the following code:
Private Sub btnOK_Click(...) Handles btnOK.Click Dim num1 As Integer Dim num2 As Integer Dim num3 As Double Dim sum As Double num1 = CInt(txtNum1.Text) num2 = CInt(txtNum2.Text) num3 = CDbl(txtNum3.Text) sum = num1 + num2 + num3 lblSum.Text = CStr(sum) End Sub
Email Me |
Office Hours |
My Home Page |
Department Home |
MCC Home Page
© Copyright Emmi Schatz 2007