0% found this document useful (0 votes)
3 views119 pages

Introduction To Visual Basic Programming

This document provides an introduction to visual programming languages, outlining their definitions, examples, and hardware/software requirements. It explains the structure of a visual program, including event-driven programming, integrated development environments, and variable types. Additionally, it includes practical activities for building simple programs using Visual Basic.

Uploaded by

otiejacob80
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
3 views119 pages

Introduction To Visual Basic Programming

This document provides an introduction to visual programming languages, outlining their definitions, examples, and hardware/software requirements. It explains the structure of a visual program, including event-driven programming, integrated development environments, and variable types. Additionally, it includes practical activities for building simple programs using Visual Basic.

Uploaded by

otiejacob80
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

INTRODUCTION TO

VISUAL
PROGRAMMIN
G LANGUAGES
Specific Objectives:
By the end of this topic, the trainee should
be able to
1) Describe Visual Programming
2) Identify different examples of visual
programming languages
3) Describe hardware and software
considerations for visual programming
Description of Visual Programming
What is a program?
A program is a set of instructions that tells a computer
how to do a task. With programs, computers can
perform tasks
What is programming?
Programming is the process of designing, writing,
testing and debugging a program. To write a
program, you need to know and solve the problem
first. After solving the problem, you tell the computer
how to solve the problem using a programming
language.
For example, if you need to write a program that
calculates percentage changes, you should first
solve the problem by obtaining the formula of
percentage change. After that, you will write a
program to do the task.
 What is a programming language?
A Programming language s a special language that is used by
the programmer to develop software programs, scripts or other
instructions for computers to execute
 A programming language consists of a specification and an
implementation. The specification provides a definition of the
programming language, and programmers write programs
according to the specification. And the implementation is a
translator: something that converts the program from the
programming language into machine code.
 Characteristics of programming
o Simplicity
o Naturalness
o Abstraction
o Efficiency
o Structured
o Compactness
Examples of Visual Programming
Languages

Delphi
C++
Visual Basic
Visual Basic
Definition of Visual Basic
Visual basic is a computer
programming language that is
used to create programs that
can run in windows operating
systems.
Visual Programming is a
graphical user interface
programming language that is
designed for creating software
systems that run under Microsoft
Windows environment.
Hardware and software considerations
for visual programming
 A computer that can open Notepad.
 A a copy of Microsoft's .NET Framework to convert
your text into an application
 A 1.6 GHz processor
 At least 4 GB Ram with 512 MB of free RAM
 A 32-bit and 64-bit Windows operating systems
newer than Vista.
 A 5400-RPM hard drive and 10 GB (NTSF) of free
hard drive space.
 A video card capable of running DirectX 9 at
screen resolutions of 1024 by 768 or higher.
Visual Environment
Objectives : A trainee should
be able to:-
1. Describe visual environment
2. Describe integrated
development environment
3. Describe various visual
objects
Getting Started with Visual Basic
 Visual Basic is a third-generation event-
driven programming language modelled
from Microsoft to help students learn how
to program.
A programmer can create an application
using the components provided by the
Visual Basic program itself.
Programs written in Visual Basic can also
use the Windows API, which requires
external function declarations.
Description of a visual environment
Event driven environment
•An event is a response generated by the
program when the user performs an action.
The response depends on the code held in
an event
•Event-driven programming is a programming
paradigm in which the flow of the program is
determined by events such as user actions (mouse
clicks, key presses), sensor outputs, or messages
from other programs or threads. In an event-driven
environment, there is generally a main loop that
listens for events, and then triggers a callback
function when one of those events is detected.
•Event-driven programs can be written in any
programming language, although the task is easier in
languages that provide high-level abstractions, such as
await and closures.
•Event-driven programming is the dominant paradigm
used in graphical user interfaces and other applications
(e.g., JavaScript web applications) that are centered on
performing certain actions in response to user input
It has a collection of tools/controls that are used by
programmers. They are accessed from the toolbox
It has special objects called forms that have a title
bar at the top. The programmer can then add a
menu bar, status bar, toolbars, buttons and side bars
to the form when creating an application
Illustration of Event Driven Procedure
Description of Integrated Development Environment

Visual basic displays a dialog box at start with three tabs, New, Existing
and Recent. The new tab is used for creating a new application
 Upon clicking the [Link] then Open the following window
appears
IDE is a collection of preferred facilities for creating, compiling, executing
and managing programs. The programmer can develop and test the
programs easily by using IDE.
An IDE contains different kinds of tools that help you to write programs, like
source code editor, form designer, compiler, debugger, Controlls,
Properties, Immediate Window, and many other tools.
 Components of IDE
1. The Menu Bar
1. Menu Bar

2. The standard toolbar


Like many applications, the standard toolbar has standard icons
that are short cut of commands to the menu commands. Some
icons in this toolbar may be helpful when Debugging a project
and Stop debugging a project among other icons.
It is located below the Menu Bar

Start/Run End/Stop
To execute a Visual basic project you simply click on the start icon.
And to stop click on the End Icon
 Form Design Window
It is the main object of the project. This is a place where the
programmer does the actual design of the user interface for the
program. It is accomplished by selecting the relevant control
icons from the toolbox then placing them on the form design
window.
 You can nomad a form around the screen by holding the
project title then dragging it the required destination.
 Tool box Contains different types of controls to develop windows
application . These controls are placed on a form for creating
graphical user interface
Code editor window
It is accessed from the standard toolbar by clicking on
the Solution explorer icon Then the dialog box for the
code editor menu appears as below
 Once you click on Code view icon the following code editor
window will appear
Immediate window
Use the Immediate window to debug and evaluate expressions,
execute statements, and print variable values. The Immediate
window evaluates expressions by building and using the currently
selected project.
Types of Controls
 The Visual Basic toolbox has controls that enable a person
to design and customize forms . It is within the standard
toolbar ot positioned at the left side
Examples of this controls :-
: When used provides a way of specifying a Yes/No
Response
: Provides a list of text items for selection by the user
: Provides a means of entering / displaying text.
:It is a special type of list box that combines the
capabilities of a text box and a list box. Provides
a list of items for selection by the user
: Used to display graphical objects to initiate event
actions
: Allows timed event to occur repeatedly at a
specific time interval
: Displays text on a form
 Allows a user to assign text associated with the control
 : Allows a user to print an active document/ Project
: Allows a user to preview code
Properties Window
 Allows a user to customize properties of an active control. They are
accessed from the standard toolbar and have a format illustration
below
Assigning values to properties
 Different properties accept values of different data types. Please
see the table below:
 0718529769

Name of Data type Example


property
Text String [Link] = "Title of the Window"
ForeColor Color* [Link] = [Link]
BackColor Color [Link] = [Link]
Left Integer [Link] = 100
Top Integer [Link] = 234
Width Integer [Link] = 300
Height Integer [Link] = 400
Visible Boolean [Link] = True
(True/False)
Enabled Boolean [Link] = False
(True/False)
 Class Work 3.5

Write down a Visual Basic statement for


each of the following operation
Operation VB statement

Change the background colour of


the TextBox1 to blue.
Make Button2 disappear.
Set the title of the form to “New
Document”
Change the colour of the text in
Label1 to yellow.
Move Button1 that Button1 is
vertically aligned with Button2.
(Assume that the heights of both
buttons are the same.)
Teacher to
demonstrate
creating a visual
environment as
trainees attempt to
create their own
PROGRAM STRUCTURE
Objectives: By the end of the
topic the trainee should be
able to:-
1)Describe format of a visual
program
2)Explain different data types
3)Explain various data
operators
Format of a visual basic program
 There are some basic techniques in writing the Visual
Basic program code.
 First of all, we should understand that each control or
object in VB are able to run numerous kinds of events.
 These events are listed in the dropdown list in the
code window, that is displayed when you double-
click on an object and click on the procedures’ box.
Among the events are loading a form, clicking on a
command button, pressing a key on the keyboard or
dragging an object and more. For each event, you
need to write an event procedure so that it can
perform an action or a series of actions.
 To start writing code for an event procedure, you
need to double-click an object to enter the VB code
window. For example, if you want to write code for
the event of clicking a command button, you double-
click the command button and enter the codes in the
Variables
 In Visual Basic, you use variables to store values. Variables
have a name and a data type.
 A variable is a name / identifier that is used to represent a
numerical quantity, character, a string or other data
items. When a variable is declared in a program, the
computer sets aside memory space to hold a value in the
variable.
 Rules to be followed when declaring variables:-
1. The variable must not have more that 255 characters
2. The variable must start with a letter
3. The letter case is not important when declaring variables
4. A variable must not be a reserved word( Case, Else, Dim,
etc)
5. Variables must not have spaces
For example to declared a variable that will store first name
of a trainee in a program the following declaration can
be made:
Dim FirstName As String
 Types of variables
1. Numeric variables : used to store numeric values known as
numeric variable. These may be integers and real numbers. They
are used in arithmetic calculations . Examples of numeric
variable :
Integer variables /Long variables / Single variables/double
variables/currency variables.
2. String variables . They are used to store string values known as
string variable. A set of characters enclosed in double
quotations is referred to as string Types of Strings include:
Variable length string / fixed length string
3. Special variables : they are types of variables that are used to
store special values they may be date variables, Boolean
variables
4. Variant variables: they handle all types of data and converts
between them automatically . If an integer value is stored in
variant then VB uses it as integer and incase of text it uses it as
string
 Variant
A variant is a variable whose data types has not been
explicitly declared by the programmer. In this case the
variable type will be determined by the value held by
the variant. (There data type keeps on changing with
the values they hold.)
Data Type Description
Integer A whole number with no fractional part -1212 to
1212
Long Integer Numbers which are integers but have bigger value
and range e.g -1,111,111,111 to 1,111,111,111
Single A single precision real constant includes a
fractional part e.g 3.4 X 1038
Double Includes a fractional pat but has far much larger
magnitude than the single real number constant
however it cannot be larger that 1.2 x 10308
String Characters enclosed in quotation marks
Boolean Data types that have only two logical states i.e true
or false
 Constants
In programming a constant is a value that remains the
same. it does not change during the execution of the
program. There are three types of constants: String,
numeric and named constants.
(a) String Constants
A string constant can be defined as a sequence of
characters enclosed in quotation marks. They are
used to write non – numeric values like telephone
numbers, addresses and names. The following are
examples of string constants
“Learning is interesting”, “0712573009”,”Kshs670.00”
(b) Numeric constants
Numbers are usually referred to as constants in Visual
Basic. In most cases, the numeric constants are either
whole numbers (interger) or double/ single e.g
1 3 60000 +70 1.674 etc
Constants cont’
 Named constants
A named constant is identified by name rather than
its actual value. In visual Basic the reserved word Cont
is used to declare this type of constants e.g.
Const Price As integer = 20 meaning an integer value
20 is identified using the name price
 Scope
Refers to the portion of the program that a variable ,
a constant or a procedure is recognized.. The scope
of a procedure is set by declaring it as either Private
or public.
A private procedure is accessed in the module or
form within which it is declared while a public
procedure can be accessed from any module or
form in the program.
An example of declaration is
1. Private X as Integer
2. Public Y As String
PROGRAM WRITING
Objectives: By the end of this topic, the
trainee should be able to :
1. Define program writing terminologies
1. Build a program
2. Compile a program
3. Debug a program
4. Execute a program in visual basic
Build a simple program: Adding controls and code.
Practical activity:1
Let us try to create a simple project with a form that has a
command button once clicked it displays welcome to
programming. We shall follow the steps below:-
 Click on Visual Basic  Click on New Project  Click on Windows
forms application Then assign the form a name and click OK
 Locate the command button from the Toolbox and Drag it to the
Form1 Window that appears
 Right click on the button and select properties
 In the text property check box type Go
 Then from the form double click on Go button
 In the code window that appears Add MsgBox(WELCOME TO
PROGRAMMING)in between Private statement and End Sub
Statement

Private Sub Button1_Click(ByVal sender As [Link], ByVal


e As
[Link]) Handles [Link]
MsgBox("welcome to programming")
Activity 2. Code a program that will
accept two numbers and compute the
total

Label 1 to have
Number 1
Label 2 to have
Number 2
Label 3 will hold the
sum after calculation
Command Button will
have calculate event
action
Private Sub CALCULATE_Click(ByVal sender As
[Link], ByVal e As [Link])
Handles [Link]
Dim sum As Integer
Dim a As Integer
Dim b As Integer
a = Val([Link])
b = Val([Link])
sum = a + b
[Link] =sum
End Sub
Activity 3
 Create a program that can be used to calculate the area
of a rectangle. The program should prompt the user to
enter the length and width of the rectangle.
 Private Sub cmdCalculate_Click(ByVal sender As
[Link], ByVal e As [Link]) Handles
[Link]
Dim l As Single
Dim w As Single
Dim a As Single
l = Val([Link])
w = Val([Link])
a = (l * w)
[Link] = a
End Sub
 Activity 4
Savings Account
Start a new project that will determine how much
you save by making monthly deposits into a
savings account. We shall use the formula: F = D [
(1 + I)M - 1] / I
where
F - Final amount
D - Monthly deposit amount
I - Monthly interest rate
M - Number of months
Steps
Place 4 label boxes, 4 text boxes, and 2
command buttons on the form.
 It should look something
like this:
Deposit Name txtInterest

Label2: Text3:
Caption Yearly Interest Text [Blank]
Name txtMonths
Label3:
Caption Number of Text4:
Months
 Set the properties of the Text [Blank]
form and each object.
Name txtFinal
Label4:
Form1:
Caption Final Balance
BorderStyle 1-Fixed Command1:
Single Caption &Calculate
Caption Savings Text1:
Name cmdCalculate
Account Text [Blank]
Name frmSavings Name txtDeposit
Command2:
Caption E&xit
Text2:
Name cmdExit
Label1: Text [Blank]
Caption Monthly
 Now, your form should look like this:

 Declare four variables in the general declarations area of your form. This
 makes them available to all the form procedures:
 Option Explicit
 Dim Deposit As Single
 Dim Interest As Single
 Dim Months As Single
 Dim Final As Single
 The Option Explicit statement forces us to declare all variables.
Attach code to the cmdCalculate command button Click event.

Private Sub cmdCalculate_Click ()

 Private Sub cmdCalculate_Click(ByVal sender As [Link], ByVal e As [Link]) Handles [Link]

Dim Deposit As Single

Dim Interest As Single

Dim months As Single

Dim final As Single

Dim IntRate As Single

Deposit = Val([Link])

Interest = Val([Link])

IntRate = Interest / 1200

months = Val([Link])

final = Deposit * ((1 + IntRate) ^ months - 1) / IntRate

[Link] = final

End Sub

This code reads the three input values (monthly deposit, interest rate, number of

months) from the text boxes, computes the final balance using the provided

formula, and puts that result in a text box.

Attach code to the cmdExit command button Click event.

Private Sub cmdExit_Click ()

End

End Sub

Play with the program. Make sure it works properly. Save the project.
Activity 5
Design a window that displays the current
month, day, and year. Also, display the
current time, updating it every second
(look into the Timer control). Make the
window look something like a calendar
page. Play with object properties to make
it pretty.
Properties: FontName = Times New FontSize = 72
Roman
Form frmCalendar:
FontBold = True
Caption = My Calendar Label lblMonth:
FontSize = 24
BorderStyle = 1 - Fixed Alignment = 2 - Center
Single
Caption = March
Label lblYear:
FontName = Times New
Timer timDisplay: Alignment = 2 - Center Roman
Interval = 1000 Caption = 1998 FontBold = True
FontName = Times New FontSize = 24
Roman
Label lblDay:
FontBold = True
Caption = Sunday
FontSize = 24
FontName = Times New
Roman
FontBold = True Label lblNumber:
FontSize = 24 Alignment = 2 - Center
Caption = 31
Label lblTime: FontName = Arial
Caption = 00:00:00 PM FontBold = True
Code:
General Declarations:
Option Explicit
timDisplay Timer Event:
Private Sub timDisplay_Timer()
Dim Today As Variant
Today = Now
[Link] = Format(Today, "dddd")
[Link] = Format(Today, "mmmm")
[Link] = Format(Today, "yyyy")
[Link] = Format(Today, "d")
[Link] = Format(Today, "h:mm:ss ampm")
End Sub
Private Sub Command1_Click()
Dim a, d As Integer
Dim b, e As Integer
Dim c, f As Integer
a = Val([Link])
b = Val([Link])
c = Val([Link])
d = Val([Link])
e = Val([Link])
f = Val([Link])
x=a*d
n=b*e
z=c*f
Text7 = x
Text8 = n
Text9 = z
Text10 = x + n + z
End Sub
Assignment
Write a Visual Basic Program statement that
could be used to perform each of the
following:
1) Display an image named [Link] using
image control; ( 2 marks)
2) display the string “Hello Kenya….” On a
label in a second form from the first form; (
2 marks)
3) position a shape at centre horizontally on
the screen. ( 2 marks)
PROGRAM DEBUGGING
Debugging is the routine process of
identifying, analyzing, removing errors,
checking, detecting and correcting
errors or bugs using debugging tools to
allow proper program operation
according to set specifications
A Software Application needs to be
error-free before going out in the
market so as to enable customer/
organization satisfaction.
Software programs undergo heavy
testing, updating, troubleshooting, and
maintenance during the development
It is possible for errors to creep into our programs.
These errors may be grouped into 3 categories:-
a) Syntax Errors
Occur when you mistype a command or leave
out an expected phrase or argument. VB detects
these errors as they occur nd even provides hint
on how to correct them. A program cant run
unless syntax error free
b) Run – time errors
Are usually beyond your program’s control. For
instance when a variable takes an unexpected
value ( /0), when file is missing, Drive door is left
open. Vb allows you to trap such errors and make
attempts to correct them
c) Logic Errors
Mostly unidentified as the program will run but
produce unexpected results.
Debugging process begins after the software fails to execute
The basic steps in debugging are:
 Identify the Error: A bad identification of an error can lead to wa
sted developing time It is import to identify the actual error to av
oid a program executing and giving false result
 Find the Error Location: After identifying the error correctly,
you need to go through the code to find the exact spot where t
he error is located. In this stage, you need to focus on finding th
e error instead of understanding it.
 Analyze the Error: In the third step, you need to use a
bottom-up approach from the error location and analyze the
code. This helps you in understanding the error.
 Prove the Analysis: Once you are done analyzing the original
bug, you need to find a few more errors that may appear on
the application.
 Cover Lateral Damage: In this stage, you need to create or
gather all the unit tests for the code where you are going to
make changes. Now, if you run these unit tests, they all should p
ass.
Ways of minimizing errors
Design your application carefully .
More design time = less
debugging time
Use comments where applicable
to help you remember some tips
Use consistent and meaningful
naming conventions for your
variable, objects and procedures.
Benefits of Debugging
Provides maximum useful information of
data structures and allows easy interpret
ation.
Assists the developer in reducing useless
and
distracting information.
Reports an error condition immediately t
o
allow earlier detection of an error
It aids the developer to avoid complex
one-use testing code to save time in soft
ware development.
 Debugging tools
There are several debugging tools available for
use in VB. Access to these tools is provided with
both menu options and buttons on the Debug
toolbar. These tools include:-
 Breakpoints
 Watch points
 Calls
 Step into
 Step over
 Step out
The simplest tool is the use of direct prints to the
immediate window
CONTROL STRUCTURES
Control structures determine the
execution of statements in a program.
There are three control structures
1. Sequence
The computer reads instructions from
a program starting from the first line
preceding downwards. (Sequential
program execution)
2. Selection
The execution of statement depends on
a condition that returns either True of
False conditioned by Boolean
expression.
There are four types of selection control
structures used in most high level
programming languages. They include
i. IF….THEN
ii. IF….THEN…ELSE
iii. Nested IF
iv. CASE selection
IF …THEN Selection
It is used to execute a single
statement or a group of
statements that represent only
one alternative or option
Example:
If Age>60 THEN
Label1=“Above Retirement Age”
END IF
Use of IF ..THEN..ELSE
It allows execution of two
alternatives or options depending on
whether the test returns a True of
False.
Example:
If Age>60 THEN
Label1=“Above Retirement Age”
ELSE
LABEL1=“Below Retirement Age”
END IF
Use of Nested IF
It is used if there are more than two
available options to choose from
For Example:
If marks >= 80 Then
grade = "A"
ElseIf marks >= 70 Then
grade = "B"
ElseIf marks >= 50 Then
grade = "C"
Else
grade = "D"
End If
1. Design a form to provide a platform
for marks capture and display a
grade for the marks captured .

2. Design a code for the above using the


Command button for calculate.
3. Assign a code to the Exit button that will
close the program
Code for the above shall be
Private Sub cmdcalculate_Click(ByVal sender As [Link], ByVal e
As [Link]) Handles [Link]
Dim Score As integer
Score = val([Link])
If Score >= 80 Then
[Link] = "A"
ElseIf Score >= 60 Then
[Link] = "B"
ElseIf Score >= 50 Then
[Link] = "C"
Else
[Link] = "D"
'End If'
'End If'
End If
End Sub
End Class
 Write a program that inputs marks of Cat and End
Term for VP. Its displays “Not Referred” if both
scores are above 40 else “You are referred”.
Insert a command button and attach the following
code
private sub command_click()
Dim cat as integer
Dim Endterm as integer
cat = inputbox(“Enter cat mark”)
Edterm= inputBox(”enter Endterm mark”)
If cat>40 And Endterm>40 Then
MsgBox”Not Referred”
Else
MsgBoxv”Refferred”
Endif
End Sub
 Case Selection :
 It allows a variable to be tested for equality against a list
of values. Each value is called a case and the variable
being switched on is checked for each select case.
 Example
Private sub on command click()
Dim Grade as String
Grade inputbox(“enter grade”)
Select case Grade
Case “A”
Msgbox (“Distinction”)
case “B”
Msgbox (“credit”)
case”C”
msgbox(“fair”)
End Select
End Sub
Iteration / Looping /Repetition
We can write a Visual Basic procedure that allows the program to
run repeatedly until a condition or a set of conditions is met. This
is procedure is known as looping
It is designed to execute the same block of code again and
again until a certain condition is fulfilled. It is applicable in
situations where the same operation has to be carried out on a
set of data many times.
The common looping constructs used in visual basic include :-
1. While …. Wend loop
2. Do… While Loop
3. Do…until loop
4. Do…loop while
5. Do….loop until
6. For ….. Next loop
DO….. While loop
it executes one or more statements while the given condition is true.
Syntax
Do while condition
Statement(s)
Loop
Activity:
Write a program that shows sum of first nine numbers using do……while loop.
The code will read
Private Sub Command1_Click()
Dim r, i As Integer
r=0
i=1
Do While i <= 9
r=r+1
i=i+1
Loop
Print "sum FROM 1 TO 9 IS=" & r
End Sub
Write a program hat get10numbersfrom the
user and display whether the number is
even or odd. But if the user keys a negative
number it is terminated
The Code
Private sub Command_click
Dim n,x as integer
n=1
Do
x=inputBox(“Key positive number:”)
If x<0 Then Exit Do
Print x
n=n+1
Loop while n<=10
End sub
LOOPING WITH WHILE –WEND
It executes one or more statements
while the given condition remains true
While<condition>
Statements
Wend
Practical Activity 8
Write a program that prints
“programming is good” five times using
while loop.

Project code will read
Private Sub Command1_Click()
Dim n As Integer
n=1
While n <= 10
Print "programming is good"
n=n+1
Wend
End Sub
Do….until….loop
I executes one or more statements until the given condition remains false.
Syntax
Do until condition
statement(s)
Loop
Activity
Write a program that inputs a number from the user and finds its factorial using
do……until….loop
Private Sub Command1_Click()
Dim n, c As Integer
Dim f As Long
c=1
f=1
n = InputBox("enter a number:")
Do Until c > n
f=f*c
c=c+1
Loop
Label1 = "The factorial of n is" & f
End Sub
 Do….loop….while
It xecutes one or more statements while the given condition is true. It is
similar to do……while….loop
syntax
Do
Statement(s)
Loop while condition
Activity
Write a program that gets a number from the user and display the
table of that number
The code reads
Private Sub Command1_Click()
Dim n, i As Integer
n = InputBox("Enter a number:", "table")
i=1
Do
Print n * i
i=i+1
Loop While i <= 10
End Sub
USE OF FOR NEXT LOOP
 This control structure executes the statements within the construct in
a predetermined number of times. It is suitable for accessing values
in a list or array because of its sequential nature. The general format
for this structure reads:
 Practical activity 9:
use for … next loop to code a program that will display the first 40
numbers
Program code will read
Public Class Form1
Private Sub Form1_Load(ByVal sender As [Link], ByVal e As
[Link]) Handles [Link]
Dim x As Integer
Dim counter As Integer
x=0
For counter = 1 To 40
x=x+1
[Link](counter)
Next
End Sub
End Class
 ERROR HANDLING
Error handling is an essential procedure in
programming that helps make a program error-
free. An error-free program can run smoothly and
efficiently. Errors often occur due to incorrect input
from the user. For example, the user might make
the mistake of attempting to enter text (string) to a
box that is designed to handle only numeric values
and thus create an error. These errors are known as
synchronous errors.
 Therefore a good programmer should be more
alert to the parts of the program that could trigger
errors and should write errors handling code to help
the user in managing the errors. Writing errors
handling code is a good practice for programmers,
On the other hand, there should not be too many
errors handling code in the program as it creates
problems for the programmer to maintain and
TYPES OF ERRORS
It is possible for errors to creep into our programs. These
errors may be grouped into 3 categories:-
a) Syntax Errors
Occur when you mistype a command or leave out an
expected phrase or argument. VB detects these errors
as they occur nd even provides hint on how to correct
them. A program cant run unless syntax error free
b) Run – time errors
Are usually beyond your program’s control. For
instance when a variable takes an unexpected value
( /0), when file is missing, Drive door is left open. Vb
allows you to trap such errors and make attempts to
correct them
c) Logic Errors
Mostly unidentified as the program will run but
produce unexpected results.
d) Semantic Errors
Error handling techniques
Writing error handlers
ON ERROR GO TO
Example 20.1 Division by Zero
In this example, we will deal with the error of
entering non-numeric data into the textboxes
that will hold numeric values. The program
label here is error handler. when the user
enters non-numeric values into the textboxes,
the error message will display "One of the
entries is not a number! Try again!". If no error
occurs, it will display the correct answer. Try it
out yourself.
On error resume
On Error Resume Next Specifies that when a
run-time error occurs, control goes to the
statement immediately following the
statement where the error occurred and
execution continues. This statement allows
execution to continue despite a run-time error.
It only becomes inactive when another
procedure is called, so you should execute an
On Error Resume Next statement in each
called routine if you want inline error handling
within that routine.
Err objects
The err object contains properties
and methods that allow you to
obtain information about a single
runtime error in a visual basic
program. It allows you to generate
errors and to reset the error object.
When your program reaches an exit
function, exit sub, exit property,
resume or on error statement , the err
object is cleared and its properties
reinitialized.
SUB PROGRAMS
A Sub procedure is a series of Visual Basic
statements enclosed by the Sub and End
Sub statements. The Sub procedure performs a
task and then returns control to the calling code.

You can define a Sub procedure in modules,


classes, and structures. By default, it is Public,
which means you can call it from anywhere in your
application that has access to the module, class, or
structure in which you defined it.

A Sub procedure can take arguments, such as


constants, variables, or expressions, which are
passed to it by the calling code.
 Private sub programs
Private Sub sets the scope so that subs in outside
modules cannot call that particular
subroutine. This means that a sub in Module 1
could not use the Call method to initiate a Private
Sub in Module 2.
 Private [insert variable name] means that the
variable cannot be accessed or used by
subroutines in other modules. You can use this
type of variable when you have one subroutine
generating a value and you want to pass that
value on to another subroutine in the same
module.
 Dim [insert variable name] is used to state the
scope inside of a subroutine . Dim can be used
either inside a subroutine or outside a subroutine
(using it outside a subroutine would be the same
as using Private).
 Public sub program
Public Sub means that your subroutine can be
called or triggered by other subs in different
modules. Public is the default scope for all
subs so you do not need to add it before the
word “sub”.
 Public [insert variable name] means that the
variable can be accessed or used by
subroutines in outside modules. These
variables must be declared outside of a
subroutine (usually at the very top of your
module). You can use this type of variable
when you have one subroutine generating a
value and you want to pass that value on to
another subroutine stored in a separate
module.
 Scope of variables
Scope represents where in your program the subroutine
can be called from. Subroutines with a Private scope
can only be called from the source file from where they
were defined. While those with a Public scope can be
called from anywhere in your program.
 Global Variable
A global variable is a variable that it is visible (hence
accessible) throughout the program, unless shadowed.
global variables are generally dynamically allocated
when declared, since they are not known ahead of
time.
 Interaction mechanisms with global variables are
called global environment
 Global variables are used extensively to pass
information between sections of code that do not share
a caller/callee relation like concurrent threads and
signal handlers.
Local Variable
A local variable with procedure scope is recognized
only within the procedure in which it is declared. A
local variable can be declared with a Dim or Static
statement. A local variable declared with the Static
statement remains in existence the entire time
Visual Basic is running.
Dim
When a local variable is declared with the Dim
statement, the variable remains in existence only as
long as the procedure in which it is declared is
running.
The next time the procedure is executed, all of its
local variables are reinitialized.
Module scope
 A variable that is recognized among all of the
procedures on a module sheet is called a "module-
level" variable.

Characteristics of a module level variable


1. It is available to all of the procedures in that
module
2. It is not available to procedures in other modules.
3. It remains in existence while Visual Basic is running
until the module in which it is declared is edited.
4. They can be declared with a Dim or Private
statement at the top of the module above the first
procedure definition.
DATA STRUCTURES
Description of data structures
Data Structure are formations
/container programmed to
store organized data so that
various operations can be
performed on it easily and
effectively. (anything that can
store data like Integer, Float,
Boolean, Char etc, all are data
structures.
The data structures can also be classified on the basis of the following characteristics:

Characterstic Description
Linear data items are arranged in a linear sequence.
Example: Array
Non-Linear the data items are not in sequence.
Example: Tree, Graph
Homogeneous all the elements are of same type. Example: Array

Non-Homogeneous the elements may or may not be of the same


type. Example: Structures
Static Static data structures are those whose sizes and
structures associated memory locations are fixed,
at compile time. Example: Array
Dynamic Dynamic structures are those which expands or
shrinks depending upon the program need and its
execution. Also, their associated memory
locations changes. Example: Linked List created
using pointers
Types of data structures
The most commonly used data
structures include:-
Arrays
Stacks
Queues
Linked Lists
Trees
Graphs
Tries (they are effectively trees, but it’s
still good to call them out separately).
Hash Tables
Array
 An array is a collection of simple variables of the same
type( homogeneous) to which the computer can
efficiently assign a list of values.
 Array variables have the same kinds of names
as simple variables.
 An array is a consecutive group of memory locations
that all have the same name and the same type. To
refer to a particular location or element in
the array, we specify the array name and the array
element position number.
 The Individual elements of an array are identified using
an index. Arrays have upper and lower bounds and the
elements have to lie within those bounds.
 Other data structures like stacks and queues are derived
from arrays.
Advantages of Using Arrays
They store large number of values
Are used to process many values
easily and quickly
The values stored in array can be
sorted easily
A search process can be applied
on arrays easily
Declaring arrays: Arrays may be declared as
Public (in a code module), module or
local. Module arrays are declared in the
general declarations using keyword Dim or
Private. Local arrays are declared in a
procedure using Dim. Array must be declared
explicitly with keyword "As". There are two
types of arrays in Visual Basic namely:
Fixed-Size Array: The size of array always
remains the same-size doesn't change
during the program execution. When an
upper bound is specified in the declaration, a
Fixed-array is created. The upper limit should
always be within the range of long data
type.
An array can be one-dimensional or multidimensional.
A one-dimensional array it us used to store different values of similar
type as a single row or column. It is also called linear array/vector
array/1-d array syntax Dim <arrayName>(length) As <type>
Student
Name(1) Name(2) Name(3) Name(4)
Name

Write a program that uses two For…. Next loops . The first loop gets
he five inputs from the user and stores them in an array. The second
loop prints the values stored in this arrays.
Code:
Private Sub command_click()
Dim Marks(4) As integer
for I = 0 to 4
Marks(i)=InputBox(“enter marks”,”marks”)
Next
For i=0 to 4
Print “Value at index”&i& “is”&marks(i)
Next
End Sub
A two-dimensional array is a table of items that make up of
rows and columns. the format for a two dimensional array is
ArrayName(x,y) and a three-dimensional array is
ArrayName(x,y,z)

Table 16.2 Two Dimensional Array


Name(1,1) Name(1,2) Name(1,3) Name(1,4)

Name(2,1) Name(2,2) Name(2,3) Name(2,4)

Name(3,1) Name(3,2) Name(3,3) Name(3,4)


Two Dimensional Arrays:
Arrays can have multiple dimensions. A
common use of multidimensional arrays is
to represent tables of values consisting of
information arranged in rows &columns.
To identify a particular table element, we
must specify two indexes: The first (by
convention) identifies the element's row
and the second (by convention) identifies
the element's column.
Two subscriptions are used to identify an
item. E.g Dim StudentScore(2,4) means
that the element is in the 3rd row, 5th
column.
Write a code program to read of two dimensional array
A(3,4) on a row by row. Print the value and position of
each element.
Dim A(3,4) As Single
for I = 1 to 3 (rows)
For j = 1 to 4 (columns)
A(I,j) = val(inputbox(“”))
Next J
Next I
For I=1 To 3
For J= 1 To 4
[Link] A(I, J) ; Space(2) ;
[Link] I ; " , " ; J ; Space(2);
Next J
[Link] : [Link]
Next I
End sub

To manipulate elements stored
in a two dimensional array, we
use the nested For….Next loop,
for example
Dim iIndex As Integer
Dim jColumn As Integer
For iRow= 1 to 20
For jColumn = 1 to 5
Studentscore(irow,jColumn)
Next jColumn
next iRow
 suppose N is a (5x2) matrix array is entered into ListBox on row by row.
Write a program segment to find the location I and J such that N (I,J)
contains the largest value in N. Print the values of array N. Display the
Largest value and the location into textboxes
Dim N(5,2) As Single
K=0
For I = 1 To 5
For J=1 To 2
N(I,J)= Val ([Link] (K))
K=K+1
Next J, I
Max = N(1, 1): R = 1: C = 1
For I = 1 To 5
For J = 1 To 2
If N(I, J) > Max Then
Max = N(I, J) R = I: C = J
End If
Next J , I
For I = 1 To 5
For J = 1 To 2
[Link] N(I, J); Space(2);
Next J: [Link]: Next I
[Link] = Str(Max)
[Link] = Str(R)
[Link] = Str(C
 Write a code program to defined the array H (5,5)
Calculate the elements of the numeric array (H). Each
element of H is determined by the formula :
Create the one dimensional array X contains the elements
of array H(5,5) on row by row. Print the array X into List Box.
Solution:
Dim H(5,5) As Single , X(25) As Single
For I=1 To 5
For J=1 To 5
H(I,J)=(I+J-1)
Next J ,I
For I =1 To 5
For J=1 To 5
K=K+1 X(K) =H (I , J)
Next J , I
For I=1 To K
[Link] str(X(I))
Next I
Write a code program to read the elements of the array T(5,3) on a row
by row. Calculate the SUM of elements in each row and stored in column
4. Print a new array T(5,4) and the sum of all individual row sums, the
cumulative sum for all rows
Solution:
Dim T (5, 4) As Single
For I =1 To 5
For J=1 To 3
T(I,J)=Val (InputBox(“”))
Next J, I
For I=1 To 5
Sum=0
For J=1 To 3
Sum=Sum + T(I ,J)
Next J
T (I,4) = Sum
Total=Total +T(I,4)
Next I
For I=1 To 5
For J=1 To 3
[Link] T (I , J);
Next J: [Link] : Next I
[Link]=Str(Total)
End Sub
Dynamic Array:
The size of the array can be changed at the
run time- size changes during . The program
execution. In actual practice, the amount of
data that a program will be processing is not
known in advance. Programs should be
flexible and incorporate a method for
handling varying amounts of data. Visual
basic makes this possible with the statement
ReDim ArrayName (N) As Var Type
This can use variables or expression when
indicating the subscript range. However,
ReDim statements can only be used inside
procedures.
 Example: Suppose a one dimension array A with N
elements is entered into inputbox. Write a visual
basic program segment which is calculated the sum
of the squares:

Solution:
Dim N
N= Val (InputBox(“N=”))
ReDim A(N)
For I=1 To N
A(I) =Val(InputBox(“”))
Sum=Sum+A(I)^2
Next
[Link]=Str (Sum)
Records
A record refers to a series of
related data items ( fields). They
differ from arrays in that where as
in arrays all elements are of the
same type data items on a record
they need not to be of the same
type.
Records are defined in a standard
code module/ or in the general
declaration section of a form
module
Sort techniques
For the sorting process simple
algorithm has two majors steps that
are repeated. The two steps are first
to find the smallest element in a
range of storage locations and then
interchange the smallest element
found with the preceding one, The
coding tool will use For…. Next
construct
 Sort techniques

 Sortname Method Short Description


Bubble Sort Exchanging Yes Basic two-loop sort
Cocktail Sort Exchanging Yes Bi-directional Bubble sort
Comb Sort Exchanging No Faster variation of the Bubble sort
Gnome Sort Exchanging Yes Hybrid (Bubble and Insertion Sort)
Selection Sort Selection No In-place comparison sort
Insertion Sort Insertion Yes Simple comparison sort
Shell Sort Insertion No Generalization of insertion sort
Binary tree sort Insertion Yes Builds a Binary tree of the data and uses the tree to sort
Library Sort Insertion Yes Insertion sort that leaves gaps in the list for subsequent elements
Merge Sort Merging Yes A divide, sort, and merge algorithm
In-Place Merge Sort Merging Yes Space-optimised version of the merge sort
Heap Sort Selection No Two-stage comparison style sort
Smooth Sort Selection No Small variation of a Heap sort
Quick Sort Partitioning No Recursive partition and sort
Intro Sort Hybrid No Hybrid of quick sort and heap sort
Patience Sorting Insertion No Statistical ordering of elements
Stand Sort Selection Yes Useful for data which is stored in a linked list
 Bubble Sort
The bubble sort sets up two loops simply to go
through the list of items one at a time and compare
an item to an item after it in the list, and place the
smaller (or larger) item higher up in the list. There are
two methods of using this algorithm; both are
correct and return much the same results it terms of
time and passes.
 One method, "the backward bubble sort," is to set
up the outer loop to step up through the list and the
inner loop to step down to the outer loop value, and
on each pass compare elements adjacent to each
other and swap them if they are in the wrong order.
 The other method, "the forward bubble sort," is to
step both the inner and outer loops down the list
and compare the element of the outer loop to the
element of the inner loop and swap them if they are
Insertion Sort
The Insertion sort is one step better than the
bubble sort and works on a similar principle.
You still loop over the full list from first to last
but instead of swapping elements over,
you insert the element in the correct
position within the already sorted part of
the list. It can be used to sort items in an
online fashion, as in the user inputting a list
or input from an outside device, a lot
quicker that most other sorts.
Selection Sort
The Selection sort is somewhere between
the insertion sort and bubble sort; it scans
over the remaining unsorted list to find the
smallest item and place it at the beginning.
Selection sort is also often referred to as
Exchange sort because of the method in
which items are not shifted up and down
but rather will exchange positions to place
an item in the correct place.
Heap Sort
The Heap sort has a two-step method of
sorting; first, the list is semi sorted to build a
parent-child tree within the list. Then, the
parent child tree is used to sort the list.
 Shell Sort
The Shell sort improves the Insertion sort by
doing comparisons separated by a gap of
several positions, with each pass progressively
reducing the gap.
 Quick Sort
The Quick sort, also known as a Stack sort,
partitions the list on a random pivot point,
placing all items smaller or larger on either side
of the pivot, and then recursively calls itself
passing over the split lists. The recursive calls
continue until the algorithm receives a list
where there are only one or two items in it, at
which time this part of the list is sorted into the
correct position
LINKING
DATABASES
USING DAO, RDO, AND ADO

You may wonder why there are three different sets of database object in visual basic, the reason
is historical.

 At first, VB only supported DAO, which connected to the Microsoft Jet database engine in
MS Access, Open database connectivity (ODBC) standard and supported ODBC with
Remote Data
Objects in Visual Basic.

 Active Data Object (ADO) allows connections on the same computer, over networks and
through the web, and is intended to support ODBC. ADO is also called OLE DB, and in fact,
it’s based on COM programming techniques.
There are two ways to work with DAO, RDO and ADO object sets in VB.

1) The first way is working with the special controls, Data Control, Remote Data Control
and ADO data control. You use them to connect to and to move through database
without displaying the actual data instead other Visual Basic controls, and those bound
controls handle the display.

2) The second way is working with the three database object sets directly in code, without
controls like the data control or DAO data control.
 What are Databases?
Nearly all business applications need to store large volumes of data,
organized in a format that simplifies retrieval. This is accomplished with
a database management system (DBMS), a mechanism for
manipulating tabular with high-level commands.
The database management system hides low-level details, such as
how data are store in a database, and frees the programmers to
concentrate on managing information, rather than on the specifics of
manipulating files or maintaining links among them.
 Database architectures
1. Centralized System Architecture:
Merits of Centralized System Architecture
• Excellent Security
• Centralized administration as both application logic and data reside
on the same machine
De-Merits of Centralized System Architecture
• Mainframe computers are very expensive to buy, lease, maintain
and use.
• The limitation is that both the application and the database live
within the same machine process
2) File Server Architecture
The application logic now executed on the client
workstation instead
of the server. These servers also provided access to
computing resources like printer and large hard disk.
The merit of the file server system
 The low cost entry point with flexible arrangement.
 Computer resources can be added or reduced as and
when necessary using this system.
The drawback of the file server architecture
 All application logic is executed on the client machine.
 The job of the server is to provide files only to store the
data.
[Link] server architecture is a
process involving a minimum of
two independent entities, one
is the client and the other is the
server. The client makes a
request to the server and the
server services the requests and
the resulting data is sent to the
client.
LINKING DATABASE
 Open Database Connectivity (ODBC) Open database connectivity (ODBC) is
a windows technology that lets a database client application connect to
external database.
 To use ODBC, database vendor must provide an ODBC driver for data
access.
 Once this driver is available, the client machine should be configured with this
driver.
 Creating ODBC Data Source Before any application can access an ODBC
database, the ODBC driver must be installed and a Data source name (DSN)
created using the control panel. The DSN is used whenever a reference is
made to an ODBC database. Follow these steps to create ODBC for Access
1) Double click on ODBC configuration option under control panel.
2) Select Add button to add new ODBC drivers that are currently installed in
system are displayed
3) Select Microsoft Access Driver (*.mdb) from list and click on Finish button.
4) Type any Data source name and select database for which you want to
create DSN by clicking on Select button.
5) Click on OK button to complete process.
 Using ODBC with DAO The properties and methods of DAO can be used in
conjunction with ODBC database. Creating ODBC Data Source Before
any application can access an ODBC database, the ODBC driver must
be installed and a Data source name (DSN) created using the control
panel. The DSN is used whenever a reference is made to an ODBC
database. Follow these steps to create ODBC for Access
1. Double click on ODBC configuration option under control panel. A list of
ODBC data source is displayed
2. Select Add button to add new ODBC drivers that are currently installed in
system are displayed
3. Select Microsoft Access Driver (*.mdb) from list and click on Finish button.
4. Type any Data source name and select database for which you want to
create DSN by clicking on Select button
5. Click on OK button to complete process. Using ODBC with DAO The
properties and methods of DAO can be used in conjunction with ODBC
database.
6. OpenDatabase The OpenDatabase method creates a connection
between the application and the ODBC database and assigns it to a
database type object. Syntax Dim db as Database Set db =
opendatabase (“”, , “” ODBC; UID=; PWD=”)
 Reports
 Emerging trends in visual programming
 Challenges of emerging trends in visual programing
 Coping with challenges of emerging trends in visual programming

You might also like