CSC 438 VBPL
CSC 438 VBPL
CSC 438 VBPL
Dr. K. S. Adewole
COURSE SYLLABUS:
Performance Evaluation:
Attendance: compulsory; Assignments: 10%; Test: 30%; Final Examination: 60%.
Bibliography:
1. Foxall, J. (2010). Sams Teach Yourself Visual Basic 2010 in 24 Hours. USA: Pearson
Education, Inc.
2. Visual basic 2010 step by step
https://ptgmedia.pearsoncmg.com/images/9780735626690/samplepages/9780735626
690.pdf
MODULE 1: INTRODUCTION TO VISUAL BASIC PROGRAMMING
Visual Studio 2010 IDE will be used in this course material. The IDE is the design framework
that allows you to develop applications using tools that are accessible from within the VB IDE.
Visual Studio 2010 provides supports for program development with different languages, Visual
Basic being the most popular among these languages. In order to work with VB projects, you
need to first start the Visual Studio 2010 IDE. You can start Visual Studio from the
Start/Program menu just the same way you normally start other applications like Microsoft
Word, Microsoft Excel and so on. You can also start Visual Studio using the shortcut icon on
your desktop. Figure 1.1 shows a typical Visual Studio 2010 startup page.
There are some terms you need to be familiar with before you begin coding in Visual Basic.
These terms are described as follows:
Distributable component: This refers to the final compiled version of your project, which
can be distributed and executed on other computers without the need to install Visual
Studio 2010 development environment. This can often be referred to as program. In this
Unit, you will learn how to build a simple and yet functional application that computes
the area of a circle. You will also learn how to build distributable component for this
application and execute it on another computers.
Project: This is a collection of files that can be compiled to create a distributable
component (i.e program). Visual Basic enables programmers to develop different types of
projects. Programmers can create complex applications that comprise multiple projects,
such as Windows application projects. VB also provides support for dynamic link library
(DLL) projects.
Solution: A solution is a collection of projects and files that make up an application or
component.
VB creates a new Windows Forms Application project as shown in Figure 1.3 and adds one
empty gray form so that you can begin adding controls to your form and build interface for your
application. Form is the term given to the design-time view of a window that can be displayed to
a user.
Figure 1.3 shows the Visual Basic IDE with several windows/components like Project Title,
Solution Explorer, Properties Windows, Form, Menu Bar, Tool Bar, Toolbox and Data Sources.
You can adjust the size and position of any of these windows and you can even hide and show
them as needed from the View menu. The Project Title bar shows the name of the project you are
currently working on. Solution Explorer displays the project name as well as all the files contain
in the project. At this point, we only have Form1.vb file in the project “Area of Circle”.
Properties Windows is a window that can be used to modify the properties of the various
controls/objects you place on the form, including the form itself. The Properties Window on the
right side of the design environment is perhaps the most important window in the IDE, and it is
the one you will use most often. Form is a design-time view of a window where the programmer
places different controls/objects that make up the application interface. Menu Bar allows you to
perform series of operations such as creating new project from the File menu, add additional
Windows Form from the Project menu, start running the current project from the Debug menu
(Start Debugging F5) and so on. Tool Bar provides easy access to Menu Bar items without
necessarily clicking on the individual menu to make use of the specific function. The Toolbox,
when clicked, displays the various controls that can be placed on the form to produce interactive
and user-friendly application. We will discuss these components in the subsequent Units.
Project Title
Menu Bar
Toolbox
Solution
Explorer
Form
Tool Bar
Data
Sources Properties
Window
Object resize
handle
Figure 1.3: New Windows Form Application with empty Form (VB IDE)
1.4 Changing the Characteristics of Objects
Visual Basic programmers work with objects to build interactive and user-friendly applications.
Form itself is an object. Other objects include but not limited to TextBox, Button, CheckBox,
PictureBox and so on. These objects can be accessed through the Toolbox tab as shown in Figure
1.3. Items you can place on a form are called control objects or controls. Some objects did not
have physical appearance but only exist in the code. In Visual Programing, every object has a
distinct set of attributes known as properties. This is regardless of whether the object has
physical appearance or not. Properties define an object‟s characteristics. As human being, you
have certain properties or characteristics, which are unique to you. These may include your
name, height, weight, skin colour, hair type, and so on. Every object possesses some forms of
unique attributes. Visual Basic objects have properties as well, such as Name, Text, Height and
BackColor. When you create a new object in VB, you need to first adjust its properties through
the Properties Window. To access object properties, click on the object on the form.
Current object
Order of selected
arrangement
Properties of the
selected object
Figure 1.4
Changing the form’s title icon
The form icon is the picture displays at the left-hand side of the title of a window form. To
change this picture, click on the icon property in the Properties Window and use the Open File
dialog to locate and change the icon for the form.
1. Click on File > Save All or Click the Save All icon ( ) on the Tool Bar.
2. In the Save Project dialog box (see Figure 1.5), browse the location where you would like
to save your new project. Then, click the Save button.
Coding environment
When you double-click a control on a form in the design view, the default event for that control
is displayed in a code window as shown in Figure 1.8. The default event for a Button control is
its Click event, which makes sense; because clicking is the most common action a user performs
with a button. The default event varies according to the control that is currently selected. Note
that the type of event can be changed from the top right-hand corner of the code window while
the box at the top left-hand corner can be used to change the object or control.
Write the following code under the Click event of the CmdCalculate command button. Notice
the use of „ symbol for comment. Comment can be inserted anywhere in the code to improve
code readability. For instance, code „displaying the result in the textbox txtArea is a comment
which is not executed by the VB compiler. The keyword Const defines a constant PI as double
precision floating-point data type and assigned the value of 3.142 to it. The operator = is used as
assignment operator. Dim (i.e dimension) keyword allocates memory storage for the variable r
and area, which are both of double precision floating-point data. The first two lines of the codes
are data type declaration statements. The third line r = txtRadius.Text takes the value of radius
that the user enters in the textbox txtRadius and assign it to variable r. The forth line computes
the value for area of circle using the value in variable r and PI. Finally, the result of the
computation is displayed in the textbox txtArea via its Text property.
You switch between the design view and code view by clicking on the View menu as shown in
Figure 1.9. You can also make use of the shortcuts at the top right-hand side of the Solution
Explorer.
Shortcut to
switch
between code
and design
views
Debug builds are created automatically by Visual Studio when you create and test your program.
They are stored in a folder called Bin\Debug within your project folder as shown in Figure 1.11.
The debug executable file contains debugging information that makes the program run slightly
slower.
Figure 1.11: Showing debug executable file automatically created by Visual Studio
The Release builds are optimized executable files stored in the Bin\Release folder within your
Project folder. When you are sure that all errors have been fixed, you can change the build
settings. To customize the settings for your build option, you need to right-click the project name
in the Solution Explorer e.g “Area of Circle” and the click on the Properties in the context-menu.
This will display the interface shown in Figure 1.12. Notice that the compile tab is currently
selected and the current build folder is Bin\Debug.
You can also run Windows applications, including compiled Visual Basic programs (i.e the
executable file), by opening Windows Explorer and double-clicking the executable file. You can
create a shortcut icon on the Desktop for the executable file.
Standard
Toolbar
1. In the toolbox, click the icon or tool representing the control that you want to place on a
form, and then click and drag on the form where you want the control placed.
2. Double-click the desired control type in the toolbox. A new control of the selected type is
placed in the upper-left corner of the form if the form is selected. If the control is a
runtime-only control, such as the OpenFileDialog control, it will only appear below the
form.
3. You can drag a control from the toolbox and drop it on a form. If you hover the mouse
pointer over the form for a second, the toolbox disappears, and you can drop the control
on the form anywhere you want.
4. Right-click an existing control and choose Copy; then right-click the form and choose
Paste to create a duplicate of the control on the form.
2.5 Setting Object Properties Using the Properties Window
As discussed earlier, Visual Basic, through the Properties window, allows you to customize the
properties of any object. During the interface development for your projects, you will spend a lot
of time viewing and setting object properties in the Properties window. As shown in Figure 1.16,
Properties window contains three important components: (i) An object drop-down list (ii) A list
of properties (iii) A set of tool buttons or icons used to change the appearance of the properties
grid; and (iv) A section showing a description of the selected property (see Figure 1.16).
Figure 1.17: Using the drop-down list of the Properties window to select and view object
properties
For instance, let us change some properties of the form control. First, change the background
colour of the form control to blue. To do this, simply locate the BackColor property in the
Properties window and select blue color from the pop-up box containig varieties of colours as
shown in Figure 1.18.
Colour
box
Second, we change the text colour of the txtRadius to red. To do this, you will either select
txtRadius from the drop-down box of the Properties window or select txtRadius control on the
form during the design view and change the ForeColor property to red. Third, we change the
background colour of the two command buttons CmdCalculate and CmdClose to light green. To
do this, simply change the BackColor properties for the two buttons from the Properties window.
Lastly, we change the font size of the text that will be displayed in the txtArea to 14pt. This is
done using the Font property of the txtArea, which displays the font dialog box shown in Figure
1.19.
Figure 1.19: Changing control font, font style, and font size using the Font dialog box
Figure 1.20: Customizing controls properties for the “Area of Circle” project
Notice that colour drop-down box (see Figure 1.18) is composed of three tabs: Custom, Web,
and System. Most colour properties use a system color by default. In Visual Basic, colours are
expressed as a set of three numbers, each having a value from 0 to 255. A given set of numbers
represents the red, green, and blue (RGB) components of a color, respectively. The value
0,255,0, for instance, denotes pure green colour, whereas the value 0,0,0 represents black and
255,255,255 represents white.
The following is a list of some of the components you might use in your projects:
Modules: enable you to store code procedures without needing a specific form to attach
them to. For instance, you might want to define custom procedures or subroutines that
achieve specific tasks and can be called or invoked within your project in a module. E.g
adding a subroutine to connect to your database server.
A class modules: is a special type of module that enables you to create object-oriented
applications. In this course material, you will learn how to program using an object-
oriented language (i.e Visual Basic), but mostly you will learn how to use objects or
controls supplied by Visual Basic. In Module 4, you will learn how to use class module to
create your own objects.
Forms: are the visual windows that make up your application‟s interface. A special type
of class module is used to define forms.
Controls: These include the controls supplied by Visual Basic as well as user created
controls.
When you follow any of the three steps above, a dialog box shown in Figure 1.25 will appear
where you can chose the type of object to add to your project. Simply name the object and click
Open to create a new object of the selected type. To create an object of a different type, click the
type to select it, name it, and then click Open.
Figure 1.24: Adding item through the Project name in the Solution Explorer
Figure 1.25: Add New Item dialog box
4. Next is to write the codes below under the two command buttons.
5. Now run your project. You will notice that the first form FrmArea is still the form
window displayed to you. This occurred because Visual Basic has automatically set your
first form as the project Startup form. To change the project Startup form, click on
Project menu and click the project properties, which is usually the last menu item under
the Project menu (see Figure 1.26). In the Properties window (see Figure 1.27), click on
Application tab and change the Startup form to FrmGuess.
Accessing project
properties
6. Now run your application and try your guess. See Figure 1.28 for a sample guess output.
Points to Note
The line of code compFirstNum = Int(Rnd() * 10) instructed the computer to generate a random
number from 0 to 9. This number is then assigned to the variable comFirstNum, which denotes
the first number generated by the computer. You can actually make Visual Basic generate
unpredictable numbers within specific guidelines; in other words, you can create random
numbers for lottery contests, dice games, or other statistical patterns. The Rnd function in the
codes creates a random number between 0 and 1 (a number with a decimal point and several
decimal places), and the Int function returns the integer portion of the result of multiplying the
random number by 10. Therefore, this computation creates random numbers between 0 and 9 in
the program. The values randomly generated with this statement are then tested against the user‟s
inputs using the If statement. The result of the test is displayed in the RichTextBox rtbOutput.
The ampersand (&) character is used for in Visual Basic for concatenation in order to create the
output string.
Car
- Model
- NumberPlate
- Color
- EngineNumber
- ChasisNumber
Figure 1.29: Showing properties of a car object
ObjectName.Property
For instance, suppose you would like to reference the Text property of a Form named FrmArea,
then you can write:
FrmArea.Text
This line of code would return whatever was contained in the Text property of the form
FrmArea. If you would like to store the value that you just returned inside a variable, you could
write:
Dim myText As String
myText = FrmArea.Text
These statements first allocate a memory location for your variable myText and then assigned
whatever value was stored in the Text property of the FrmArea. Similarly, to set a property to
some value, you use an equal sign (=). For instance, to change the value of the Text property of
FrmArea, we could write:
Figure 1.30 shows the IntelliSense or auto-completion drop-down list in the coding area. This
drop-down list allows you to access any property or method of your object. We will discuss
methods in the subsequent section. You can press the spacebar on your keyboard to accept the
highlighted property or method from the IntelliSense drop-down list. In the figure, Me refers to
FrmArea. Alternatively, you can type FrmArea instead of Me. You will get the same result. Also,
notice the event FrmArea_Load which specifies that the codes should execute once the form
FrmArea is loaded or displayed at run-time.
Figure 1.30: Using IntelliSense or auto-completion drop-down list to access property or method
of an object.
- Model
- NumberPlate
- Color
- EngineNumber
- ChasisNumber
+accelerate()
+stop()
+move()
+receiveFuel()
ObjectName.Method
For example, to access the methods of an object, say myCar of a type Car, we could write:
myCar.accelerate()
Method can accept arguments or parameters, which are the items the method will use to achieve
its task. For instance, the method receiveFuel of a myCar object could receive the litre of fuel
that the car owner just bought. Thus, it is very important to first find out the methods that an
object supports and how to use those methods.
Now that you have inserted additional button, we will write the code under this button Click
event. To do this, simply double-click the button to open the code view. Type the following code
under the Click event of the CmdDraw:
The first line of code creates an object (objGraphics) of type Graphics. The process of creating
an instance of an object is called instantiation. To instantiate an object in code, you create a
variable that holds a reference to an instantiated object. In the case of our example, objGraphics
is the variable created that holds the reference. In the second line of the code, CreateGraphics is a
method of the form. Recall that the keyword Me refers to the current form, which in our case, it
is FrmGuess. The method, CreateGraphics, instantiates a new object that represents the client
area of the current form. The client area is the gray area within a form‟s borders and title bar.
Anything drawn on the objGraphics appears on the form. The third line of the code clears the
form‟s background using whatever color the user has selected as the Windows Control color.
The forth line of the code uses the DrawRectangle() method of our newly created object
(objGraphics) to draw border around the specified area. Since our goal is to draw the border
around the RichTextBox rtbOutput, specify the left, top, width and height of the border area.
Notice the use of the Pen colour Red. This is the colour that will be used for the border line of
the rectangle. Finally, the Dispose() method of our object objGraphics is called to clean up any
memory effect. This is necessary because object may use other object or resources. Call to the
Dispose() method frees any resources the object might be holding. If an object is not properly
disposed, you can create a memory leak within your application that slowly or rather quickly
munches system memory and resources, and can slow down the processing speed of your
system.
You can now run your project and test the Click event of the CmdDraw. Figure 1.32 shows a
sample output. Notice the red border drawn around the RichTextBox.
Let us now look at some of the events supported by a command button in Visual Basic. To check
these events, simply double-click a particular button on the form (e.g CmdCalculate on
FrmArea) to access the coding area for the button click event. Then, click on the combo box at
the top right-hand corner to access other event of the selected button. Figure 1.33 shows some of
the typical events supported by a button. Notice also that the default Click event appears in bold.
From this combo box, you can select other event from the list and insert the code for the selected
event; just the same way you did for the default Click event.
The item following the ByVal keyword is the name of the parameter, and the string after the
word. The two parameters in our example of the Click event of a button are sender and e.
The first parameter, sender, holds a generic object. Object parameters can be any type of object
supported by Visual Basic. The sender parameter holds a reference to the control or object that
causes the event to be triggered. The e parameter of the Click event holds the detailed
information about the event. The e parameter also holds an object, and in this case the object is
of type System.EventArgs. This object has properties that relate to the Click event. Figure 1.34
shows how to access the properties of an event's parameter. As you can see from the figure,
typing the name of the event parameter (in this case e) followed by the dot (.) causes the
properties of the event to be listed in the drop-down list. The items in this drop-down list is not
only limited to the properties of the event but also include the methods.