[Lesson 3] << [Contents] >> [Lesson 5]
In preceding lesson, you have learned how to design the user interface by inserting controls to the form and changing their properties. However, the controls will not function without adding VB code to them. In this lesson, we shall learn how to write VB code for all the controls so that they can interact with events triggered by the users. Before learning how to write VB code , let me explain the concept of event-driven programming
4.1 The Concept of Event-Driven Programming
Figure 4.1: Events associated with Form
Figure 4.2 shows the events associated with button
4.2 Writing the VB Code
When you run the program, a message box that displays the text “My First Visual Basic 2013 Program” will appear, as shown in Figure 4.3. MsgBox is a built-in function in Visual Basic 2013 that displays a message in a pop-up message box.
* You will notice that above Private Sub structure there is a preceding keyword Public Class Form1. This is the concept of object oriented programming language. When we start a windows application in Visual Basic 2013, we will see a default form with the name Form1 appears in the IDE, it is actually the Form1 Class that inherits from the Form class System.Windows.Forms.Form. A class has events as it creates an instant of a class or an object.
You can also write VB code to perform arithmetic calculations. For example, you can use the MsgBox and the arithmetic operator plus to perform an addition of two numbers, as shown below:
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.LoadMsgBox(“2” & “+” & “5” & “=” & 2 + 5)End Sub
*The symbol & (ampersand) is to perform string concatenation.
The output is as shown in Figure 4.4
If you wish to close the window after the message, you can add the statement Me.Close(), as follows:
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
MsgBox(“2” & “+” & “5” & “=” & 2 + 5)
We will learn more about code writing in coming lessons