In Visual Basic 2022, there are many kinds of controls that you can use to build a VB 2022 app. The controls can be categorised into Common Controls, Containers, Menus and Toolbar, Data, Components, Printing, Dialogs and WPF Interoperability. We shall only deal with the TextBox and the Label in this lesson.
TextBox is for accepting input from the user as well as to display the output. It can handle string and numeric data but not images or pictures. String in a text box can be converted to a numeric data by using the function Val(text).
In this application, add two text boxes and a button to the Form. Change the text of the button to ADD. Next, click on the button and enter the following code:
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
This program will add the value in TextBox1 and the value in TextBox2 and displays the sum in a message box.
The output UI is as shown in Figure 5.1.
After clicking the Add button, you will get the answer in a message box, as shown in Figure 5.2.
Label is used for multiple purposes like providing instructions and guides to the users, displaying outputs and more. It is different from the TextBox because it is read only, which means the user cannot edit its content at runtime. Using the syntax Label.Text, it can display string as well as numeric data. You can change its text property in the properties window or at runtime by writing an appropriate code.
Based on Example 5.1, we add two Labels, one is for displaying the text Sum= and the other Label is to display the answer of the Sum. For the first Label, change the text property of the label by typing Sum= over the default text Label1. Further, change its font to bold and its font size to 10. For the second label, delete the default text Label2 and change its font to bold and the font size to 10. Besides that, change its background color to white. In this program, instead of showing the sum in a message box, we display the sum on the Label.
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click LblSum.Text = Val(TextBox1.Text) + Val(TextBox2.Text) End Sub
*The function Val is to convert text to numeric value. Without using Val, you will see that two numbers are joined without adding them.