In VB2017, there are many kind of controls that you can use to build a VB2017 app. In this lesson, we shall only deal with the common controls. Among the common controls are the Label, TextBox, Button, ListBox, ComBox, PitureBox, RadioButton and more. We will work with the text box and the label in this lesson and other controls in coming lessons.
The following program will add the value in textbox 1 and value in textbox 2 and displays the sum in a message box.
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click MsgBox("The sum is "& Val(TextBox1.Text) + Val(TextBox2.Text)) End Sub
The output window:
After clicking Add button, you can get the answer in a message box, as shown in Figure 5.2:
The label can be used to provide instructions and guides to the users as well as to display outputs. It is different from text box because it can only display static text, which means the user cannot change the text. Using the syntax Label.Text, it can display text and numeric data. You can change its text in the properties window and also at runtime.
In this visual basic 2017 program, instead of showing the sum in a message box, we want to display the sum on a label.This is a simple calculator program that can calculate the sum of two numbers entered by the user. To design the interface, you add two text boxes, three labels and a button on the form. Under the respective properties windows, change the name of the first text box to txtNum1 and the name of the second text box to txtNum2. Next, change the text of the first label to +, the text of the second label to =. For the third label, change the autosize property to false and the name to LblAns. Drag the third label to appropriate size and set its background to yellow color. For the button, change its name to BtnCal and its text to Calculate. Lastly, change the text of the form to Simple Calculator. The two text boxes are used to accept inputs from the user. The button is programmed to calculate the sum of the two numbers using the plus operator.
Public Class Form1 Private Sub BtnCal_Click(sender As Object, e As EventArgs) Handles BtnCal.Click Dim num1 As Single = Val(TxtNum1.Text) Dim num2 As Single = Val(TxtNum2.Text) Dim Sum As Single = num1 + num2 LblAns.Text = Sum.ToString End Sub End Class
The Dim keyword is to declare a number as a single precision number and the function Val is to convert a string to a number. The method ToString is to display an output as a string. We shall learn more about Dim in a later lesson.
The output window: