CSC 438 VBPL

Download as pdf or txt
Download as pdf or txt
You are on page 1of 37

CSC 438: Visual Programming (2 credits)

Dr. K. S. Adewole
COURSE SYLLABUS:

MODULE 1: INTRODUCTION TO VISUAL BASIC PROGRAMMING


UNIT 1: VISUAL BASIC PROGRAMMING TOUR
UNIT 2: NAVIGATING VISUAL BASIC IDE
UNIT 3: UNDERSTANDING OBJECTS AND COLLECTIONS
UNIT 4: UNDERSTANDING EVENTS

MODULE 2: BUILDING A USER INTERFACE


UNIT 1: BUILDING FORMS
UNIT 2: WORKING WITH TRADITIONAL CONTROLS
UNIT 3: WORKING WITH ADVANCED CONTROLS
UNIT 4: ADDING MENUS AND TOOLBARS TO FORMS

MODULE 3: PROGRAMMING CONCEPTS


UNIT 1: CREATING AND CALLING CODE PROCEDURES
UNIT 2: USING CONSTANTS, DATA TYPES, VARIABLE, AND ARRAYS
UNIT 3: ARITHMETIC OPERATIONS, STRING MANIPULATION, AND DATE/TIME
UNIT 4: CONTROL STRUCTURES IN VISUAL BASIC

MODULE 4: USER INTERACTION, CLASSES AND DEBUGGING


UNIT 1: INTERACTING WITH USER
UNIT 2: DESIGNING OBJECTS USING CLASSES
UNIT 3: CODES DEBUGGING

MODULE 5: WORKING WITH DATA


UNIT 1: FILE OPERATIONS
UNIT 2: WORKING WITH REGISTRY AND TEXT FILES
UNIT 3: WORKING WITH DATABASE
UNIT 4: WORKING WITH REPORTS
MODULE 1: INTRODUCTION TO VISUAL BASIC PROGRAMMING

UNIT 1: VISUAL BASIC PROGRAMMING TOUR


Starting Visual Basic
Creating a New Project
Understanding Visual Studio Environment
Changing the Characteristics of Objects
Adding Controls to a Form
Designing the Interface
Working with Codes behind an Interface
Running a Project
Creating Executable File

UNIT 2: NAVIGATING VISUAL BASIC IDE


Opening an Existing Project
Showing and Hiding Design Windows
Working with Toolbars
Adding Controls to a Form Using the Toolbox
Setting Object Properties Using the Properties Window
Managing Projects
Working with Solution

UNIT 3: UNDERSTANDING OBJECTS AND COLLECTIONS


Understanding Objects
Understanding Properties
Understanding Methods
Building a Simple Object
Understanding Collections

UNIT 4: UNDERSTANDING EVENTS


Event-Driven Programming
Accessing an object‟s event
Working with Event Parameters

MODULE 2: BUILDING A USER INTERFACE

UNIT 1: BUILDING FORMS


Working with Forms
Creating Topmost Nonmodal Windows
Creating Transparent Forms
Creating Scrollable Forms
Creating MDI Forms

UNIT 2: WORKING WITH TRADITIONAL CONTROLS


Static Text with Label Control
Textbox for User Input
Creating Buttons
Creating Containers and Groups of Option Buttons
Using Checkbox
List with Listbox
Drop-Down List with Combo Box

UNIT 3: WORKING WITH ADVANCED CONTROLS


Creating Timers
Creating Tabbed Dialog Boxes
Working with Image List Control
Working with List View Control
Working with Tree View Control
Working with Progress Bar

UNIT 4: ADDING MENUS AND TOOLBARS TO FORMS


Building Menus
Using the Toolbar Control
Creating Status Bar

MODULE 3: PROGRAMMING CONCEPTS

UNIT 1: CREATING AND CALLING CODE PROCEDURES


Creating Code Modules
Writing Code Procedures
Calling Code Procedures
Existing Procedures

UNIT 2: USING CONSTANTS, DATA TYPES, VARIABLE, AND ARRAYS


Understanding Data Types in Visual Basic
Defining and Using Constants
Declaring and Referencing Variables
Working with Arrays
Determining Scope
Declaring Variables of Static Scope
Naming Conventions

UNIT 3: ARITHMETIC OPERATIONS, STRING MANIPULATION, AND


DATE/TIME
Basic Arithmetic Operations
Comparing Equalities
Understanding Boolean Logic
Manipulating Strings
Working with Dates and Times
UNIT 4: CONTROL STRUCTURES IN VISUAL BASIC
Making Decision with If...Then
Using GoTo
Looping with For...Next
Looping with Do...Loop

MODULE 4: USER INTERACTION, CLASSES AND DEBUGGING

UNIT 1: INTERACTING WITH USER


Working with MessageBox
Creating Custom Dialog Boxes
Using InputBox
Interacting with the Keyboard
Using Mouse Events

UNIT 2: DESIGNING OBJECTS USING CLASSES


Understanding Classes
Instantiating Objects from Classes

UNIT 3: CODES DEBUGGING


Adding Comments to Your Code
Identifying the Two Basic Types of Errors
Working with Debugging Tools
Error Handling with Try...Catch...Finally

MODULE 5: WORKING WITH DATA

UNIT 1: FILE OPERATIONS


Using OpenFileDialog and SaveFileDialog Controls
Files Manipulation with File Objects
Directories Manipulation with Directory Object

UNIT 2: WORKING WITH REGISTRY AND TEXT FILES


Working with the Registry
Reading and Writing Text Files

UNIT 3: WORKING WITH DATABASE


Introduction to ADO.NET
Manipulating Data

UNIT 4: WORKING WITH REPORTS


Introduction to Crystal Report
Creating and Displaying Reports
Expectation:
Students are expected to attend all lectures, submit all assignments/projects, write test and final
examination.

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

1.1 Starting Visual Basic


Let us begin by answering the question - What is Visual Programming? Visual programming
language (VPL) is any programming language that allows users to develop programs through
graphical manipulation of program elements rather than through textual manipulation. A VPL
allows programming with visual expressions, spatial arrangements of text and graphic symbols.
VPL uses programing elements such as boxes, arrows, buttons, forms and so on. The main
objective of VPLs is to make program development easier, even for novices and to support
programmers at different levels. Although there have been debate as to what constitute Visual
programming, however, in this course material, the definition of Visual Programming
encompasses GUI-programming languages, such as Visual Basic, Visual C++ and the entire
Visual programming family, that allows manipulation of programming elements with Graphical
User Interface (GUI) through the provision of Integrated Development Environment (IDE).
These set of programming languages provide GUI builder to make programming interfaces
easier. For this course, Visual Basic (VB) is selected among all the programming languages
bundled into Visual Studio IDE. Unlike like in those days, Visual Basic is now part of a larger
entity known as the .NET Framework. The .NET Framework encompasses all the .NET
technologies, including Visual Studio .NET and the common language runtime (CLR), which is
the set of files that make up the core of all .NET applications. Visual Basic is one of the many
languages that exist within the Visual Studio family. Many other languages included in the .NET
framework also include Visual C#, Visual F#, Visual C++ and so on.

Advantages of Visual Basic


1. Basic programming language is simple to use;
2. The VB IDE has been highly optimized to support rapid application development which
makes it easy to develop graphical user interfaces and to connect them to handler
functions provided by the application.
3. The GUI of the VB IDE provides intuitively appealing views for the management of the
program structure and the various types of program entities such as classes, modules,
procedures, forms and so on.
4. VB IDE provides a comprehensive interactive and context-sensitive online help system.
5. VB IDE supports IntelliSense technology that notifies programmer using a popup
window about the types of constructs that may be entered at the current cursor location.
6. VB is a component integration language which is attuned to Microsoft‟s Component
Object Model (COM).
7. The supported COM components can be written in different languages and then
integrated using VB.
8. Interfaces of COM components can be easily called remotely via Distributed COM
(DCOM), which makes it easy to construct distributed applications.
9. COM components can be embedded and liked to your applications.
10. There is a wealth of readily available COM components for many different purposes
which can be used in your applications.
11. VB is built around the .NET environment used by all Microsoft Visual languages,
therefore is supports varieties of applications development.
Disadvantages of Visual Basic
1. VB is a proprietary programming language written by Microsoft.
2. VB generally requires a great deal of memory for initial installation and in order to
function efficiently after installation.
3. VB is based on development tool with graphical aspects that require a significant amount
of space.
4. VB is not very useful for making programs that use a lot of processing time, such as
games.

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.

Figure 1.1: 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.

1.2 Creating a New Project


When you start the Visual Studio 2010 as shown in Figure 1.1, you will see the Start Page tab
that allows you to create new project or open an existing projects on the system. To create a new
project, click on New Project link to display the new project dialog box shown in Figure 1.2.
From this dialog box, you can specify the type of Visual Basic project to create such as
Windows, Web, Cloud, Reporting and so on.

Figure 1.2: New Project dialog box

Follow the below steps to create a new window application project:


1. Select Windows Form Application in the new project dialog box (see Figure 1.2)
2. In the Name textbox, delete the “WindowsApplication1” and type the name of the new
project. For our simple application to compute area of a circle, type “Area of Circle”.
3. Click Ok button.

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.

1.3 Understanding Visual Studio Environment

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.

Setting Object Properties


The Properties Window in Figure 1.4 can be used to change the attributes or properties of any
object with physical appearance. When you click the object on the form, the Properties Window
adjusted to display all the properties of the selected object. For instance, to change the name of
the form, simply change Form1 to the desired name (e.g FrmArea). Note that the name of the
object must not have space. We will discuss more on the rules for naming object in the later
Units. The Text property of a form is used to change the title of the form. Change this to “Area of
a Circle” and notice the effect on the form title. Notice that the new name e.g FrmArea does not
change the form‟s filename as it is displayed in the Solution Explorer window.

Changing the form’s filename in Solution Explorer


1. Right-click the Form1.vb to display a context-menu.
2. In the context-menu displayed, click Rename and change the form‟s filename to
FrmArea.vb.

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.

Changing the form size


First, you can use the object resize handles (see Figure 1.3) around the form to change the size of
the form at design-time. Second, the size property of the form can also be used to set the form‟s
width and height (see Figure 1.5).

Figure 1.5: Size property of a form


Saving your new project
When you make changes to your project either at the design view or in the coding area, you will
need to save the changes. You can do this by following these steps:

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.

Figure 1.5: Save Project dialog box

1.5 Adding Controls to a Form


At the stage, it is believed that you can now change the properties of any control or object that
you place on the form. At the same time, you can navigate the VB IDE and make changes to
some items such as resizing form, changing the form's filename, interacting with menus and
some other operations earlier discussed. Let us now place additional control on our empty form.
Use the Toolbox to place additional controls or objects such as TextBox, Label, PictureBox etc
on the form. The Toolbox (see Figure 1.6) is organized into different categories (e.g Common
Controls, Containers, Menus & Toolbars, Data and so on). Each category consists of the objects
or controls that you can place on the form. For instance, Common Controls has objects like
Button, CheckBox, CheckedListBox, ComboBox, DateTimePicker, Label, and so on. Now, we
will design the interface showing all the controls that we need for the simple application to
compute the area of circle.

Figure 1.6: Toolbox controls or objects

1.6 Designing the Interface


Recall that Area of a circle is πr2. This means that we need π and radius to calculate the value for
the area of a circle. Design your interface as shown in Figure 1.7 using two Label controls, two
TextBox controls, and two command Button controls. The properties of the controls are
described in Table 1.1.

Table 1.1: Properties of the controls for Area of Circle project


Controls Properties and values
Label control 1 Name: lblRadius
Text: Enter Radius
Font: Microsoft Sans Serif, 12pt, style=Bold
Label control 2 Name: lblArea
Text: Area Is
Font: Microsoft Sans Serif, 12pt, style=Bold
Textbox control 1 Name: txtRadius
Text:
Font: Microsoft Sans Serif, 12pt, style=Bold
Textbox control 2 Name: txtArea
Text:
Font: Microsoft Sans Serif, 12pt, style=Bold
ReadOnly: True
Command Button 1 Name: CmdCalculate
Text: Calculate
Font: Microsoft Sans Serif, 12pt, style=Bold
Command Button 2 Name: CmdClose
Text: Close
Font: Microsoft Sans Serif, 12pt, style=Bold

Figure 1.7: Designing the interface

1.7 Working with Codes behind an Interface


Now that we have designed the interface for the simple VB program to compute the area of a
circle, the next is to write the codes behind the commend buttons that will perform the desired
operations such as calculating the area and closing our application. Note that Visual Basic is an
event-driven programming language, which means that code is executed in response to events.
These events are triggered when the user interacts with the object. For instance, events might
include such thing as a user clicking a button and triggering its Click event. Each control has
associated events that are executed to control the behaviour of that object. For instance, sleep is
behaviour of human being and it can be triggered when a person sleeps. Presently, your simple
application looks very nice but it cannot do anything even if you run it and click on the calculate
and close buttons. You can try to run your program by clicking on F5 on the keyboard and press
the two buttons; you will notice that nothing happens. This means that you need to write codes to
accomplish the tasks.

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.

Use to change object Use to change event


for code writing of a control

Figure 1.8: Visual Basic coding environment

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.

Private Sub CmdCalculate_Click(ByVal sender As System.Object, ByVal e As


System.EventArgs) Handles CmdCalculate.Click
Dim PI As Double = 3.142
Dim r As Double, area As Double
r = txtRadius.Text
area = PI * r * r
'displaying the result in the textbox txtArea
txtArea.Text = area
End Sub
Closing the application
Write the following codes under the click event of the CmdClose button. The Me.Close()
statement closes the current form. When the last loaded form in a program is closed, the
application shuts itself down completely. Later when you build robust application, you will learn
how to execute all kinds of cleanup routines before terminating an application, however, for this
simple example, closing the form is okay for now.

Private Sub CmdClose_Click(ByVal sender As System.Object, ByVal e As System.EventArgs)


Handles CmdClose.Click
Me.Close()
End Sub

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

Figure 1.9: Switching between design and code view

1.8 Running a Project


Now that your application is complete. You will need to save all the changes you have made to
your program by clicking the Save All from the File menu or use the Save All icon on the
toolbar. To run your program, click Debug > Start Debugging or press F5 on the toolbar. When
you run the program, the Visual Basic interface changes, and the form you have designed
appears, floating over the design environment. You can now test your application for correctness.
For our simple application to compute the area of a circle, Figure 1.10 shows the value of area of
a circle when radius of 5cm is supplied.
Figure 1.10: Running application for area of a circle

1.9 Creating Executable File


Executable file for Windows applications created with Visual Studio have the file name
extension .exe and can be run on any system that contains Windows operating system and the
necessary support files. If you plan to distribute your applications, see the next section on
“Deploying Your Application” in this Unit. It is important to know that Visual Studio creates
two types of executable files for your Windows application project: a debug build and a release
build.

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.

Figure 1.12: Customizing the Release build

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.

UNIT 2: NAVIGATING VISUAL BASIC IDE


2.1 Opening an Existing Project
By default Visual Studio displays a startup page as shown in Figure 1.1. From this page, you can
open an existing Visual Basic project by clicking the Open Project link. This displays the Open
Project dialog box. Then, navigate to the location where you save the project and click on the
project solution file with .sln extension to open the project. Figure 1.13 shows an example for
our “Area of Circle” project. Alternatively, you can use the Open Project submenu under the File
menu.
Figure 1.13: Opening existing project

2.2 Showing and Hiding Design Windows


When a design window is closed and you cannot find it, you can access it by clicking on
the View menu. Other windows such as Properties Window, Solution Explorer, Code
Window and so on can also be displayed from the View menu. Figure 1.9 shows the
various windows you can display from the View menu. To close a design window,
simply click on the Close button as shown in Figure 1.14.
Close
button

Figure 1.14: Closing the design window

2.3 Working with Toolbars


Toolbars allow you to access menu commend or items easily and they are mainly available in
every Windows application. As you progress in your program development, you will want to
insert toolbars in your own application and create application that is menu-driven. You can
customize the toolbars provided by the Visual Basic IDE for your project via the View menu.
For instance, you can show or hide a number of toolbars included in the Visual Basic IDE. The
default toolbar that is included when you open VB IDE is Standard Toolbar as you can see in
Figure 1.15. You can show or hide other toolbars by simply checking or unchecking the toolbar
of your choice. Notice that the Standard Toolbar is the only one that is currently checked.

Standard
Toolbar

Figure 1.15: Showing or hiding toolbar

2.4 Adding Controls to a Form Using the Toolbox


Visual Basic IDE provides some fantastic tools for building a graphical user interface (GUI) for
your applications. Most GUIs applications consist of one or more forms (Windows) with various
elements or controls on the forms, such as textboxes, list boxes, combo box, label and buttons to
build user-friendly applications. The toolbox is used to place controls on a form as shown in
Figure 1.6. The Pointer item in the Toolbox is not actually a control, but when selected ensure
that the design environment is placed in a select mode rather than in a mode to create a new
control. By selecting the pointer item selected, Visual Basic allows you to click a control on the
form to display all its properties in the Properties window. There are four ways by which you can
add controls to a form in Visual Basic:

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.16: Components of the Properties window

Viewing Objects and Its Properties


The drop-down list at the top of the Properties window, which shows the name of the form you
are currently working with (e.g FrmArea), can be used to select other controls on the form.
Figure 1.17 shows all the controls available on the form of our simple program "Area of Circle".
Selecting any of the controls from the drop-down will display the properties of the control. You
can also click the specific control directly on the form to display its properties.

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

Figure 1.18: Changing the BackColor of form control

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

Save and Run Area of Circle Project


At this point, you will need to save all the changes made so far in the design view by clicking the
Save All. Running the project displays the window shown in Figure 1.20. As you can see, the
changes to the controls properties have been effected. Notice that we test our application, this
time around, with 10cm radius.

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.

2.6 Managing Projects


When working with Visual Basic, you will need to understand what makes up a VB project and
you can add remove components from the VB projects. In this section, you will also learn how to
manage your project files through the Solution Explorer window including customizing the
properties of your project. As you develop projects, they will become more and more complex,
sometimes containing different objects, such as forms and modules (i.e for grouping sets of
codes). Each object is defined by one or more files on your hard drive. In addition, you can build
complex solutions composed of more than one project. The Solution Explorer window, is the
tool for managing all the files in a simple or complex solution. Using the Solution Explorer, you
can add, rename, and remove project files, as well as select objects to view their properties. You
can also customize your project properties by simply right-clicking the project name. You click
the tool or icon on the Solution Explorer to view the different files in your project. Figure 1.21
shows an icon in the Solution Explorer, which when clicked, displays the different files
associated with your project. Click the expand and collapse arrows to show or hide project files.
Figure 1.21: Showing the files in your project

2.7 Working with Solution


Often the terms project and program are used interchangeably, but with many distinctions. A
project is the set of source files that make up a program or component. A program is the binary
file that you build by compiling source files into something such as a Windows executable file
(.exe) that can be run to produce outputs. Projects always consist of a main project file and can
be made up of any number of other files, such as form files or class module files. What, then, is a
solution? As your abilities grow and your applications increase in complexity, you will find that
you have to build multiple projects that work harmoniously to accomplish your goals. For
instance, you might build a custom user control such as a custom data grid that you use within
other projects you design. Or you might isolate the business rules of a complex application into
separate components to run on isolated servers. All the projects used to accomplish those goals
are collectively called a solution. Therefore, basically, a solution is really nothing but a group of
projects. Visual Basic creates a solution file for you when you save a project. The solution file is
saved with the extension .sln, and you can open this file as discussed earlier. If a solution
contains a single project, it really does not matter which one you open, the solution (.sln) or the
project file (.vbproj). However, when you need to work with multiple projects together, you
should open the solution file.

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.

Adding and Removing Project Files


At the beginning of this course, you created a simple project with just a single windows form.
Visual Basic does not limit the number of forms you can add to your project as well as the
number of other files. You can create and add code modules and classes as well as other types of
objects. You can add a new or existing object to your project in one of three ways:
 Choose the appropriate item from the Project menu (see Figure 1.22).
 Click the small drop-down arrow that is part of the Add New Item button on the Standard
toolbar, and then choose from the menu that appears (see Figure 1.23).
 Right-click the project name in the Solution Explorer window, and then choose Add from
the context-menu to access a submenu from which you can select object types (see Figure
1.24).

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.22: Adding item through the Project menu


Figure 1.23: Adding item through the toolbar

Figure 1.24: Adding item through the Project name in the Solution Explorer
Figure 1.25: Add New Item dialog box

Sample Project – Guessing two numbers


In this example, you will add additional windows form to your existing project that computes the
area of circle. On this form, you will develop a task that allows a user to guess two numbers that
have been randomly picked by the computer system from 0 to 9. You will then click a button to
verify if your guesses are correct or wrong. Your program must display the result in a label
control. Here, we will add two label controls, one RichTextBox, two TextBox controls and two
commend buttons. Table 1.2 shows the properties and values for the individual control.

Table 1.2: Controls for guessing two number‟s project


Controls Properties and values
Form 2 Name: FrmGuess
Text: Guessing Two Numbers
Label control 1 Name: lblFirstNum
Text: Enter Your First Number
Font: Microsoft Sans Serif, 12pt, style=Bold
Label control 2 Name: lblSecondNum
Text: Enter Your Second Number
Font: Microsoft Sans Serif, 12pt, style=Bold
RickTextBox Name: rtbOutput
Text:
Font: Microsoft Sans Serif, 12pt, style=Bold
ForeColor: Red
Textbox control 1 Name: txtFirstNum
Text:
Font: Microsoft Sans Serif, 12pt, style=Bold
Textbox control 2 Name: txtSecondNum
Text:
Font: Microsoft Sans Serif, 12pt, style=Bold
Command Button 1 Name: CmdVerifyGuess
Text: Verify Guess
Font: Microsoft Sans Serif, 12pt, style=Bold
Command Button 2 Name: CmdClose
Text: Close
Font: Microsoft Sans Serif, 12pt, style=Bold

Procedures to design and run the guess project


1. Open your “Area of Circle” project
2. Add one more windows form to your project by following the steps highlighted in the
previous section. Do not forget to name your form as depicted in Table 1.2.
3. Add the specified controls to your new form and set their properties. The design view of
your new form should look like Figure 1.25. Notice the changes to the Solution Explorer
i.e a new windows form has been added.

Figure 1.25: Design view of the guess project

4. Next is to write the codes below under the two command buttons.

Private Sub CmdVerifyGuess_Click(ByVal sender As System.Object, ByVal e As


System.EventArgs) Handles CmdVerifyGuess.Click
Dim firstNum As Integer, secondNum As Integer
Dim compFirstNum As Integer, compSecondNum As Integer
firstNum = txtFirstNum.Text
secondNum = txtSecondNum.Text
'let the computer picks its numbers
compFirstNum = Int(Rnd() * 10)
compSecondNum = Int(Rnd() * 10)
'now test if your guesses are correct with the computer numbers
If (firstNum = compFirstNum) And (secondNum = compSecondNum) Then
rtbOutput.Text = "Congratulations! You guess right. The first number is " &
compFirstNum & " and the second number is " & compSecondNum
Else
rtbOutput.Text = "Ooops! You guess wrong. The first number is " &
compFirstNum & " but you enter " & firstNum & " and the second number is " &
compSecondNum & " but you enter " & secondNum & ". Try your luck next type."
End If
End Sub

Private Sub CmdClose_Click(ByVal sender As System.Object, ByVal e As


System.EventArgs) Handles CmdClose.Click
Me.Close()
End Sub

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

Figure 1.26: Accessing project properties from Project menu


Figure 1.27: Project properties window

6. Now run your application and try your guess. See Figure 1.28 for a sample guess output.

Figure 1.28: Sample output for the guess program

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.

UNIT 3: UNDERSTANDING OBJECTS AND COLLECTIONS

3.1 Understanding Objects


Basically everything you use in Visual Basic is an object. Thus, it is very important to have the
basic knowledge of object-oriented programming (OOP). Understanding the little concepts of
OOP will guide you throughout your learning and it will assist you to use or design different
kinds of objects that are useful to your application. The previous versions of Visual Basic, before
the introduction of Visual Basic.Net, were not truly object-oriented languages. The advent of
Visual Basic .Net gave rise to a fully-functional object-oriented programming. Almost
everywhere you look, the Web, publications, books, you read about objects. What then is an
object? An object is a programming element that encapsulates data and functionality as a single
unit and for which the only public access is through the programming structure‟s interfaces such
as properties, methods, and events. In the class-based OOP paradigm, an object refers to a
particular instance of a class, where the object can be a combination of variables, functions, and
data structures. In a layman language, an object is anything that you can think of. For instance, as
you have seen in the previous projects, form is an object and all the controls you can place on a
form are also objects. Every element of a Visual Basic project is an object and belongs to a
collection of objects. When we defined an object as anything you can think of, this definition
encompasses all real-life objects such as a dog, a cat, a house, a car and so on. All objects have
attributes (called properties), most have methods, and many have events. Whether creating
simple applications or building large-scale enterprise solutions, you must understand what an
object is and how it works. In Visual Basic, the most commonly used objects are the form object
and the control object. In the previous units, you were introduced to working with form and
controls in Visual Basic. You also customized the properties of these objects via the Properties
window. Both TextBox and Label are control objects; however, each is a specific type of control
object. In another example, you can think of pet objects. Dogs and cats are definitely different
entities (objects), but they both fit into the category of pet objects. Similarly, a RichTextBox and
a Button is each a unique type of object, but they are both considered control objects.

3.2 Understanding Properties


To understand properties of an object, we need to consider an example. Every object has
attributes which are used to return the state of the object. These attributes are called properties
and we have shown some examples of attributes of some of the controls we use in our Visual
Basic project. For instance, Name, BackColor, Text, ForeColor and Font are some of the
attributes of a Windows form. Let us consider a real life example of an object. For example Car
is an object and it could possess properties such as Model, NumberPlate, Color, EngineNumber,
ChasisNumber among others. Individual object of a type car has unique values for these set of
attributes that define the car. For instance, we could have a car Toyota 2018 model with
NumberPlate A12345, these values will be different from that of another car. It should be noted
that, indeed, every object exposes a specific set of properties, but not every object exposes the
same set of properties. Figure 1.29 shows an object Car with some of its attributes (properties).

Car

- Model
- NumberPlate
- Color
- EngineNumber
- ChasisNumber
Figure 1.29: Showing properties of a car object

Getting and Setting Object Properties


In Visual Basic, as you have seen earlier, the Properties window is used to change the properties
of any object. However, the properties showing by the Properties window are only available at
the design view. Most of the time, you will need to change the properties of your controls or
objects through the code. To reference a property of an object in the code, you will need to
mention the name of the object followed by a dot or period (.) and the particular property. The
syntax is:

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:

FrmArea.Text = “Area of Circle”

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.

3.3 Understanding Methods


Recall that we had earlier said every object possessed properties or attributes whose values are
unique to that specific object. Moreover, an object also possessed methods which are actions the
object can perform, in contrast to attributes, which describe the object. For instance, human
beings as an object possesses certain methods, such as sleep, eat, talk, walk, wave, and so on. Let
us consider our Car object in the previous example; the car object possesses methods like
accelerate, stop, move, receiveFuel and so on. These methods are depicted as shown in Figure
1.31.
Car

- Model
- NumberPlate
- Color
- EngineNumber
- ChasisNumber

+accelerate()
+stop()
+move()
+receiveFuel()

Figure 1.31: Showing methods of object of type Car


Therefore, methods are like functions that the object can perform. When you invoke or call a
method, the particular code attached to that method is executed. Invoking or triggering a method
is similar to referencing the value of a property. First you reference the object‟s name, and then
provide a dot, and then the method name, such as:

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.

3.4 Building a Simple Object


This section demonstrates how to build a simple graphic object. The goal of this project is to
create a graphic object that will allow us to draw a border around the RichTextBox (rtbOutput) in
the Guess program.

Sample Project - Drawing


Now, modify the Guess program interface in the design view by including additional command
button with the following properties:

Table 1.3: Setting properties of button for Drawing project


Controls Properties and values
Command Button 3 Name: CmdDraw
Text: Draw Border
Font: Microsoft Sans Serif, 12pt, style=Bold

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:

Private Sub CmdDraw_Click(ByVal sender As System.Object, ByVal e As System.EventArgs)


Handles CmdDraw.Click
Dim objGraphics As Graphics
objGraphics = Me.CreateGraphics
objGraphics.Clear(System.Drawing.SystemColors.Control)
objGraphics.DrawRectangle(System.Drawing.Pens.Red, rtbOutput.Left - 1,
rtbOutput.Top - 1,
rtbOutput.Width + 1, rtbOutput.Height + 1)
objGraphics.Dispose()
End Sub

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.

Figure 1.32: Drawing border using the simple Graphics object

3.5 Understanding Collections


Collections contain sets of like objects, and they have their own properties and methods.
Collections are used to organized or group similar objects. Collections make it easy to work with
large numbers of similar objects by enabling you to create code that performs iterative
processing on items within the collection. Iterative processing is an operation that uses a loop to
perform actions on multiple objects, rather than requiring you to write the operative code for
each object. In addition to containing an indexed set of objects, collections have properties and
might have methods. For instance, you can think of collection such as Vehicle which can contain
sets of cars. Also, Animal can be conceptualized as a collection containing sets of Pets. Using
collection, you can iteratively change the properties of any object within a given collection. For
example, the code below loops through the controls on a form and used MessageBox object in
Visual Basic to display their names. You can create a new project to test this code. As you can
see from this code, individual object within a collection is associated with an index. Index helps
us to know the exact position of the object within the collection and can be used to access either
properties or methods of that object. The statement Me.Controls.Count returns the total number
of the controls placed on the form.

Dim index As Integer


For index = 0 To Me.Controls.Count - 1
MessageBox.Show(“Control with index of ” & index & “ has the name “ &
Me.Controls(index).Name)
Next index

UNIT 4: UNDERSTANDING EVENTS


4.1 Event-Driven Programming
The beauty of Visual Basic IDE is that it allows programmer to design very pretty interfaces and
user-friendly applications. As you have seen earlier, you can place a lot of controls on your
Windows form such as command button that user can click, text boxes which allows users to
enter information and label control that provides opportunity to display text. However, without
building events for the controls, your application will not be interactive and responsive.
Therefore, you have to empower your program to perform actions in response to both how a user
interacts with the program and how Windows interacts with the program. This interaction
achieved through the use of events. The traditional programming language often referred to as
procedural programming, dictates the code to be executed and when the code is executed. When
you execute a program written by the traditional programming language, the code start executing
from the very first line of code in the program (assuming the main start point) and continues
executing in a completely predetermined path. The execution of code might branch and loop on
occasion, but the execution path is completely determined by the program. This is unlike a
Windows application, in which a user can interact with different parts of the interface, mostly in
any order the user wants. Visual Basic incorporates an event-driven programming model
allowing user to interact with specific portion of the program code. Event-driven applications are
not bound by the constraints of procedural programs. Instead of the top-down approach of
procedural languages, event-driven programs have logical sections of code placed within events.
To further understand event driven programming, you will recall that in our program to compute
area of circle, you need to click the button Calculate before a result can be displayed in the
txtArea. The Click is an event of button and it gets triggered when you user clicks it. You will
also notice that when you click the Calculate button, the code under the Close button did not
execute. This is because the user has not interacted with the Close command button. Event-
driven programming provides flexibility in code execution and also allows modular debugging.
Triggering Events
Event must be triggered before the code for that event can execute. Triggering event is simply
invoking the code written for the event. There are several ways a user can trigger event in Visual
Basic. These include the following:
 Users can trigger events by interacting with your program. Clicking a button, for
example, triggers the button‟s Click event.
 Objects can trigger their own events as needed. The Timer control, for example, can
trigger its Timer event at regular intervals.
 The operating system can trigger events.
 You can trigger events by calling them much as you would invoke a method when using
Visual Basic code.

4.2 Accessing an Object’s Event


Accessing an object‟s events is simple and straight forward. In our previous project examples,
you have accessed some of the default events of the objects placed on the form including the
form itself. For instance, you have accessed the Click event of command button; you have used
the Load event of a form and so on. Each object in Visual Basic possesses a number of unique
events that can be triggered to make your application responsive.

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.

Figure 1.33: Accessing other events of a control

4.3 Working with Event Parameters


Event parameters are the list of items within the parentheses of an event declaration. An event
parameter is a variable that is created and assigned a value by Visual Basic. These parameter
variables are used to get, and sometimes set, relevant information within the event. Multiple
parameters within an event procedure are always separated by commas. As you can see, the
Click event has two parameters. When the event procedure is triggered, Visual Basic
automatically creates the parameter variables and assigns them values for use in this single
execution of the event procedure. The next time the event procedure occurs, the values in the
parameters are reset. You can use the values in the parameters to make decisions or perform
operations in your code.

The Click event of a button has the following parameters:

ByVal sender As System.Object and ByVal e As System.EventArgs

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.

Figure 1.34: Accessing properties and methods

You might also like