You are on page 1of 40

Introduction to Computer Programming (Visual Basic) 1 / 40

INTRODUCTION TO COMPUTER PROGRAMMING

Syllabus:

S.No. Content PageNo.


1 Flowcharts 2
2 Introduction to the integrated development environment. 3
3 VB Environment 3
a. Tool Box
b. The Form Window
c. The Code Window
d. The Project Window
e. Properties Window
f. Form Layout Window
g. Menu Bar and Tool Bar
4 A simple program displaying a line of text 11
5 Introduction to visual basic programming 12
a. Constants and Variables
b. Arithmetic operators and Comparison operators.
6 Simple Programs 17
7 Control Structure 25
a. IF—THEN
b. IF. THEN…ELSE
c. Select case
d. Do While…..Loop
e. Do …..Loop While
f. Do Until
g. For….Next
8 Sub procedures 29
9 function procedures 32
10 Strings – Trim, left $, rights$, mid$ functions 33
11 Arrays 35
12 Linking to Access data base 35

Auxeeliya, Ashraph
Dept. of Computer Science
Introduction to Computer Programming (Visual Basic) 2 / 40

1) Flowcharts

Flowchart is a graphical representation of the sequence of operations in an information


system or program. Program flowcharts show the sequence of instructions in a single
program. Different symbols are used to draw each type of flowchart.

A flowchart is also defined as a diagrammatic representation that illustrates the sequence


of operations to be performed to get the solution of a problem. Flowcharts are generally
drawn in the early stages of formulating computer solutions. Flowcharts facilitate
communication between programmers and business people. These flowcharts play a vital
role in the programming of a problem and are quite helpful in understanding the logic of
complicated and lengthy problems. Once the flowchart is drawn, it becomes easy to write
the program in any high level language. Often we see how flowcharts are helpful in
explaining the program to others. Hence, it is correct to say that a flowchart is a must for
the better documentation of a complex program.

Symbols used in flowcharts

A typical flowchart may have the following kinds of symbols:

Start or end of the program

Computational steps or processing function of a program

Input or output operation

Decision making and branching

Connector or joining of two parts of program

• Start and end symbols, represented as ovals or rouned rectangles, usually containg
the word "Start" or "End".
• Arrows, showing what's called "flow of control" in computer science. An arrow
coming from one symbol and ending at another symbol represents that control
passes to the symbol the arrow points to.
• Processing steps, represented as rectangles. Example: Add 1 to X.
• Input/Output, represented as a parallelogram. Examples: Get X from the user;
display X.
• Conditional, represented as a diamond (rhombus). These typically contain a
Yes/No question or True/False test. This symbol is unique in that it has two
arrows coming out of it, usually from the bottom point and right point, one
corresponding to Yes or True, and one corresponding to No or False.

Flowcharts may contain other symbols, such as connectors, usually represented as circles.

Auxeeliya, Ashraph
Dept. of Computer Science
Introduction to Computer Programming (Visual Basic) 3 / 40

Flowcharts are usually drawn using some standard symbols; however, some special
symbols can also be developed when required.

2) Introduction to Integrated Development Environment

IDE is an acronym for Integrated Development Environment. The IDE is the workbench
on which you make your programs in Visual Basic.

The Visual Basic IDE is a collection of menus, toolbars, and windows that make up your
programming workbench. Each part of the IDE has features that affect different aspects
of your programming activity. The menu bar lets you direct the overall activity and
management of your programming. The toolbar enables you to access much of the menu
bar's functionality through various toolbar buttons. Forms--the basic building blocks of
Visual Basic programs--are presented in a Form window. You use the ToolBox to add
controls to the forms of your project. The Project Explorer displays the projects on which
you're working, as well as the different parts of each of those projects. You browse and
set a control, form, and module's properties within the Properties window. Finally, you
position and view a form or forms onscreen within the Form Layout window. All these
properties of VB are together creating the Visual Basic Environment.

3) Visual Basic Environment

On start up, Visual Basic 6.0 will display the following dialog box as shown in the
following figure. You can choose to start a new project, open an existing project or select
a list of recently opened programs.

A project is a collection of files that make up your application. Now, click on the
Standard EXE icon to go into the actual VB programming environment. (EXE means
executable program).

The Visual Basic Start-up Dialog Box

Auxeeliya, Ashraph
Dept. of Computer Science
Introduction to Computer Programming (Visual Basic) 4 / 40

The Visual Basic Environment consists of the following components:

a. Tool Box
b. The Form Window
c. The Code Window
d. The Project Window
e. Properties Window
f. Form Layout Window
g. Menu Bar and Tool Bar

Menu
Bar Project
Window
Control
Toolbox

Properties
Form Window

a. Tool Box

Visual basic tool box consists of objects, which are used for the programming design.
Each and every object of a toolbox is called a Control.

Pointer Picture
Label Text Box
Group Frame Command Button
Check Box Option/Radio Button
Combo Box List Box
Horizontal Scroll Bar Vertical Scroll Bar
Timer Drive List Box
Directory List Box File List Box
Shape Line
Image Data Control
OLE
Auxeeliya, Ashraph
Dept. of Computer Science
Introduction to Computer Programming (Visual Basic) 5 / 40

Handling some of the common controls

1. The Text Box

The text box is the standard control that is used to receive input from the user as well as
to display the output. It can handle string (text) and numeric data but not images or
pictures. String in a text box can be converted to a numeric data by using the function
Val(text).

2 The Label

The label is a very useful control for Visual Basic, as it is not only used to provide
instructions and guides to the users, it can also be used to display outputs. One of its most
important properties is Caption. You can change its caption in the properties window and
also at runtime.

3. The Command Button

The command button is a very important control as it is used to execute commands. It


displays an illusion that the button is pressed when the user click on it. The most common
event associated with the command button is the Click event, and the syntax for the
procedure is
Private Sub Command1_Click ()
Statements
End Sub

4. The Picture Box

The Picture Box is one of the controls that used to handle graphics. You can load a
picture at design phase by clicking on the picture item in the properties window.

5. The Image Box

The Image Box is another control that handles images and pictures. It functions almost
identically to the picture box. However, there is one major difference, the image in an
Image Box is stretchable, which means it can be resized. This feature is not available in
the Picture Box.

6. The List Box

The function of the List Box is to present a list of items where the user can click and
select the items from the list. In order to add items to the list, we can use the AddItem
method. For example, List1.AddItem (“Lesson1”)

Auxeeliya, Ashraph
Dept. of Computer Science
Introduction to Computer Programming (Visual Basic) 6 / 40

7. The Combo Box

The function of the Combo Box is also to present a list of items where the user can click
and select the items from the list. However, the user needs to click on the small
arrowhead on the right of the combo box to see the items which are presented in a drop-
down list. In order to add items to the list, you can also use the AddItem method. For
example, if you wish to add an item to Combo box 1, you can key in the following
statement, Combo1.AddItem “Item1”

8. The Check Box

The Check Box control lets the user to select or unselect an option. When the Check Box
is checked, its value is set to 1 and when it is unchecked, the value is set to 0. You can
include the statements Check1.Value=1 to mark the Check Box and Check1.Value=0
unmark the Check Box, and use them to initiate certain actions.

Example
Private Sub Check1_Click ()
If Check1.Value = 0 Then
Form1.BackColor = vbRed
ElseIf Check1.Value = 1 Then
Form1.BackColor = vbBlue
End If
End Sub

9. The Option Box

The Option Box control also lets the user selects one of the choices. However, two or
more Option Boxes must work together because as one of the Option Boxes is selected,
the other Option Boxes will be unselected. In fact, only one Option Box can be selected
at one time. When an option box is selected, its value is set to “True” and when it is
unselected; its value is set to “False”.

10. The Drive List Box

The Drive ListBox is used to display a list of drives available in your computer. When
you place this control into the form and run the program, you will be able to select
different drives from your computer as shown in the following figure.

Figure The Drive List Box

Auxeeliya, Ashraph
Dept. of Computer Science
Introduction to Computer Programming (Visual Basic) 7 / 40

3.2.10 The Directory List Box

The Directory List Box is used to display the list of directories or folders in a selected
drive. When you place this control into the form and run the program, you will be able to
select different directories from a selected drive in your computer as shown in the
following figure.
Figure. The Directory List Box

11. The File List Box

The File List Box is used to display the list of files in a selected directory or folder. When
you place this control into the form and run the program, you will be able to a list of files
in a selected directory as shown in the following figure.

Figure The File List Box

You can coordinate the Drive List Box, the Directory List Box and the File List Box to
search for the files you want.

b. The Form Window

The Form window is the window or background, where the user can design his form
using various controls from the toolbox.

Auxeeliya, Ashraph
Dept. of Computer Science
Introduction to Computer Programming (Visual Basic) 8 / 40

c. The Code Window

After designing the form, the next step will be code writing. The Code window is the
place where all the coding of every form will be written.

Auxeeliya, Ashraph
Dept. of Computer Science
Introduction to Computer Programming (Visual Basic) 9 / 40

d. The Project Window

The Project Window can be used to navigate between the code and form window for each
form / window a project has.

It is also a list of the files which are


currently being used by the
project

❖ Project file is basically a list of


files used

❖ With each form being saved as


a separate file

❖ And any other files are also


listed in the project file e.g.
a module which we will meet
later

Add a form from the Project Explorer

1. Position the pointer on the white area of the Project window (not over a form or
any other item on the tree view).
2. Right-click to display the Project Explorer context menu.
3. Choose Add and then Form.

You can add or remove projects, forms, and modules to or from the Project Explorer
by using its context menu.

Auxeeliya, Ashraph
Dept. of Computer Science
Introduction to Computer Programming (Visual Basic) 10 / 40

e. Properties Window

The properties window is,

❖ Used to set how a control looks and


behaves

❖ Holds its default values

❖ The default values of the properties can be


changed or set during design time.

For example, the setting the BackColor property


will change the colour of the control during design
time itself. You can also change the properties at
runtime to give special effects such as change of
color, shape, animation effect and so on.

f. Form Layout Window

❖ It allows Allows the setting of the default


position of forms (windows) on the screen

❖ Drag and drop the forms within


this window to set there postion

g. Menu Bar and Tool Bar


y
The Menu Bar consists of 3 elements the
1. Title Bar, which holds the name of application
2. Menu Bar, this is the link to Visual Basics menu facilities, each menu
option drops down into sub-menus
3. Toolbar, contains icons which give access to the more commonly used
commands (which are also available through the menu bar)

Title bar Menu Bar Toolbar

Auxeeliya, Ashraph
Dept. of Computer Science
Introduction to Computer Programming (Visual Basic) 11 / 40

The menu bar presents the Visual Basic menus. Here is a list of those menus and what
they do:
File - File handling and printing; also used to make EXE files
Edit - Standard editing functions, undo, searches
View - Displays or hides windows and toolbars
Project - Sets project properties, adds/removes forms and modules, and
adds / removes references and components
Format - Aligns or sizes controls
Debug - Starts/stops debugging and stepping through programs
Run - Starts a program, or compiles and starts it
Tools - Adds procedures, starts the Menu Editor, sets IDE options
Add-Ins - Add-in manager, lists add-ins like Application Wizard and API
Viewer
Window - Arranges or selects open windows
Help - Handles Help and the About box

4) A simple program displaying a line of text


This program is to display a single line of text, which is going to be typed in a text box, in
a label box when a button is pressed. To achieve this application design your form by
placing the following controls and follow the below given steps.
• A Label box
• A Text box
• A Command Button

Step1: Change the Caption and Name properties of the command button into
DisplayName
Step2: Double clicking the command button will take you to the code window, to write a
code in the click event of the DisplayName button. Write the following code:

Private Sub DisplayName_Click()


Label1.Caption = "Name is " + Text1
End Sub

In this code, the text value of the textbox named Text1 will be given to the Caption
property of the label box. The “+” sign is used to concatenate two strings.

Auxeeliya, Ashraph
Dept. of Computer Science
Introduction to Computer Programming (Visual Basic) 12 / 40

5) Introduction to visual basic programming


Background to Visual Basic

Visual basic has the base programming language called BASIC (Beginners All-purpose
Symbolic Instruction Code). It is a simple programming language developed in the mid
1960’s. Simplicity of BASIC made it a natural choice as a programming language.

Visual Basic was developed in-house at Microsoft. It is preferred by most application


software builders because of its,
– Interface design
– Simple coding
– Quickness to produce programs

Editions and Versions of VB

There have been several versions of VB


– Version 1
– Version 2
– Version 3
– Version 4
– Version 5
– Latest version is VB version 6

There are also several editions with each version


❖ Learning edition - , which is the most basic edition. This edition allows you to
write many different types of programs, but lacks a number of tools that the
other editions have.

❖ Standard edition - entry level versi von

❖ Professional edition - designed for professionals. This edition contains all that
the Learning Edition contains and more, such as the capability to write
ActiveX controls and documents. It is required for certain database
functionality

❖ Enterprise edition which is the most complete Visual Basic edition. This
edition is targeted towards professional programmers who may work in a
team and includes additional tools such as Visual SourceSafe, a version-
control system that coordinates team programming.

Concepts of Visual Basic


1) Controls
❖ Every graphical object is a ‘control’
– Form,
– Text box,
– Command Button,

Auxeeliya, Ashraph
Dept. of Computer Science
Introduction to Computer Programming (Visual Basic) 13 / 40

– Label,
– etc

❖ Controls have
– Properties : determine how control looks / interacts
– Events : are things that can be done to a control
– Methods : routines which can be done to a control

2) Properties
❖ Properties describe the characteristics of a control, these can be
– physical characteristics such as height, width and colour
– or its current state such as enabled, or links definitions to other
applications
❖ Note the name and caption properties of a control have the same default values
but are actually quiet different.
– The name is what code uses to reference the control, whereas
– the caption is purely what is written on the control so the user can identify
it
❖ properties can be changed either at design time or at run time

3) Events
❖ In order to implement these blocks of code in Visual Basic
– Controls have pre-defined ‘events’ e.g. Click, Change etc
– Code can be attached to an event
– When an event occurs
i. if code has been attached it is executed,
ii. e.g when a command button is clicked using a mouse, the ‘click
event’ is invoked, so any code under the command buttons click
event is executed
iii. otherwise default processing takes place
iv. e.g. in terms of click event, if no code is attached nothing happens
Some VB events for a form object are:

Auxeeliya, Ashraph
Dept. of Computer Science
Introduction to Computer Programming (Visual Basic) 14 / 40

Aligning, Sizing, And Spacing Multiple Controls

Visual Basic is very...well...visual, and that includes the layout of controls in your
programs. If you’ve got a number of controls that should be aligned in a straight line, it
can be murder to have to squint at the screen, aligning those controls in a line down to the
very last pixel. Fortunately, there’s an easier way to do it:

1. Hold down the Ctrl key and click all the controls you want to align.

2. Make sure you have one control in the correct position, and click that one last. Sizing
handles, the eight small boxes that you can grasp with the mouse to resize a control,
appear around all the clicked controls.

To align all the selected controls to the same left, right, or center position of the key
control, you continue with these steps:

3. Select the Align item in the Format menu, open the Align submenu,

4. Select the type of alignment you want in the Align submenu: align the left, the center,
the right, the top, the middle, or the bottom edges of the controls with the key control.

5. While the controls are still collectively selected, you can move them, if you like, as a
group to any new location now that they are aligned as you want them.

To size all selected controls the same as the key control, follow Steps 1 and 2, and then
continue this way:

3. Select the Make Same Size item in the Format menu, open that submenu

4. Choose the appropriate item in the Make Same Size submenu to size the controls
as you want them: matching the key control’s width, height, or both.

To space multiple controls vertically or horizontally, follow Steps 1 and 2 and then
continue:

3. Select the Horizontal Spacing or Vertical Spacing item in the Format menu,
open that submenu.

Spacing controls.

4. To space the controls horizontally or vertically, select one of the items in the
corresponding submenu:
" Make Equal_Sets the spacing to the average of the current spacing
" Increase_Increases by one grid line
" Decrease_Decreases by one grid line
" Remove_Removes spacing

Auxeeliya, Ashraph
Dept. of Computer Science
Introduction to Computer Programming (Visual Basic) 15 / 40

Saving a VB project

❖ The best way to organise your projects is by keeping each project in a separate
directory on your floppy disk.
❖ When you come to save the project you will be saving a number of files:
– FORM1.FRM the form itself
– MODULE. BAS module file if any
– PROJECT1.VBP the project file
❖ If you select ‘Save Project’ from the ‘File’ Menu, it will save all your files

a. Constants and Variables

Constants are values which will not be changed through out the program. Use
constants and declare them all in one place, then refer to the constants by name
throughout the code instead of hardwiring numeric values in the code.

Constants can be declared in Visual Basic with the Const statement:

[Public | Private] Const constname [As type] = expression

The Public keyword is used at the module level to make a constant global. The
Private keyword is used at the module or form level to declare constants that are
private, which means only available within the module or form where the declaration
is made. These keywords are not allowed in procedures. (constants in procedures are
always private anyway).

The constname identifier is the actual name of the constant. The type identifier is the
data type of the constant, which may be Integer, Long, Currency, Single, Double,
Date, String, etc. The expression identifier holds the value you want for this
constant.

When you want to modify the value of the constant, you only have to change it in its
declaration, not in many places around the program. Also, constants don’t change
their values.

Here’s an example showing how to declare and use a constant:

Private Sub Command1_Click()


Const Pi = 3.14159
Dim Radius, Area
Radius = 1
Area = Pi * Radius * Radius
MsgBox ("Area = " & Str(Area))
End Sub

Auxeeliya, Ashraph
Dept. of Computer Science
Introduction to Computer Programming (Visual Basic) 16 / 40

Constants can also be defined without the keyword Const.

Example:
C=10 ‘ here C is a numeric constant
A=”UNR” ‘ here A is an string constant

Variables are some user defined names which can be given different values by the
user in the same program. The Dim statement is used in VB to declare variables.

In Visual Basic a variable can be declared in two ways. They are


i) Implicit Declaration:
You can just use any name. Variable type determined by the data assigned

Name = “John” ‘ Name is a String variable here


Value = 10 ‘ Value is an Integer Variable here
ii) Explicit Declaration:
You must pre-declare any variables used: Here’s an example of declaring
variables using Dim:

Dim EmployeeID As Integer ‘ to store numbers


Dim EmployeeName As String ‘ to store names

❖ Variables can be declared in a control event procedure


❖ In this case they are only available within the procedure in which they are
declared

❖ Variables can also be declared in the general declarations section of a form


❖ In this case they are available anywhere within the form in which they are declare

Auxeeliya, Ashraph
Dept. of Computer Science
Introduction to Computer Programming (Visual Basic) 17 / 40

b. Arithmetic operators and Comparison operators.

Arithmetic operators
These operators are used to perform mathematical calculations.

Arithmetic operation Symbol Example


_____________________________________________________
Exponentiation ^ 2^3 = 8 (2*2*2)

Multiplication & division *, / 2/4 = 0.5


Addition & subtraction +, - 2+2=4

Modulo arithmetic Mod 7 Mod 2 = 1 (remainder 1)

Comparison operators
These are operators which are used to compare two numbers, names, etc.,
> greater than
< less than
= is equal to
>= is greater than or equal to
<= is less than or equal to
<> is not equal to
Example:
If ( Age = 10 ) Then
If ( Marks >= 40 ) Then

6. Simple Programs
Exercise 1:
Program using Check Box and Option Button.

Controls:
Place the following controls in your form and change the below mentioned
properties as shown in the table.
Control Name Caption
Label Box Label1 Degree
Label Box Label2 Courses
Text Box Text1
Option Button Option1 Bachelor
Option Button Option2 Master
Option Button Option3 Doctor
Check Box Check1 C++
Check Box Check2 Java
Check Box Check3 VB
Command Button ResultOfOption ResultOfOption
Command Button ResultOfCheck ResultOfCheck

Auxeeliya, Ashraph
Dept. of Computer Science
Introduction to Computer Programming (Visual Basic) 18 / 40

Objective of the program:

When you click the command button ResultOfOption it has to display a


message box to tell which option button (Degree) is selected. When you
click the command button ResultOfCheck the status (selected / not
selected) of the three check boxes should be displayed in the text box.

Coding:

Write the following codes in the code window.


Private Sub ResultOfCheck _Click()
If Check1.Value = 1 Then
Text1.Text = "C++ is elected"
Else
Text1.Text = "C++ is not selected"
End If

If Check2.Value = 1 Then
Text1.Text = Text1.Text + " Java is selected"
Else
Text1.Text = Text1.Text + " Java is not selected"
End If

If Check3.Value = 1 Then
Text1.Text = Text1.Text + " VB is selected"
Else
Text1.Text = Text1.Text + " VB is not selected"
End If
End Sub

Private Sub ResultOfOption _Click()


If Option1.Value = True Then
MsgBox ("Bachelor Degree is selected")
ElseIf Option2.Value = True Then
MsgBox ("Master Degree is selected")
Else
MsgBox ("Doctor Degree is selected")
End If
End Sub

Auxeeliya, Ashraph
Dept. of Computer Science
Introduction to Computer Programming (Visual Basic) 19 / 40

Exercise 2:
Program using Frames.

Controls:
Place the following controls in your form and change the below mentioned
properties as shown in the table.

Control Name Caption


Label Box Label1 Working with Frames
Option Button Option1 FESG
Option Button Option2 Applied Science

Frame Frame1 FESG


Inside Frame1 create the following controls
Label Box Label2 Management
Label Box Label3 Economics .
Label Box Label4 Statistics .

Frame Frame2 AS
Inside Frame2 create the following controls
Label Box Label5 Computer Science
Label Box Label6 Electronics .
Label Box Label7 Civil Engineering

Auxeeliya, Ashraph
Dept. of Computer Science
Introduction to Computer Programming (Visual Basic) 20 / 40

Objective of the program:


When you click the option button Option1 it has to display Frame1 with
its details where as if you click the option button Option2 it has to display
Frame2 with its details.
Coding:

Write the following codes in the code window.

Private Sub Form_Paint()


Frame1.Visible = False
Frame2.Visible = False
End Sub
Private Sub Option1_Click()
Frame1.Visible = True
Frame2.Visible = False
End Sub
Private Sub Option2_Click()
Frame2.Visible = True
Frame1.Visible = False
End Sub

Auxeeliya, Ashraph
Dept. of Computer Science
Introduction to Computer Programming (Visual Basic) 21 / 40

Exercise 3:
Program using Combo Box and List Box.

Controls:
Place the following controls in your form and change the below mentioned
properties as shown in the table.

Control Name Caption


Label Box Label1 List Box
Label Box Label2 Combo Box
Text Box Text1
Text Box Text2
Text Box Text3
Command Button AddTextToList Add Text to List
Command Button DisplayFromList Display from List
Command Button AddTextToCombo Add text to Combo
List Box List1
Combo Box Combo1
Objective of the program:
When you click the command button AddTextToList it has add the text
typed by the user in Text1 into the list box. When you click the command
button DisplayFromList after selecting an item from the list box, that item
should be displayed in the text box Text2. When you click the command
button AddTextToList it has add the text typed by the user in Text3 to the
Combo box. A piece of code should be added in Form Load to add some
items into the list box when the execution begins.
Coding:
Write the following codes in the code window.
Private Sub AddTextToCombo_Click()
Combo1.AddItem (Text2)
End Sub

Private Sub AddTextToList_Click()


List1.AddItem (Text1)
End Sub

Private Sub DisplayFromList_Click()


Dim n As Integer
For n = 0 To List1.ListCount - 1
If List1.Selected(n) = True Then
Text3.Text = List1.List(n)
End If
Next
End Sub

Auxeeliya, Ashraph
Dept. of Computer Science
Introduction to Computer Programming (Visual Basic) 22 / 40

Private Sub Form_Load()


List1.AddItem ("Sugar")
List1.AddItem ("Rice")
List1.AddItem ("Coffee")
List1.AddItem ("Tea")
List1.AddItem ("Salt")
End Sub

Exercise 4:
Creating menus in VB

A Typical Drop-down menu

Menu Shortcut
bar s

Cascading Checked
Menus option

Separator Disabled
bar Options

Auxeeliya, Ashraph
Dept. of Computer Science
Introduction to Computer Programming (Visual Basic) 23 / 40

How to go to Menu Editor?

To go to the Menu Editor do any one of the following steps.


• Right click on any blank area of the form, choose Menu Editor from the
pop up menu.
• Click on the Menu Editor icon on the standard tool bar.
• Click on Tools menu.

The Menu Design Window

Creating the first option

Caption, to go on
menu

“Internal” name for option


(used in programming -
choose
a meaningful name)

Update the “Index”


value (optional)

Caption value “echoed”


here
Auxeeliya, Ashraph
Dept. of Computer Science
Introduction to Computer Programming (Visual Basic) 24 / 40

Adding further options


Press “Next” key to create
another option

Use left/right arrow keys


to
create sub-menus

Select shortcut letter


by
preceding it with “&”.

Option is “enabled” (can be


selected)
and“shortcuts”
Adding “visible” (default values)
Shortcut keys

Shortcut key selection


Inserting another option into the menu

e.g. Select “About” option, then press Insert key.

Auxeeliya, Ashraph
Dept. of Computer Science
Introduction to Computer Programming (Visual Basic) 25 / 40

Example:
Objective of the program:

To change the background colour of the form when depends on the menu item
you click.

Menu items

Create menus and submenus as directed below using the Menu Editor

Color
…FormColor
……Red
……Blue
……Green
Window
….Close
Coding

Add the following codes in the code window

Private Sub Blue_Click()


Form1.BackColor = vbBlue
End Sub
Private Sub Close_Click()
End
End Sub

Private Sub Green_Click()


Form1.BackColor = vbGreen
End Sub

Private Sub red_Click()


Form1.BackColor = vbRed
End Sub

7. Control Structures
i) If….then
If condition Then {actions when condition is TRUE}

Example:
If Marks<40 Then Result = "Fail"

Block form:
If there are many lines under a if statement they can be written inside if block.
This type of block if always requires an endif.

Auxeeliya, Ashraph
Dept. of Computer Science
Introduction to Computer Programming (Visual Basic) 26 / 40

If condition Then
{action 1 when condition is TRUE}
{actions ... when condition is TRUE}
End If

Example:
If (iMarks<40) Then

ii) If….then ….else

If condition Then {TRUE action} Else {FALSE action}

Example:
If Marks<40 Then Result= "Fail" Else Result = "Pass"

Block form:
If ( condition ) Then
{actions ... when condition is TRUE}
Else
{actions ... when condition is FALSE}
End If

Example:
If (iMarks<40) Then
Result = "Fail"
Grade = “B”
Else
Result = "Pass"
Grade = “A”
End If

iii) Select – Case

Select Case is similar to if statements but simpler than that. The simplest form of
the Select statement is:

Select Case test expression


Case expression list
{actions ... when expression list is equal to the test expression }
Case expression list
{actions ... when expression list is equal to the test expression }
End Select

Auxeeliya, Ashraph
Dept. of Computer Science
Introduction to Computer Programming (Visual Basic) 27 / 40

Example:

Code=4
Select Case Code
Case 1
form1.backcolor=QBColor (1)
Case 2, 3, 4
form1.backcolor=VbRed
Case 5 To 7
Form1.backcolor=RGB (0, 255, 0)
End Select

Do Loop
– Do Loop structure is used to perform a statement (or set of statements) one
or more times, depending on whether the condition at the top or bottom of
the loop is true or false.
– There are a number of forms of the Do...Loop:
– There are two variations of the Do…Loop statements and both use the
same basic model. A loop can be executed either while the condition is
True or until the condition becomes true.
– These two variations use the keywords While and Until.
– To execute a block of statements while a condition is True, While is used
with DO where as to execute a block of statements until the condition
becomes True, Until is used with Do.

iv) Do while….Loop

Do While condition
statements
Loop

❖ Do While tests condition first


❖ It executes while the condition is True, terminating when it becomes False
❖ Statements within looping structure are only executed if the condition is true

Example:
Sub Command1_Click ()
Dim iCount As Integer
iCount = 100
Do While iCount > 0
Print "iCount = "; iCount
iCount = iCount – 10
Loop
End Sub

Auxeeliya, Ashraph
Dept. of Computer Science
Introduction to Computer Programming (Visual Basic) 28 / 40

v) Do Until….Loop

Do Until condition
statements
Loop

❖ Do Until tests condition first


❖ It executes while the condition is False, terminating when it becomes True
❖ Statements within looping structure are repeatedly executed only if the condition
is False.

Example:
Sub Command1_Click ()
Dim iCount As Integer
iCount = 100
Do Until iCount < 0
Print "iCount = "; iCount
iCount = iCount – 10
Loop
End Sub

vi) Do …Loop While

Do
statements
Loop While condition

❖ Loop while tests condition last


❖ It will always execute at least once
❖ Loop While executes whilst the condition is True,

Example:
Sub Command1_Click ()
Dim iCount As Integer
iCount = 100
Do
Print "iCount = "; iCount
iCount = iCount – 10
Loop while iCount > 0
End Sub

vi) For … Next

❖ The For...Next construct is used to perform a statement (or set of statements) a


fixed number of times

Auxeeliya, Ashraph
Dept. of Computer Science
Introduction to Computer Programming (Visual Basic) 29 / 40

❖ It should be used when you know how may times the loop should be executed
before entering the loop
❖ General structure:

For Count = StartValue To EndValue [Step Increment]


statements...
Next [Count]

❖ Unless a Step is specified the For loop will increment by 1 each time
❖ We can also specify the step size and count backwards:

Example:
Sub Command1_Click ()
Dim iCount As Integer
For iCount = 100 To 0 Step -10
Print "iCount = "; iCount
Next iCount
End Sub

The above examples of different kind of loops are to produce the following result.

8) Sub Procedures

Procedures are useful for implementing repeated tasks, such as frequently used
calculations. If there are some statements that are needed to be repeated many times in a
program, those statements can be written only once as a separate procedure and can be
called anywhere inside the program for any number of times.

Modularity of Code: Sub-Procedures

❖ Sub-Procedure Structure:
Parameters
Sub subname(value1 As type, Value2 As type, etc)
declarations (local)
statements
End Sub

Auxeeliya, Ashraph
Dept. of Computer Science
Introduction to Computer Programming (Visual Basic) 30 / 40

❖ Calling: Arguments
Call subname(value1, value2, etc)
or
subname value1, value2, etc

Exercise
Program using a Procedure

Controls:
Place the following controls in your form and change the below mentioned
properties as shown in the table.

Control Name Caption


Text Box Text1
Command Button 2*2 TwoTwo
Command Button 3*2 ThreeTwo
Command Button 4*2 FourTwo
Objective of the program:
Not to repeat the code for multiplying two numbers in every button.
Instead write a procedure for multiplication and to call that procedure in
every button.

Coding:
Write the following codes in the code window.

Private Sub FourTwo_Click()


Multiply 4, 2
End Sub

Private Sub ThreeTwo_Click()


Multiply 3, 2
End Sub

Private Sub TwoTwo_Click()


Multiply 2, 2
End Sub

The above codes will be executed when the respective command buttons are
clicked. This code executes Multiply procedure.

You have to now add a new procedure to your form and have to name it Multiply.

Auxeeliya, Ashraph
Dept. of Computer Science
Introduction to Computer Programming (Visual Basic) 31 / 40

To add a new procedure,


i. Double click the form to display the code window and then select Add
Procedure from the Tools menu. (Visual Basic responds by
displaying the Add Procedure dialog box)

ii. Type Multiply in the Name box of the dialog box.


iii. Set the Type of the procedure to Sub and make sure the Scope is Public.
iv. Click Ok. (Visual Basic responds by adding the Multiply() procedure in
theCode window as follows)

Public Sub Multiply()


End Sub

v. Now the following code should be added between the parenthesis of the
first line of the Multiply procedure as follows.

Public Sub Multiply(X As Integer, Y As Integer)


End Sub

vi. Type the following code in the Multiply procedure

Public Sub Multiply(X As Integer, Y As Integer)


Dim Z As Integer
Z=X*Y
Text1 = Z
End Sub

Auxeeliya, Ashraph
Dept. of Computer Science
Introduction to Computer Programming (Visual Basic) 32 / 40

9) Function Procedures

A Function is similar to a Procedure, but a function returns a result. Procedures perform


task and don’t report anything to the calling program; functions commonly carry out
calculations and report the result to the calling program. You call a Function procedure
using the function name, followed by the argument list in parentheses. Finally, End
Function ends the procedure definition.

❖ Passes back a value to the calling procedure


❖ Calling:
– variable = funcname( value1, value2, etc)
❖ Function structure:
– Function funcname( value1 As type, value2 As type, etc) As type
statements
funcname = returnvalue
End Function

Exercise

Follow the same steps of the exercise for adding Procedure to design the form and
include some small changes in the code window (with Add Procedure dialog box and in
the code for the command buttons) as instructed below.

Coding

Write the following codes in the code window.

Private Sub FourTwo_Click()


Text1 = Multiply (4, 2)
End Sub

Private Sub ThreeTwo_Click()


Text1 = Multiply (4, 2)
End Sub

Private Sub TwoTwo_Click()


Text1 = Multiply (4, 2)
End Sub

The above codes will be executed when the respective command buttons are
clicked. This code executes Multiply function.

You have to now add a new function to your form and have to name it Multiply.
To add a new function, follow the same steps of adding procedure except
choosing the type.

Auxeeliya, Ashraph
Dept. of Computer Science
Introduction to Computer Programming (Visual Basic) 33 / 40

For adding functions, the Type of the Add Procedure dialog box should be
choosen as Function.

Change the code of Multiply function as follows

Public Sub Multiply(X As Integer, Y As Integer)


Dim Z As Integer
Z=X*Y
Multiply = Z
End Sub

The output will be very similar to that of procedures.

10) Strings

String is a data type that stores only text.

Example:
Dim Str as String ‘Str is a string variable which can hold only text value

We can assign any text to the variable Str. We can store nearly 2GB of text in a string
variable. The values of a string variable must always be enclosed by double quotes. The
following assignments are example for some valid string values.

Str = “WELCOME”
Str = “1500”
Str = “Good Morning to Everybody”

Some functions of String

i) Trim
• The Trim() function returns the string without the leading and trailing
spaces.
• The LTrim() funtction returns the string without the leading spaces.
• The RTrim() function returns the string without the trailing spaces.

Examples:
Private Sub Command1_Click()
Dim Str As String
Str = " Welcome to NUR "
Print "ResultOfTrim =" + Trim(Str)
Print "ResultOfLTrim =" + LTrim(Str)
Print "ResultOfRTrim =" + RTrim(Str)
End Sub

Auxeeliya, Ashraph
Dept. of Computer Science
Introduction to Computer Programming (Visual Basic) 34 / 40

ii) Left$
Left$() function is used to extract a substring from the left of the given
string. The parameter is used to say the number of characters to be
extracted.

iii) Right$
Right$() function is used to extract a substring from the right side of the
given string. The parameter in this function is used to tell the number of
characters to be extracted from the right side of the string.

iv) Mid$
Mid$() function is used to extract a substring from the middle of the given
string. In this function two parameters are used. The first is used to tell the
starting character and the second is to tell the number of characters to be
extracted from the first parameter.

Example:
Private Sub Command1_Click()
Dim Str As String
Str = "Welcome to NUR"
Print "Result Of Left$=" + Left$(Str, 3)
Print "Result Of Right$=" + Right$(Str, 6)
Print "Result Of Mid$ =" + Mid$(Str, 4, 7)
End Sub

Auxeeliya, Ashraph
Dept. of Computer Science
Introduction to Computer Programming (Visual Basic) 35 / 40

11) Arrays

A single variable name holding a set of similar values is called array. An array variable
can be declared in a general declaration or a procedure or in a module. We need to say
what the size of the array is when we declare it.

Example:
Dim Count(10) As Integer ‘ an integer array which can store 10 numbers
Dim Names(5) As String ‘ a string array that can hold 5 names

We need to be able to address the individual elements in an array. For that we use the
array name and the element number to access it.

Dim Names(5) As String Names (1) “Jane”

Names(2) = “Pete” (2) “Pete”

Names(3) = “Lucy” (3) “Lucy”


Text1.Text = Names(4) (4) “Dave”
12) Linking to Access data base. (5) “Ian”
Database Concepts
Before linking Visual Basic with Access database, we mmust know some basic concepts
of a database.

What is a Database ?
❖ A Database is a store of information
❖ Databases are divided into one or more tables
❖ Each table consists of a series of records
❖ Each record contains a number of distinct fields

What is a Field ?
❖ Fields are a store for an individual item of data
e.g. they may contain someones name or their age
❖ For example an name field could contain the name “Jeremy”
❖ Or an age field could contain the number 18

Name field “Jeremy”


Age field 18

❖ Each field contains a specific data type e.g. a string or a number

Auxeeliya, Ashraph
Dept. of Computer Science
Introduction to Computer Programming (Visual Basic) 36 / 40

What is a Record ?
❖ A Record is a collection of fields , which describe some entity
❖ For example a book can be described as having a
– Title
– Author
– ISBN
Book Record

Title Author ISBN Publisher


– Publisher

What is a Table ?

❖ A table is a collection of related records


❖ For example all the records for books in a library would make up a table

Table of books
Title Author ISBN Publisher
Oliver Charles Dickens 012-9877-5643 McGraw Hill
VB Design John Smith 230-7692-1287 Prentice Hall
: :
: :
: :
: :
Pasta Fasta Gill Jones 890-6023-5028 Penguin

Multiple Tables
❖ Databases are made up of one or more tables
❖ Databases should be divived into tables containing a related type of data e.g.
A company could have a staff database, split into tables as below for different
departments to access

Training Courses Salaries


(Training Dep’t) (Finance)

Personal Details Company


(Personnel) Staff Database

Access Connectivity

• A powerful feature of VB is its ability to access the contents of various databases.


• It is possible to use the Microsoft Access Engine to access, display and alter the
contents of a database.
• VB can be used to create a front-end interface for database tables.

Auxeeliya, Ashraph
Dept. of Computer Science
Introduction to Computer Programming (Visual Basic) 37 / 40

• VB includes a control object called the Data Control which acts as a ‘bridge’
between VB and Access.
• This permits information from a database to be linked with normal objects on a
form e.g. text boxes, labels etc.
• This linking includes three major steps.
• Creating an Access database (we can also use a database which already
exists)
• Design the Visual Basic form according to the fields of the Access
database you want to connect.
• Connecting the VB form to the Access database using Data Control.

Creating an Access database

Creating an access database from the Visual Basic interface includes the following steps.

• Click on Add-Ins menu on the menu bar.


• Select Visual Data Manager. This will display a VisData dialog box.

• In that select File, New, Microsoft Access, Version 7.0 MDB.

• This action will display the create database window, where you have to type the
database name.

Auxeeliya, Ashraph
Dept. of Computer Science
Introduction to Computer Programming (Visual Basic) 38 / 40

• In the database window, right click and click New Table, give a name for your
table to create a new table and to add fields for that table.

• After creating the necessary fields for the table click Build the table to construct

the table structure.

• Once the table is created double click on the table name to open the table and data
can be added to that table by clicking the add and update buttons.

Auxeeliya, Ashraph
Dept. of Computer Science
Introduction to Computer Programming (Visual Basic) 39 / 40

Using the Data Control to Connect to a DB

• A data control like the following should be placed in the VB form.


• The buttons move the data control to the beginning, end and next records in the
database.

• The DB name is defined in the DatabaseName property of the Data Control.


• It is also necessary to identify the table to be accessed.
• This is defined in the RecordSource property.
• Little or no coding is required to access the DB.
• Once the DB and table have been identified, the information can be displayed on
the interface.

Accessing data from the DB

• Once the data control has been initialized it is possible to access the information.
• No VB code is required, only the use of the properties window.
• E.g. to display the value of a field from the DB in a text box:
• add a text box to the form
• select the properties window
• set the DataSource to the name of the data control
• set the DataField to the field in question from the DB.

Manipulating Databases

• In addition to viewing the contents of a database it is also possible to add, delete


and modify its contents.
• In a user interface it may be the case that the user cannot see the data control.
• This can be achieved by setting its properties (visible) to ‘False’.
• VB has a number of reserved words to perform the actions of the Data Control:

• Data1.Recordset.MoveFirst - moves to first record in DB table


• Data1.Recordset.MoveLast - moves to the last record
• Data1.Recordset.MoveNext - moves to the next record

Auxeeliya, Ashraph
Dept. of Computer Science
Introduction to Computer Programming (Visual Basic) 40 / 40

• Data1.Recordset.MovePrevious - moves to the previous record


• Data1.Recordset.AddNew – to add a new record.

Visual Basic Links to Database - Recordset

• A recordset is a set of data from a database table or query to which Visual


Basic links
• A recordset can be thought of as a two dimensional array of data. where
the rows are records and columns are fields

• Data Controls create a recordset, but this is invisible to the programmer.


• Recordsets can also be created using code

Auxeeliya, Ashraph
Dept. of Computer Science

You might also like