In lesson 3, we have learned how to design the user interface by adding controls to the form and changing their properties. However, the controls on the user interface alone will not work without adding code to them. In this lesson, we shall learn how to write Visual Basic 2015 code for all the controls so that they can interact with events triggered by the users. Before learning how to write Visual Basic 2015 code, let us dwell into the concept of event-driven programming.
4.1 The Concept of Event-Driven Programming
Figure 4.2 shows the events associated with button
4.2 Writing the Code
To start writing code in Visual Basic 2015, click on any part of the form to go into the code window as shown in Figure 4.1. This is the structure of an event procedure. In this case, the event procedure is to load Form1 and it starts with Private Sub and end with End Sub. This procedure includes the Form1 class and the event Load, and they are bind together with an underscore, i.e. Form_Load. It does nothing other than loading an empty form. To make the load event does something, insert the statement
MsgBox (“Welcome to Visual Basic 2015″)
* You will notice that above Private Sub structure there is a preceding keyword Public Class Form1. This is the concept of an object oriented programming language. When we start a windows application in Visual Basic 2015, 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 code to perform arithmetic calculation. For example, you can use the MsgBox and the arithmetic operator plus to perform an addition of two numbers, as shown below:
*The symbol & (ampersand) is to perform string concatenation. The statement Me.Close() is to close the program after clicking the OK button.
The output is as shown in Figure 4.6
We will learn more about code writing in coming lessons