Sie sind auf Seite 1von 43

Notes For Visual Basic 6.0 1 P.


Introduction to Visual Basic 6.0

Visual basic is an ideal programming language for developing sophisticated professional applications
for Microsoft windows. It makes use of graphical user interface for creating robust and powerful
applications. Coding in GUI environment is easy and quicker as compare to traditional, linear programming
Visual Basic was developed from BASIC programming language. It required at least Microsoft
windows 95/NT 3.51, 486 processor and minimum of 16 M.B. of RAM and also 250 MB of hard disk to
install complete enterprise edition.

Starting Visual Basic 6.0

Visual Basic is initiated by using the Program option -> Microsoft Visual Studio and Microsoft
Visual Basic 6.0 from it. Then it opens into a screen as shown below (fig 1.1)
Fig .1.1

The integrated Development Environment

One of the most significant changes in visual basic 6.0 is the integrated Development Environment (IDE).
IDE is the term commonly used in the programming world to describe the interface and environment that we
use to create our applications. It is called integrated because we can access virtually all of the development
tools that we need from one screen called an interface.
The visual basic IDE is made up of a number of components
Menu Bar
Tool Bar
Project Explorer
Properties Window
Form layout Window
Form Designer
Object Browser
Menu Bar

KIMS Dergee &PG College

Notes For Visual Basic 6.0 2 P.MallaReddy

This is bar display the commands that are required to build an application. The main menu items have sub
menu items that can be chosen when needed.

Tool Bar
The toolbar in the menu bar provide quick access to the commonly used commands.

The toolbox contains a set of controls that are used to place on form at design time thereby creating the user
interface area. Additional controls can be included in the toolbox by using the Components menu item of the
Project menu. A toolbox is represented in fig 1.2

Pointer Picture
Label Textbox

Frame CommandButton
Shape Line
Image Data

Fig 1.2

The pointer provides a way to move and resize the control and forms.
Label display a text that the user cannot modify or interact with.
Frame control serves as a visual and functional container for control.
Checkbox display a True/False or yes/no option.
Textbox is a control used to display message and enter text.
The Listbox display a list of items from which a user can select one.
ComboBox contains a textbox and Listbox. This allows the user to select an item from Dropdown
Listbox, or to type in a selection in the textbox.
HScrollBar and VScrollBar controls allow the user to select a value within the specified range of
Timer control executes the timer events at specified intervals of time.
Dirlistbox allows the user to select the directories and paths, which are displayed
Shape control use to draw shape on form.
Image control is used to display icons, bitmaps, metafiles etc

KIMS Dergee &PG College

Notes For Visual Basic 6.0 3 P.MallaReddy

OLE control is used to link or embed an object, display and manipulate data from other windows
based applications.
Picturebox displays icons/bmp/jpg and metafiles. It displays text or acts as a visual container for
other controls.
CommandButton control which is a part of an option group allows the user to select only one option
even if it display multiple choices.
The FileListBox display a set of files from which user can select the desired one.
The DriveListBox display the valid disk drives and allows the user to select one of them.
Line control to draw a line on form.
Data control enables the user to connect to an existing database and display information from it.

Project Explorer
Docked on the right side of the screen, just under the toolbar, is the
project Explorer window. It display objects of your project like forms,
classes and modules. All the object that make up the application are
packed in a project.

Fig 1.3 (project explorer )

Properties Window
The properties window is docked under the project explorer window.
The properties windows exposes the various characteristics of selected

Fig 1.4 ( Properties window )

Form Layout
The form layout window use to place the form starting position after
you runs it.

Fig 1.5 (Form layout window)

Variables, Data Types and Modules

Variable are used for storing values temporarily. Declaring a variable tells Visual basic to reserve
space in memory. It is not must that a variable should be declared before using it.
A defined naming strategy has to be followed while naming a variable.
1. A variable name must begin with alphabet letter and should not exceed 255 characters.
KIMS Dergee &PG College
Notes For Visual Basic 6.0 4 P.MallaReddy

2. It must be unique within the same scope.

3. It should not contain any special character like %,&, #, @ or $
Dim variable [as type]
For e.g
Dim str as string
Dim I as integer

Scope of variables
A variable is scoped to a procedure-level(local) or module-level depending on how it is declared. A
variable is declared in general declaration section of a Form, and hence is available to all the procedures.
Local variable are recognized only in the procedure in which they declared. They can be declaring with dim
and static keyword.

Local Variable: Local variable is one that is declared inside a procedure. This variable is only
available to the code inside the procedure and can be declared using dim statement as given below

Dim I as integer

Static Variables
Static variables are not reinitialized each time visual basic invokes a procedure and thus retains or
preserves value even when a procedure ends.
Static in as integer

Module Level Variables

Module level variables are available to all the procedure in the module. They are declared using
Public or private keyword.
public nk as integer
private st as string
declaring a variable with public keyword makes it available throughout the application even for the other
modules. A variable can have same name with different scope.
Data Type:
By default Visual Basic variables are of variant data types. The variant data type can store numeric,
date/time or string data. When a variable is declared, a data is supplied for it that determines the kind of data
they can store.
A list of visual basic data types are given below

Type Name Values Range

Byte 0 to 255
Boolean True or False
Integer -32,768 to 32,767
Long -2,147,483,648 to 2,147,483,647
Single -3.402823 * 103 to -1.401298 * 10 45 for negative values.
1.401298 * 10-45 to 3.402823 * 10 38 for positive values.
Double -1.79 * 10 308 to -4.94 * 10 -324 for negative values
4.94 * 10 -324 to 1.79 * 10 308 for positive values
Date January 1, 100 to December 31, 9999
KIMS Dergee &PG College
Notes For Visual Basic 6.0 5 P.MallaReddy

String 0 to approximately 2 billion characters

Currency -922,337,203,685,477.5808 to 922,337,203,685,477.5807

Data Type Conversion

Visual Basic functions either to convert a string into an integer or vice versa and many more conversion
functions. A complete listing of all the conversion functions offered by visual basic is elucidated below.

Conversion To Function
Boolean Cbool
Byte Cbyte
Currency Ccur
Date Cdate
Decimals Cdec
Double Cdbl
Integer Cint
Long Clng
Single Cn=sng
String Cstr
Variant Cvar
Error CVErr

Note: A conversion function should always be placed at the right hand side of the calculation statement.

Visual basic programs can be broken into smaller logical components called procedures. Procedures
are useful for condensing repeated operations such as the frequently used calculations, text and controls
manipulation etc. The benefits of using procedures in programming are:
It is easier to debug a program with procedures, which breaks a program into discrete logical limits.
Procedures used in one program can act as building block for other programs with slight
A procedure can be sub, function or property procedure

Sub Procedure
A sub procedure can be placed in standard, class and form modules. Each time the procedure is
called, the statement between Sub and End Sub are executed.

[private | public ] [ static] Sub Procedure_Name [ (arg_list)]

End Sub
Argument list is separated by commas. Each argument acts like a variable in the procedure. There are
two type of sub procedures namely general procedures and event procedures.

Event Procedures
An event procedure is procedure block that contains the controls actual name, an underscore ( _ ),
and the event name
KIMS Dergee &PG College
Notes For Visual Basic 6.0 6 P.MallaReddy

Private sub Form1_Load( )

Statement block

End sub
This is event for form1. Execute when load form.

General Procedures
A general procedure is declare when several event procedure perform the same action. It is good
programming practice to write common statements in separate procedure and then call them in the event

Function Procedures
Function are like sub procedures, except they return a value to calling procedure. They are especially
useful for taking one or more pieces of data, called arguments and performing some tasks with them. Then
function return value that indicate result of the task.
The following function procedure calculates area of circle of given radius.

Function Area(a as double) as double

Area = 3.14 * a^2
End Function

Control Flow Statements

Control statements are used to control the flow of programs execution. Visual Basic supports control
structures such as If -- --- -- Then, If -- --- -- Then -- -- -- Else-- End If. Select----Case and Loop structures,
such as Do While-------Loop, Do-----Loop while and For..Next method.

If.Then.Else statement
The If then block is used for conditional execution of one or more statements. Syntax:
If Condition Then


End If
The statement is execute only if the given condition is true. The condition is usually a comparison, but it can
be any expression that evaluates a numeric value
If.Then . Else Statement
To execute one block of code if condition is false.
If Condition Then
End If

Select ..Case Statement

SelectCase structure is an alternative to If Then .Else If for selectively execute a single block
of statement from among multiple blocks.
KIMS Dergee &PG College
Notes For Visual Basic 6.0 7 P.MallaReddy

Select Case Index
Case 0
Case 1
Case n
End Select

Select . Case statement evaluates an expression once at the top of the block where as ifthen else
structure evaluates different expressions for each Else If statement.

Do While..Loop statements
The Do While . Loop is used to execute statements until a certain condition is met. Following do
while .. loop counts from 1 to 100
Do while count < 100
Count = count + 1

DoLoop While Statement

The do..loop While Statement first execute the statements and then test the condition after each
execution. The following program block is same to first one(like Do While loop)

Count = 200
Text1.text = str(count)
Count=count + 1
Loop While count < 300

The program execute the statements between do and loop while structure in any case. Then it determines
weather the count is less than 300. If so, the program again execute block until it gets false.

Do.Loop Until statement

The do.loop until structure execute the statements until the condition is satisfied. It is an infinite
loop if the test fails and to get released from this loop we can use CTRL + BREAK combination or End
From Run menu.

The following code entered in the Form Load() procedure illustrates the structure.

Private Sub Form_load()

X$ = INputBox$(Password ?)
Loop until X$ = Sunil
End Sub

The For.Next Loop statement

The forNext Loop is another way to make loops in visual basic
KIMS Dergee &PG College
Notes For Visual Basic 6.0 8 P.MallaReddy

For Var_name = Start_val to End_val [ Step Number]
Next [Var_name]

For I = 1 to 100 step 1

Text1.text = str(I)
Next I

Exit For and Exit Do Statement

A ForNext Loop Can be terminated by an Exit For Statement. Consider the following statement block
For I = 1 to 100
Text1.text = str(i)
If I= 50 then
Exit For
End if

In this example loop is for 1 to 100 but we stop or exit from loop by using exit for statement in it. Same we
can exit from do loop
Do while I < 100
Text1.text = str (I)
I = I+ 2
If I > 50 then
Exit Do
End If

With .. End With Statement

When properties are set for objects or methods are called, a lot of coding is included that acts on the
same object. It is easier to read the body by implementing with With End With statement.
For e.g suppose we want to set properties for Form then
With form1
.backcolor = qbcolor(2)
.enabled = True
.MaxButton = false
.Font = Times
End with
In the above coding, the object form get all its properties which we set in with block.

Code in visual basic is stored in the form of modules. The three kinds of modules are Form module,
Standard module, and class modules. A simple application may contain a single form and the code resides in
that Form module itself. As the application grows, additional Forms are added and there may be a common
code be to executed in several Forms. To avoid the duplication of code, a separate module containing a
procedure is created that implements the common code. This is a standard module.
Class module is a foundation of the object oriented programming in visual basic. New objects can be
created by writing code in class modules. Each module can contain variable declaration or procedures.

KIMS Dergee &PG College

Notes For Visual Basic 6.0 9 P.MallaReddy

Array in Visual Basic

A sequence of variables by the same name can be referred using array. The individual elements of an
array identified using an index. Arrays have upper and lower bounds and elements have to lie within those
bounds. Each index number in an array is allocated individual memory space. We can declare array of type
variant, user defined types and object variables.
There are two types of array
Fixed size array: The size of array always remains the same
Dynamic array: The size of can be changed

Fixed Size Array

Fixed array can be declared by giving a name with the upper limit in the parentheses. The long data type.
dim lengths(10) as Integer
In the above illustration, lengths is a name of the array and the number 10 include in the parentheses is the
upper limit of the array. This create array having 10 elements with index number from 0 to 9.
Dim length(1 to 10) as Integer having lower limit 1 to upper index number 10.
Dim marks(50,50) it create two dimensional array.
Dim marks(1 to 10,1 to 10) it create two dimensional array with lower and upper limits.

Dynamic array
There will be a situation when the user may not know the exact size of the array at design time. Under such
situation, a dynamic array can be initially declared and can add elements when needed instead of declaring
the size of the array at design time.

Dim newarray( )
The actual elements can be allocate using ReDim statement
ReDim newarray( n )

Each time on the executing the ReDim statement, the current data of array is lost and the default value is set.
But if we want to change the size of array without lost any previous elements then use keyword Preserve

ReDim Preserve newarray(20)

User-Define Data Type

Variable of different data types when combined as a single variable to hold several related information is
called user-define data type.
A type statement is used to create new type. User-define type can only be private in form while in standard
modules can be public or private.

Private type student
Name as string
Age as integer
Per as double
End type

Creating variables
Dim s1 as student

KIMS Dergee &PG College

Notes For Visual Basic 6.0 10 P.MallaReddy

Or creating array
Dim s(10) as student

Accessing members of user-define type

Variable name.member name
text1.text = accessing name of student s1

Visual Basic Built-in Functions

Many built-in functions are offered by Visual Basic that fall under various categories.
Date function
Format functions
String functions

Date Functions
Now Return current system date and time.
Year() Return year number from given date.
Month() Return month number from given date.
Day() Return day of given date.
WeekDay() Return week day number from given date.
Hour() Return hour number form given time.
Minute() Return minute from given time
Second() return second from given time.

Return a date to which specific interval has been added.
Syntax: DateAdd(interval,number,Date)
Where interval is M ,D or Y
Number to add in date
Date in which you want to add.
DateAdd(m,3,02/14/2002) it return 06/02/2002 (add 3 month in date)

Returns a Variant (Long) specifying the number of time intervals between two specified dates.


DateDiff(interval, date1, date2[, firstdayofweek[, firstweekofyear]])

The DateDiff function syntax has these named arguments:

Part Description

interval Required. String expression that is the interval of time you use to calculate
the difference between date1 and date2.

date1, date2 Required; Variant (Date). Two dates you want to use in the calculation.

KIMS Dergee &PG College

Notes For Visual Basic 6.0 11 P.MallaReddy

firstdayofweek Optional. A constant that specifies the first day of the week. If not specified,
Sunday is assumed.

firstweekofyear Optional. A constant that specifies the first week of the year. If not
specified, the first week is assumed to be the week in which January 1

Dim TheDate As Date ' Declare variables.

Dim Msg
TheDate = InputBox("Enter a date")
Msg = "Days from today: " & DateDiff("d", Now, TheDate)
MsgBox Msg

DatePart() Returns an integer containing the specified part of the given date

DateValue() Convert a string into date format.

String Functions
StrComp() Compare two strings
Lcase() Convert the given string into lower case.
Ucase() Convert the given string into Upper case.
Len() Return a length of given string
Format() Convert a given string into given format.
Lset(),Rset() Justify a string
Instr() Return a variable(long) specifying the position of the first occurrence of the string within
Letf() Return specified number of character from left side of given string
Rigth() Return specified number of character from Right side of given string
Trim() Return a given string by removing all its blank space from left and right side.
Mid() Return a specified number of character from mid of given string.
Ltrim() Trim all blanks of left hand side.
Rtrim() Trim all blanks of Right hand side.

Working with Forms

In visual basic, the form is the container for all the controls that makes up the user interface. A form may fill
entire screen or have other forms within it. It may be a custom dialog box. When a Visual basic application
is executing, each window it displays on the Desktop is Form.

Setting Form Properties

Border Style
None No border is shown.
Fixed single A single-pixel width border is shown
Sizable This is default setting.
Fixed Double A double-pixel width is shown around the form.
Fixed ToolWindow this type of border is use for toolbars.
Sizable Toolwindow Same as fixed toolwindow, but border are resizable.

The title for the window is store in the caption property.

KIMS Dergee &PG College

Notes For Visual Basic 6.0 12 P.MallaReddy

Control Box
This is determine weather the control box, available by clicking the upper left corner /icon of a window.
This property specify the icon for the window in the upper-left corner of the window

This property sets the value that indicate the type of mouse pointer displayed.

Set max or min button of window which are present on title bar.

By setting it false it is possible to prevent the user from moving window.

This property specifies if this window must be shown within a multiple document interface (MDI) window.

Set the starting position of window.

Displaying Forms

Show Method
The show method is used to display the form object. For e.g. to display the form frmcalculator, the
following code is written.

Using Load Statement

The load statement is used to load a form or control into memory but does not display it. To load the
form frmcalculator, the following code should be enter.

Hiding and Unloading Forms

Using the Hide Method

The hide method hides a form. For e.g., the following code hides the form object frmcalculator

Using the Unload Statement

The unload statement removes the form from the display and releases the memory. The following
code should be entered to unload frmcalculator from memory.
Unload frmcalculator

Setting Run time and design time properties

Many properties can be set at either design time or runtime. At design time, the controls are added to
a project, their properties set and relevant code is written.
To set properties at design time following steps are followed.
1. Select the control or object whose properties you want to set.
2. Activate the property window
3. Scroll to the property you want to set
4. Enter a new setting.

KIMS Dergee &PG College

Notes For Visual Basic 6.0 13 P.MallaReddy

At run time properties can change by programs code. This is done by

Object.propertyname = value

Private Sub Form_Load()

Form1.backcolor = QBcolor(3)
Form1.Caption = Sample Application
Form1.WindowStatus = VBNormal
Form1.Width = 5000
Form1.Height = 5000
End Sub

Creating and Using Controls

A control is an object that can be drawn on a Form object to enable or enhance user interaction with an
application. Controls

Classification of controls
Visual Basic Controls are broadly classified as standard controls, Active X controls and insert-able objects.
Standard controls such as CommandButton, Label and frame controls are contained inside .EXE file and are
always include in the ToolBox which cannot be removed. ActiveX controls exist as separate files with
either .VBX or .OCX extension. They include specialized controls, few from them given below
MSChart control
The Communication control
The Animation control
TreeView control
The Picture clip control
SysInfo control

Text Box Control

A TextBox control, some times called an edit field or edit control, display information entered time at design
time, entered by the user at run time or assign any value at run time.
Some Properties of a Text Box
Name This is a name used in program to identify the control
MaxLength Set maximum no of characters that can be entered in control.
MultiLine weather a control can accept multiple lines or not.
PasswordChar It replace the text of control with given character with.
Text to assign text to control at design time.

Command Button
A command Button control to begin, interrupt, or end a process. When chosen, a Command Button appears
pushed in and so is sometimes called push button.
Properties of a command button control
To display text on a command button control, set its caption property.
An event can be activated by clicking a command button
A buttons background color can be set by setting Backcolor property.
Text color of a command button can be set using forecolor property.
Font can be change using font property.
Enabled or disable button
Tooltip text can be set using Tooltip property.

KIMS Dergee &PG College

Notes For Visual Basic 6.0 14 P.MallaReddy

A button click event is handled whenever a command button is clicked. To add a click event handler,
double click on button at design time, which adds a subroutine like the one given below.

Private sub Command1_Click()

. . .
End Sub

Using option button control

Option button a set of choices from which a user can select only one button by
Clicking at run time.
Assigning the value property to True in code like Option1.Value = True
Using the shortcut keys specified in the caption of a label
To disable Option button at run time its Enabled property set to False.

Using Listbox and ComboBox Controls

ListBox and ComboBox controls present a set of choices that are displayed vertically in a single column. If
the number of items exceed the value that can be display, scroll bars will automatically appear on the
control. These scroll bars can be scrolled up and down or left to right through the list.

Adding items to a list

It is possible to populate the list at design or at run time.

Design Time: To add items to a list at design time, click list in the property box and then add the items.
Press CTRL + ENTER after adding each item.

Run Time: The AddItem method is used to add items to a list at run time. The AddItem method uses the
following syntax:
Object.AddItem item, Index
The item argument is string that represents the text to add to the list.
The index argument is an integer that indicates where in the list to add the new item.

Removing Items from a List

The RemoveItem method is used to remove an item from a list. The syntax for this is given below.

Selecting an Item from a list

To access the items in a listbox we use the ListIndex and List properties. The list index property sets
the index number of the currently selected item. The first item in the list having index number 0. ListIndex
return -1 if no item is selected. The list count return total number of items in listbox.

Sorting the List

To sort the list set sorted property to True.

Using ComboBox
A Combo Box combines the features of Textbox. This control enables the user to select either by
typing text into combo box or by selecting an item from list.
There are three types of Combo Box styles that are given below.
Dropdown Combo (style 0)
Simple Combo (style 1)
KIMS Dergee &PG College
Notes For Visual Basic 6.0 15 P.MallaReddy

Dropdown list (style 2)

Using ScrollBar Control

The Scrollbar is a commonly used control, which enables the user to select a value by positioning it
at the desired location. It represents a set of values. The min max property represents the minimum and
maximum value. The value property represents its current value.
Managing Menus
Creating and managing menu at Design Time
Visual Basic applications can be enhanced by adding menus to it. It offers a convenient and
consistent way to group commands and easy way for users to access them.

Title Bar
Menu Bar

Separator bar

The menu bar appears appear below the title bar and it may contain one or more menu titles. When a
menu title is clicked it displays a set of menu items under that title. Each menu item corresponds to a menu
control that is defined in a menu editor and performs a specific action.

Using the Menu Editor

A menu editor can be used to add new commands to the
existing bars. A menu editor can be added only after
opening a project. To display a menu editor command is
chosen from the Tools menu or menu editor button is
clicked in the tool bar.
Writing Code form menu Control
Each menu control has click event, which is execute
when the menu item is selected or clicked. The following
code is entered in the code window for green color option
of menu.
Private sub grn_Click()
Form1.backcolor= QBcolor(2)
Grn.Enabled = False
Blue.Enabled = True
Red.Enabled = True
End sub
When the green color is selected by clicking on it, form
backcolor will be change into green color and that green
option form menu is make disable and to others enable.
KIMS Dergee &PG College
Notes For Visual Basic 6.0 16 P.MallaReddy

Adding a Separator Bar and Shortcut key.

Separator bar is a line that separates the menu items, which is mainly useful for obtaining clarity. To
add it in menu, Right click on the form select menu editor
Place the pointer where you want to insert separator
In the caption TextBox - is typed and give any name

Using Access and Shortcut keys

Access keys allow the user to open a menu by pressing the Alt key with a letter key. To open the Edit menu
in all Windows applications, for e.g. you can press Alt-E. .
Access key is designed by the programmer and they are marked with an underline character. To assign
Access key to menu item, add & sign before letter. e.g. &File.

Shortcut Keys
Shortcut keys are similar to access key has a special meaning in menu design, but inside a opening menu,
they run a command when pressed. To assign a shortcut key to a menu command, dropdown the shortcut list
in the menu editor and select a keystroke.

Pop-Up Menus
A pop-up menu is a floating menu that is displayed over a form independent of the menu bar. Pop-up
menus are also called context menus. Because the items displayed on the pop-up menu depend on where the
pointer is located when the right mouse button is clicked.
Any menu can be displayed as a pop-up menu at run time provided it has one menu item.
The following code displays the colors menu when the user clicks right mouse button over the form at run

Private Sub Form_MouseDown (Button As Integer, Shift As Integer, X As Single, Y As Single)

If Button = 2 Then
PopupMenu cc
End If
End Sub

Making menu control invisible

It run time if user wants to enable and disable to menu items, it is possible by setting the Enabled
property to True or False. When a menu item is disabled, it is dimmed and cannot be selected. But it is still
visible and the menu items seen.
Mnu_green.Enable = False
But if you want to hide menu item from display set visible property false for it.
Mnu_green.Visbile = False

Using Check Marks

In some programs we may require check marks to be placed in the menu items. To place a check mark in a
menu item, the checked property is set to true. The following example code entered in the Form_load( )
procedure places a check mark in the menu item Red.

Mnured.checked = True

Menu Control Array:

A menu control array is a set of menu items on a menu that share the name and event procedure.
Each menu control array element is identified by a unique index value, indicated in the Index property box
on the menu editor. When the member of the menu control array recognizes an event, visual basic passes the

KIMS Dergee &PG College

Notes For Visual Basic 6.0 17 P.MallaReddy

index property value to the event procedure as additional argument. The event procedure must include the
code that can check the value of the index property.

Mouse Events
Visual basic applications respond to various mouse events, which are recognized by most of the
controls. The main events are MouseDown, MouseUp and MouseMove. MouseDown occurs when the user
presses any mouse button and MouseUp occurs when the user releases any mouse button. MouseMove
occurs whenever the mouse pointer is moved to a new point on the screen. These events use the arguments
button, Shift, X, Y and they contain information about the Mouses condition when the button is clicked.
The first argument is an integer number called button. The value is 1 if left button is clicked and 2 if
right button is clicked.
The second argument is an integer called shift. The value of this argument indicates weather the
mouse button was clicked simultaneously with the Shift key or Alt key.
The third and fourth arguments X and Y are the coordinates of the mouse location at the mouse
button was clicked

e. g.
This is program to draw a line on form with the help of mouse.
First method the starting points, when you press mouse button down to draw line
(MouseDown events)
Private Sub Form_MouseDown(Button As Integer, Shift As Integer, X As Single, Y As Single)
Form1.CurrentX = X
Form1.CurrentY = Y
End Sub

Second method for drawing a line on current points (Mouse/Move events)

Private Sub Form_MouseMove(Button As Integer, Shift As Integer, X As Single, Y As Single)
If Button = 1 Then
Line (Form1.CurrentX, Form1.CurrentY)-(X, Y)
End If
End Sub

Dragging and dropping

Dragging is a process of clicking the mouse button in a control and moving the mouse while holding
down the mouse button. The action of releasing the mouse button after the dragging is called dropping. The
following drag-and drop properties, events and method are supported in Visual Basic.
DragMode property enables automatic or manual dragging of a control. DragIcon property specifies the icon
that is display when the control is dragged.
DragDrop event is recognized when a control is dragged onto the object. DragOver event is recognized
when a control is dragged over the object.
Drag method starts or stops manual dragging.
All the controls except menus, timer, lines and shapes support the above mentioned properties and
method. Forms recognize the DragDrop and DragOver events but they do not support Drag method and the
properties DragMode and DragIcon.
To develop an application to explain drag and drop events we use a image, textbox and command button

KIMS Dergee &PG College

Notes For Visual Basic 6.0 18 P.MallaReddy

Private Sub Command1_DragOver(Source As Control, X As

Single, Y As Single, State As Integer)
Dim inf As String
info = "NOW DRAGGING "
info = info + img.Tag
info = info + " OVER THE Exit button"
info = info + " STATE" + Str(State)
Text1.Text = info
End Sub

Private Sub Form_DragDrop(Source As Control, X As Single, Y As

Text1.Text = ""
img.Move X, Y
End Sub

Private Sub Form_DragOver(Source As Control, X As Single, Y As Single, State As Integer)

Dim inf As String
info = "NOW DRAGGING "
info = info + img.Tag
info = info + " OVER THE FORM "
info = info + " STATE" + Str(State)
Text1.Text = info
End Sub

In this program when user drag image icon on form or command button related message will be
display on the screen, and when release the mouse the image will be place or move on the current location of
mouse pointer.

File Controls
Usually you use the Common Dialog File Open and File Save As to get file names and file paths
from the user, but sometimes that just wont do. For e.g. you have a program where you want to let user
select files but dont want to use dialog boxes, In that and similar cases, you can use the visual basic file
controls: The Drive List Box, Directory List Box and File list Box

Drive List Box:

Use this tool to draw a drive list box in a form, you get currently selected drive in a drive list by using its
Drive property, and when the user changes the drive in the control, a Change event is generated. But File
controls always work with each other.

KIMS Dergee &PG College

Notes For Visual Basic 6.0 19 P.MallaReddy

Drive List box

Directory List box

File List box

Text Box
RichText Box

Here in e.g when the user selects a new drive, we pass that new drive on ot a directory list box, dir1 using
that drive as the new root directory in Dir1:
Sub Drive1_Change()
Dir1.Path = Drive1.Drive
End Sub

Using The Directory List Box

The directory list box control displays directories as a hierarchical set of folders. The important
property of the list box is Path property, which holds the path of the current directory. When the user
changes the current path, a Change events is generated. For example, when the user makes a change in
directory list box, dir1, we can pass the new path to file list box, File1
Sub Dir1_Change()
File.Path = Dir1.Path
End Sub

Using The File List Box Control

The file list box control lets you display the files in a directory as a list of names.
The important properties of the File list box are Path and FileName properties. In our e.g. we load file
select from File List box to Picture Box and txt file in RichText Box. So when we click on File name
following event get execute.
Private Sub File1_Click()
On Error Resume Next
Dim fname As String
fname = File1.Path + "\" + File1.FileName
Text1.Text = fname
If LCase(File1.Pattern) = "*.bmp" Or LCase(File1.Pattern) = "*.gif" _
Or LCase(File1.Pattern) = "*.ico" Then
Picture1.Picture = LoadPicture(fname)
ElseIf LCase(File1.Pattern) = "*.txt" Then
rtb.FileName = fname
End If
End Sub

KIMS Dergee &PG College

Notes For Visual Basic 6.0 20 P.MallaReddy

Graphics for Application

Visual Basic provides a variety of ways to create and use
graphics in an application, which adds styles, interest and visual
structure to the interface of an application. Graphic objects such
as lines, circles and bitmaps can be displayed in visual basic in a
quicker and easier way.
The number of times a twip is used by all visual basic
movements, sizing and graphical drawing statements is limited to
one. A twip is a unit that specifies the dimensions and location of
the graphics objects. There are 1440 twips in one inch. Thses
measurements designate the size when printed.
The coordinate system is a two dimensional grid that defines the location on the form or any other
container which is represented as(X, Y). X represents the location of a point on the X-axis and Y represents
a point on the Y-axis
A color is represented by long integer and there are four ways of specifying it at run time. They are
specified using RGB function, QBColor function, and using one of the intrinsic constants listed in the Object
Browser and by entering a color value directly
RGB(255,0,0) return Red color
RGB(0,255,0) return Green color
RGB(0,0,255) return Red color
QBcolor function takes a single number that specifies a Quick Base color number from 0 to 15 and returns a
long integer that can be used in visual basic color property.
Form1.backcolor = QBColor(4)

Using Graphics Controls

Visual Basic provides three controls to create graphical applications such as image, Line and shape.
These controls are very useful at design time.
The main advantage of graphics controls is that we can create an application with less code.

Line Control
A line control is a straight-line segment that is drawn at design time. The position, length, color and
style of the line control can be positioned to customize the look of an application

Shape Control
A shape control is a Visual element that contains several predefined shapes. In order to view a
specified shape, the control is added to the form by double clicking it. The default shape will be rectangle.
The shape property is selected from the properties window, which drops down a list of shapes, from which
the user can select the desired one.
The FillColor, FillStyle properties of the Shape control can be changed so that desigred color and
style can be obtained.

Image Control
An image control is a rectangular portion into which picture files can be loaded. The picture files include
bitmap files, icon files and metafiles.

Adding Pictures:
Line control and shape control are used for drawing geometrics shapes such as lines, circles, squares and so
on. For drawing more complex figure we can use a picture file. A picture file can be loaded on a form, image
control or Picture Control.
A picture can be added by the following two ways at design time.
KIMS Dergee &PG College
Notes For Visual Basic 6.0 21 P.MallaReddy

In the properties window of the Form, the Picture property is selected. Visual Basic displays a dialog
box from which a picture file can be selected. Similarly a picture can be loaded in a PictureBox and
Image control.
A picture can be paste on form or into PictureBox or Image control

A picture can be added by the following ways at run time.

LoadPicture function is used to specify the filename and assign the picture to the Picture property.
Picture1.Picture = LoaPicture(C:\Image\sst.jpg)
Any picture loaded to a form, PictureBox or Image control can be copied to another Form,
PictureBox or Image control.
Set picture1.picture = Image1.Picture
A picture can be copied from ClipBoard object

Removing Picture
A picture can be removed at run time using LoadPicture function without arguments.
Set image1.picture = LoadPicture( )

Moving and Sizing Pictures

If a form, PictureBox or an Image control is moved, the picture associated with it also moves
automatically. The autosize property of a picture box can be set to True in order to automatically expand and
accommodate a new picture.

Using Graphics Methods

Every graphics method draws output on a Form, PictueBox or to the printer object. The following
statement draw a point on the form

The PSet method draw a point at x, y co-ordinates that is specified by its arguments.

Clear all the graphics

PixelColor = point(30,40)
Point method return the color of a particular pixel.

Line(x1, y1) (x2, y2), Color

Line method draw a line from x1,y1 to x2,y2 of given color, x1 ,y1 is a starting point coordinates and x2, y2
is ending points.

Visual Basic provides a much simpler way to draw a box.

Line(600,600) (1000,1000), Qbcolor(4),B
B option is used with Line Method to draw a box.
A Circle method is used to draw a variety of circular and elliptical shapes. To draw a circle Visual Basic
required the location of the circles center and length of its redius.
Circle(1400, 1200), 500

Multiple Document Interface (MDI)

MDI stand for Multiple Document Interface. A Multiple
Document Interface is used for opening many Windows at
the same time. All the document windows are contained in
a parent window, which provides a workspace in the
KIMS Dergee &PG College
Notes For Visual Basic 6.0 22 P.MallaReddy

application. Visual Basic applications can have only one MDI form, which contains all the child forms. A
child form is an ordinary Form that has its Child property set True. Child form are display within the internal
area of MDI form at run time.

Add new MDI form to Project:

To add new MDI form, select it from project menu or right click on project name in Explorer
window and select Add, MDI form.
To all other forms of your project set MDIChild property True to associate these forms with parent form.
In this example we create a MDI form having two child form Name Form1 and Form2 after clicking on
Load form Option of Form menu, show form1 and on form2 show form2. window use to show list of open
1. Open New project
2. Add MDI form from project menu
3. Add Form from project menu
4. To form1 and Form2 set MDIChild property to True
5. Create the menu
Load Form1
Load Form2

Enter following code in MDI form

Private Sub loadfrm1_Click ()

End Sub

Private Sub loadfrm2_Click ()

End Sub

Debugging in Visual Basic

Debugging is a process by which error are identified and resolved in source code. In visual basic error can
occur anywhere during entire development cycle such as
Design time
Compile time
Run Time

Design Time Bugs

Errors that occurs in the IDE and before the program is compiled are called design-time bugs. These
are the most common ones. These bugs are caused by misuse of some component.
The following e.g. shows a function that works as long as a textbox control is passed to it. If any other type
of control (say text box, here, the extra space causes the problem) is passed, it fails to execute and an error is
reported this is a design time error, which is display the moment the user navigates to the next statement.

Sub settext( ctrl as text box, txt as String)

Ctrl.text = Lcase(Trim$(txt) + : + Date$
End sub

KIMS Dergee &PG College

Notes For Visual Basic 6.0 23 P.MallaReddy

On entering the first statement of the above coding in the general declaration section, the following error is

Compile-time bugs
Compile-time bugs are those that occur when we attempt to create the program executable file (EXE)
or run the project. Visual Basic can locate compile-time bugs if the Visual Basic application is set up
correctly. Visual Basic set the several points to users, which can be change as needed.
Compile-time bugs are detected by visual basic automatically when the program is compiled using F5. If the
Start With Full Compile option is used, the Compile On Demand can be turned on, and the developer will
not find any bugs until the line of code with the bugs is actually executed.
Compile errors occur as a result of incorrectly constructed code such as Next statement without a
corresponding For statement or programming mistakes that violate the rules of Basic, such as misplace
word, missing separator, or type mismatch. Compile errors included syntax errors. These include
mismatched parentheses or an incorrect number of arguments passed to an intrinsic function.

Runtime bugs
A Visual Basic runtime error is the exception generated by Visual Basic when it ascertains that the
code is about to perform something illegal. An illegal function could be something as simple as trying to
determine the size of a file that dose not exist or attempting to multiply two numbers, the result of which
exceeds the storage space that could be contained by the data type.
However, using an error handler could prevent this error dialog box from being shown and save the
program from crashing. By practices we can
also use our knowledge that a particular
error identified by its error number will be
generated to help guide our logic. This sort of
inline error handling is very powerful and
can be handled using an error handler that
checks for the condition of, say Error 57,
and then does something to avoid the
situation. This error can be finally rectified
by changing the code suitably.

Consider the following example where we declare two variable x and y. try dividing x (assign a value 9) by
y (assign 0), assigning the quotient to another variable z.

Private sub Form1_load()

Dim x as Integer
Dim y as Integer
Dim z as Integer
End Sub

Visual Basic Debugging Tools

KIMS Dergee &PG College

Notes For Visual Basic 6.0 24 P.MallaReddy

The best way to keep bugs out is to prevent then in the first place. Visual Basic gives a programming several
tools, include IDE options and compile directives, to help achieve this goal.

IDE Options
Visual Basic offer several IDE option that can help the user write better code.
Auto Syntax Check
Required Variable Declaration
Auto List Members
Auto Quick Info
Auto data Tips
Option Explicit
Option Compare Text

Additional settings and debugging aids can be viewed in a dialog box shown in the fig. using the following
1. Select Option from Tools Menu
2. Choose the Editor tab in the Option dialog box

Require Variable declaration:

This option explicitly inserts the Option Explicit statement in each new form, module, or class
created. A dim, private, public, ReDim or static statement must be used to declare a variable before the value
is assigned to it. If an undeclared variable is used, an error occurs at compile time.
Option Explicit
Private sub Form1_Load()
Sum = 0
End sub

Auto Syntax Check:

The Auto Syntax Check option forces Visual Basic to check
the line of code when the user moves the cursor off the line.

Private sub Form1_load()
Dim a integer
End sub
In this program Dim a here required As so compiler give a error message when we try to move cursor to next line.

Auto Quick Info:

The Auto Quick Info in Visual Basic display ant required or Optional parameters for methods. VB
display all possible parameters while highlighting the one we are currently entering. Auto Quick Info makes
it easier to use methods and properties because we no longer have to remember or look up all the arguments
its properties and methods.

Debugging Tools are designed to help the user with logic and run-time errors. Visual Basic provides several
buttons in the ToolBar that are helpful for debugging. They are

Breakpoint: Defines a line in the code window where Visual Basic suspends execution of application

KIMS Dergee &PG College

Notes For Visual Basic 6.0 25 P.MallaReddy

Instant Watch: Lists the current value of an expression while the application is in the break-mode.
Calls: Presents a dialog box that shows all procedures that have been called but not yet run completely.

Visual Basic provides several built-in methods for controlling the execution of the program in real
time. It is possible to execute the program line by line or procedure by procedure or a combination of the
two. These basic debugging actions are called Stepping. Because it enables the developer to walk through
the program, examining the variables and logic, stepping is the most powerful debugging tool offered by
Visual Basic. The various debugging commands are discussed below.

Step Into: Execute the next executable line of the code in the application and steps into procedures. This
enables to check every line of code as it is being executed. This option can be accessed from debug menu or
by pressing F8.

Step Over: Execute the next executable line of the code in the application without stepping into procedure.
The procedure the user steps over does execute, but Visual Basic does not walk through the stepped-over
procedure line-by-line. Shortcut key is Shift+F8.

Step Out: Moves program execution back to the calling procedure. This is the functional equivalent of Exit
sub or Exit Function. It is simple exits the current procedure without executing any more code in that

Set Next: Enables the user to move program execution to any executable line of code in the current
While debugging an application, we should clearly understand which of the three modes such as design
time, run time or break mode we are in at a given time. Break mode of an application is viewed by clicking
CTRL+BREAK at run time.

Using the Debugging Window

Debug window is one of Visual Basics window that allows to run individual commands
immediately, by typing in the command and pressing the Enter key. It automatically opens at run time.
1. In break mode, the debug window can be used to execute individual line of code, View or change
values of variables and properties, and view watch expressions.
2. At run time, it can be used to display data or messages as the programs as the program runs.
3. At design time, the developer can view the previous output to the Debug window, but cannot execute
The debug window has two part- Watch window and immediate window. The split bar separates the Debug
window into two panes. The upper pane display the Watch Window. The lower pane display the Immediate

Watch Window
Watch pane displays the current watch expressions, which are expressions whose values are decided
by the user as code is executed. The Watch pane appears automatically if the watch expressions are defined
in the project. At times we want to monitor the value of a variable for a certain state- for example to
determine weather a flag is set to True or False.
Steps to add watch expression
1. Add watch command is chosen from the Debug menu.
2. The Expression is entered in the Expression box.
3. If necessary, the scope of the variables is set and an option button is selected.
4. The OK button is clicked.

KIMS Dergee &PG College

Notes For Visual Basic 6.0 26 P.MallaReddy

Immediate Window
The immediate pane appears by default the first time the debug window is opened. From break
mode, the code is executed immediately by entering it in this pane. This window is the right place for the
users to modify data or test functions during development. We can enter any valid expression in this window
and VB will execute it. If a reference is made to an object outside the scope of the current code execution,
Visual Basic will generate an error.

Testing data and procedure in Immediate Pane

While debugging an application, Sometimes it may necessary to execute individual procedures,
evaluate expressions or assign new values to the variables or properties. The Immediate Pane can be used to
accomplish new values to the variables or properties. The Immediate Pane can be used to accomplish such
tasks. Expressions can be evaluated by printing in Immediate Pane. Some advantages of these facility.
The data or message can be viewed at run time.
Feedback is displayed in separate area, so that it does not interfere with the output that the user is
Since the coding is saved as part of the form, these statements needs not be redefined the next time we
work on the application.
Private sub Form_load( )
Dim a as integer
Dim b, c as integer
A = 10
B= 6
Msgbox Value of c is & C
Debug.print Value of c is : & c
End sub

On executing the above code the value of c is displayed in the Immediate window using the Debug.print

Using a Breakpoint to selectively Halt Execution

At run time, a breakpoint tells VB to halt before executing a specific line of code. A breakpoint can be set or
removed at design time or at break mode. To set or remove a breakpoint,
The insertion point is moved to the line of code where the breakpoint is to be set or removed.
The Toggle Breakpoint is chosen from the Debug Menu or Toggle button is chosen in the Toolbar or press
shortcut key F9.
Writing Error Handlers
Visual Basic has specific built-in ways to handle runtime errors, called trappable errors. When such
an error occurs, you can direct the execution of your program to an error handler, which is a section of code
written specifically to deal with errors.

On Error GoTo Label.

The visual basic On error Goto statement is the foundation of handling trappable errors. When you
execute an On Error GoTo Label Statement in your code. Execution is transferred to the code starting at
label if a trappable error has occurred. The code following that label is your error handler.
Private Sub Form_Load()
Dim a, b, c As Integer
On Error GoTo diverror
a = 10
KIMS Dergee &PG College
Notes For Visual Basic 6.0 27 P.MallaReddy

MsgBox "Value of C =: " & c
MsgBox "Divided by Zero Error", vbCritical, "Error"
End Sub
In this example value of b is zero, if dont trap error then our program is terminate with an error, but in this
we trap error and give appropriate Message to user.

Err :
It is a object Contains information about run-time errors. When a run-time error occurs, the
properties of the Err object are filled with information that uniquely identifies the error and information that
can be used to handle it. To generate a run-time error in your code, use the Raise method.
Main Properties of Err object
Err.Number : Return error number
Err.Description : Return error description
e.g. you may show this error message in program.

MsgBox "Des: " & Err.Description & "NUMBER : " & Err.Number

On Error GoTo line#

Besides using a label to start an error handler, you can refer to an error handler by line number in visual
basic, using on error goto line# statement.

1 Private Sub Form_Load()

2 Dim a, b, c As Integer
3 On Error GoTo 8
4 a = 10
5 b=0
6 c=a/b
7 MsgBox "Value of C =: " & c
8 MsgBox "Divided by Zero Error", vbCritical, "Error"
9 End Sub

Using On Error Resume Next

The On Error Resume Next statement provides an easy way to disregard errors, if you want to do so.
Once you execute this statement, execution continues with the next line of code if the current line generates
an error, and the error is disregarded.

On Error GoTo 0
To turn off error trapping, you can use the On Error GoTo 0 statement.

Err Function
Returns a Variant of subtype Error containing an error number specified by the user.
CVErr(error number)
The required errornumber argument is any valid error number.

KIMS Dergee &PG College

Notes For Visual Basic 6.0 28 P.MallaReddy

Use the CVErr function to create user-defined errors in user-created procedures. For example, if you
create a function that accepts several arguments and normally returns a string, you can have your function
evaluate the input arguments to ensure they are within acceptable range. If they are not, it is likely your
function will not return what you expect. In this event, CVErr allows you to return an error number that
tells you what action to take.
Note that implicit conversion of an Error is not allowed. For example, you can't directly assign the
return value of CVErr to a variable that is not a Variant. However, you can perform an explicit conversion
(using CInt, CDbl, and so on) of the value returned by CVErr and assign that to a variable of the
appropriate data type.
Sub Test()
Debug.Print CalculateDouble("345.45robert")
End Sub
' Define CalculateDouble Function procedure.
Function CalculateDouble(Number)
If IsNumeric(Number) Then
CalculateDouble = Number * 2 ' Return result.
CalculateDouble = CVErr(2001) ' Return a user-defined error
End If ' number.
End Function

KIMS Dergee &PG College

Notes For Visual Basic 6.0 29 P.MallaReddy

Database: 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 support DAO, which connected to the Microsoft Jet database engine (the
database engine in MS Access). Then, recognizing that there are other database types available, Microsoft
created the Open database connectivity (ODBC) standard and supported ODBC with Remote Data Objects
in Visual Basic. Finally For Web to access data over network Microsoft create Active Data Object (ADO)
that 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, its based on COM programming techniques.
There are two ways to work with DAO, RDO and ADO object sets in VB. The first way is working
with the special controls that support them. The Data Control, Remote Data Control and ADO data control.
You use them to connect to and to move through database but they dont display actual data, you bind them
to other Visual Basic controls, and those bound controls handle the display. The second way is working with
the three database object sets directly in code, without controls like the data control or DAO data control,
and thats what well do in the next chapter.

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.
Each individual data entry in a table, such as a students name, goes into a field in the table. A collection of
fields together, such as the Name and Grade fields in our table, make up a record. Each record gets its own
row in a table, and each column in that row represents a different field.
A collection of records- that is, row of records where each column is a field-become a table. Whats then is a
Database? A database is just a collection of one or more tables.

Evolution of computing Architectures

Lets us discuss about the evolution of client-server architecture for various computing models. In
this chapter we discuss about three architectures.

Centralized System Architecture

Companies that needed real computing power turned to the mainframe computer, which is
centralized system architecture. The salient most feature of a centralized system is that the only movement
of marshalling are keystrokes between the client and the host machine. Marshalling is the process of packing
interface elements and sending them across process boundaries. Thus in a centralized system, keystrokes are
marshalling from the terminal (client) to the host. The centralized system architecture is illustrated in fig.

KIMS Dergee &PG College

Notes For Visual Basic 6.0 30 P.MallaReddy

Application Data

Network Server



Terminal1 Terminal1 Terminal1 Terminal1

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
thereby offering no way to truly partition the application logic beyond the physical limitations of
In 1980 personal computers made an entry into the business world along with which, came the resources like
printers, modems and hard-disk storage. The introduction of the local area network(LAN) and the use of file
server architectures soon following the introduction of personal computer.
File Server Architecture
The file server system brought a complete change in implementation of the computer architecture
from the mainframe. In this system, 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
complete File Server architecture is illustrated in fig.
The merit of the file server system is 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 is that all application logic is executed on the client machine.
The job of the server is to provide files only to store the data. Though the applications file might be located
on the server, the application runs in the client machines memory space using the clients processor. This
results in the client machines need memory amount of power to run the application.
Taking into account the de-merits of the centralized and file server system architecture, the client
server architecture made its advent.

KIMS Dergee &PG College

Notes For Visual Basic 6.0 31 P.MallaReddy

Network Server

Disk I/O

Disk Blocks

Terminal1 Terminal2 Terminal3 Terminal4

App. Logic1 App. Logic2 App. Logic3 App. Logic4

Client Server Model

Client 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. In this application, two separate applications operating
independently could work together to complete a task. A well brought out implementation of this concept is
the SQL based Database Management System. The client server architecture is well illustrated in fig.
here, unlike the file server system, the request that goes to server in not merely a request for file in the form
of disk input/output requested as series of disk blocks. Instead, instructions are communicated to an
application running on the server, and the server executes those requests and sends a response to the client.

Network Server
Disk I/O


Terminal1 Terminal2 Terminal3 Terminal4

App. Logic1 App. Logic2 App. Logic3 App. Logic4

The request may take the form of the SQL query submitted to a SQL database engine. The database
engine in turn processes the request and a result set is send to the client. Thus the two independent process
work together to accomplish a task and exemplifies the client-server relationship.
The most popular client/server applications revolve round the use of DBMS such as Oracle and MS
SQL server. These applications are referred to as backend and offer support for storage manipulation and
retrieval of business persistent data. They use structure query language (SQL). As a standard method for
submitting client requests.
KIMS Dergee &PG College
Notes For Visual Basic 6.0 32 P.MallaReddy

Thus a major advantage of Client/Server architecture is reducing traffic and, in most cases, an
incredibly quicker execution time.

Two Tire and Three Tire Client Server Model

The various system architecture that has been in use have been discussed so far. Now let us move on
to discuss the creation of in information system that can change with business needs, needs that mandate
tighter budget and higher quality in addition to simply processing transactions generating report. To respond
to the challenges being presented by the business environment a new three-tier or n-tier client/server
approach has been introduced.

Two Tier Client/Server model

In two-tier model, a desktop machine operates as a client and network server function as a back-end
database engine. The logic in two in two-tier model is split between the two physical location namely the
server and client. The client in a two-tier model is necessarily a 4GL like Visual Basic or Power Builder. The
salient point for a two-tier application is that the business logic must physically reside either on the client or
be implemented on the back-end within the DBMS in the form of triggers and stored procedures. Both
triggers and procedures are stored as precompiled collections of SQL statements and control-of-flow
In VB, using any of the data controls that provide a graphical link to the back-end data source create a two
tier client/server relationship.

Merits of two-tier
The merits of this two-tier model are data access is simplified, allowing very rapid development of
applications. The GUI is bound directly to the data source and all the details of data manipulation are
handled automatically. But there is a disadvantage in this, i.e. though the data access is simplified, it is less
flexible due to which the user will not have complete control of interactions with the data source.

Limitations of Two-Tier model

Not Scalable: Inability of two-tier approach to grow beyond the physical boundaries of a client and server

Unmanageable: Business rules cannot be encapsulated and deployed centrally because of which sharing
common process and reusing work become difficult.

Poor Performance: The graphical interface binding to the data consumes major resources on the client
machine, which results in poor performance and dissatisfied clients.

Three-Tier Client/Server Model:

An improved model for client/server development resulted as an outcome of limited effectiveness of
two-tiered client/server solutions. The three-tier client/server model is based on the ability to build
partitioned applications. Partitioning an application breaks our code into logical components. The Service
Model employed to design this architecture suggests that these components can be logically grouped into
three tier. User services, Business services and Data services. The service and its location are given below.

Service Location
User Services Client
Business logic Server
Data services Server

KIMS Dergee &PG College

Notes For Visual Basic 6.0 33 P.MallaReddy

On developing an application using this model and technique, each component can then be placed on a
suitable machine that will provide the best performance depending on our situation and the current business
need. The three-tier logic can be extended to any number of tier/services called as Multi-Tier or n-Tier

Values of three-tier client/server development

Reuse: The time invested in designing and implementing components is not wasted as they can be shared
among applications.

Performance: As components can be placed on machines other than the client workstation, load processing
can be shifted from a client machine that may be underpowered to a server with extra horsepower. This
offers us the best possible methods for each aspect of our applications execution, resulting in better
Manageability Encapsulation of applications services into components allows us to break down large,
complex applications into more manageable pieces.
Maintenance: centralizing components for reuse has an added benefit. They become easier to redeploy on
making any amendments to keep pace with business needs.

Data Access Options

Visual Basic provides a variety of options to access remote Client/Server databases. They are:
Data Access Object (DAO): It communicates with the data source through the JET database engine.

Data Control: It binds data-aware control to Microsoft Access and other ODBC data sources.

ODBCDirect: It allows accessing of ODBC data source through the RDO with ADO objects, bypassing JET
database engine.

Remote Data Objects (RDO): It provides a framework for using code to create and manipulate components
of a remote ODBC database system.

Remote Data Control (RDC): It binds the controls to an ODBC remote database.

Open Database Connectivity (ODBC): this is an API call interface to the open Database Connectivity
libraries and drivers to provide data access to Microsoft SQL server and other database that provide an
ODBC driver.

Visual Basic Library for SQL Server (VBSQL): it is an implementation of the DB library API specifically
designed to provide access to SQL Server through a visual basic application

Active Data Object (ADO): This is a programming model that eliminates the need to choose from among
DAO and RDO and all other data access methods. It is designed to provide a common bridge between
different database, files systems and e-mail servers.

Data Access Objects

A DAO is a collection of object classes that model the structure of a relational database system. They
provide properties and methods that allow to accomplish all the operations to manage such a system,
including features for creating databases, defining tables, navigating and querying a database. Visual Basic

KIMS Dergee &PG College

Notes For Visual Basic 6.0 34 P.MallaReddy

supports Data Access Object such as DBEngine, Workspace, Database, TableDef, Field, Index and
Recordset Objects.

DBEngine: The DBEngine is the top level database object and corresponding to the Jet database
engine. This object is used to set database engine system parameters and default workspace.
Workspace: The Workspace object is used to support simultaneous transactions and it acts as a
container for open database. A default Workspace object Workspace (0) is created when the DAO are
referenced in the language at run time. The default workspace is always available and never be
closed or removed from the collection.
Database: The Database object corresponds to a Jet native or external database or a direct ODBC
connection. This is used to define the databases table, relations and stored queries and to open
Recordset object.
TableDef: The TableDef object corresponds to stored table definition. Each TableDef in a collection
represents the Definition of a current table in a database or an attached table in the external database.
QueryDef: The QueryDef is a stored query definition, which is a precompiled SOL statement.
RecordSet: The Recordset object corresponds to a cursored view into a database table or the results
of query. A cursored view is that stores rows of data in buffer and points to one row of data at a time
called current record. The cursor may be positioned to any row of data using Move, Seek or find
Field: The field object corresponds to a column of data type and set of properties. TableDef,
Recordset objects have collection of field objects. The collection of Field object associated with
Recordset cursor describes a single row of data.
Index: The index object is a stored index allows to quickly reorder the records in a table.
Parameter: A parameter object represents a parameter associated with a QueryDef object created
from a parameter query. A parameters collection contains all the parameter objects of a QueryDef
User: The User object is used to define and enforce database security. The DBEngine object supports
a set of user collection. The Users collection contains all stored User objects supports a collection of
system groups. Each user in the group inherits the permissions to access the objects that the group
can access.
Relation: A Relation object represents a relationship between fields in the tables or queries. A
Relations collection contains stored Relation objects of Database object. The DBEngine enforces
certain update and delete conditions on the data associated with the fields of the Relation object, to
maintain referential integrity.
Property: A property object represents a built-in characteristic or user-define characteristic of a data
access object. Properties collection contain all the property object for a specific instance of an object.

Accessing and Navigating Databases

In order to work with data objects, a reference has to be set to the appropriate DAO library. There are two
DAO libraries supported by VB they are:
Microsoft DAO 3.51 Object library
Microsoft DAO 2.5/3.51 Compatibility Layer.
To set reference to DAO type library:
Select References from the Project Menu
Select the DAO 3.51 (or 3.6) Object Library
Click on OK button

Opening Database
To open an existing database, the OpenDatabase method of workspace object is used
KIMS Dergee &PG College
Notes For Visual Basic 6.0 35 P.MallaReddy

The following code opens the employee_detail database
Dim db as Database
Set db = opendatabase(C:\Emp_detail.mdb)
In the above code, db is a variable that represents the Database object. By default, a database that is opened
can be shared and modified by any user. To specify that the database is to be opened fro exclusive use, the
following statement can be used:

Set db = opendatabase(Emp_detail.mdb,True)

In the above code True value indicates that no users will be able to open the database. The default value is
To open emp_detail database in the readonly mode, the following statement is used:

Set db = Opendatabase(Emp_dateil,False,True)

In the above statement, the True value specified as the third argument will provide only a read access on the

A recordset is an object that contains a set of records from the database. There are mainly five types of
Recordset object.
1. Table-Type Recordset: The table type recordset object is a set of records that represents a single
table can be used to add, change or delete records. They are fastest type of Recordset.
2. Dynaset-Type Recordset: The dynaset-type recordset object is a set of records that represent a table,
or attachment tables, or the results of queries containing fields from one or more tables. A dynaset
enables us to update data from more than one table.
3. Snapshot-Type Recordset: the snapshot type recordset can refer any table, attached table or query.
A snapshot cannot be updated and does not reflect changes to data made by the users.
4. Dynamic type Recordset: This recordset type represent a query result set from one or more base
tables in which we can add, change or delete records from a row returning query. Further, records
that other users add, delete, or edit in the base tables also appear in our recordset. This type is only
available in ODBCDirect workspace, and corresponds to an ODBC dynamic cursor.
5. Forward Only Type recordset: This recordset type is identical to a snapshot except that we can
only scroll forward through its records. This improves performance in situations where only need to
make a single pass through a result set. In an ODBCDirect workspace, this type corresponds to an
ODBC forward-only cursor.

Creating a Recordset:
The OpenRecordset method is used to open a Recordset and create a recordset variable.
To create a read-only recordset for the table emp, the following code is used.

Dim rs as Recordset
rs = db.OpenRecordset(emp,dbopentable,dbReadOnly)

In the above statement, db is the variable that represents the database object. Here dbOpenTable specifies the
type of the Recordset to be created.

Navigating a Recordset:
After creating a Recordset object, the various methods can be used to navigate through the recordset.

KIMS Dergee &PG College

Notes For Visual Basic 6.0 36 P.MallaReddy

The MoveFirst :mehthod moves to the first row in the Recordset

The MoveLast :mehthod moves to the Last row in the Recordset
The MoveNext :mehthod moves to the Next row in the Recordset
The MovePrevious :mehthod moves to the Previous row in the Recordset

Using BOF and EOF to navigate through Recordset

The Recordset object provides two properties for the user to know when he has moved to the
beginning or end of the recordset
The EOF (End of File) property is True when the user moves beyond the last record in the recordset.
The BOF (Beginning of file) property is true when the user moved to a position before the first record in the

Modifying and Deleting Records

To manipulate a recordset, the following methods are used.

Edit Method:
The user can edit the current record using the edit method. The Update method is used to save the
necessary changes made to the records.
AddNew Method: AddNew method is used to add a blank record in the recordset.
Delete Method: This method can be used to delete record in the dynaset-type recordset. The jet engine
deletes the current record without any warning when the Delete method used.

Finding Records
The Find methods can be used to locate a record in dynaset-type or snapshot-type Recordset. VB supports
four Find methods.
FindFirst: method finds the first record satisfying the specified criteria.
FindLast: method finds the Last record satisfying the specified criteria.
FindNext: method finds the next record satisfying the specified criteria, searching backward from the
current record.
FindPrevious: method finds the previous record satisfying the specified criteria, searching backward from
the current record.

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
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 as shown in fig.
2. Select Add button to add new ODBC drivers that
are currently installed in system are displayed as
shown in fig.2
KIMS Dergee &PG College
Notes For Visual Basic 6.0 37 P.MallaReddy

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.
The OpenDatabase method creates a connection between the application and the ODBC database and
assigns it to a database type object.
Dim db as Database

Set db = opendatabase (<Data Source Name>, <dbdriverpromptinformation>, <readonly> ODBC; UID=<User ID>;

The Active Data Objects

Visual Basic supports several data access tools, with the Active Data Object (ADO) being the most recent
addition. Whereas the first Visual Basic data access tools (the Data Access Object, discussed before this)
allowed programmers to access Access database only, ADO can access all major databases and Microsofts
foundation for a universal technology for accessing all types of data in all environments.
With ADO, your VB application sees three objects:
1. A connection object, which establishes a connection to the database, be it a local file or remote SQL
2. A command object, which executes commands against the database.
3. A Recordset Object, which holds the records retrieved from the database or the records to be updated
on the database.

As we saw AtiveX Data Objects (ADO) access data from OLE DB providers. The Connection object is used
to specify a particular provider and any parameters. To connect to a data source, you use a Connection
object. Using that connection, you can create a new record set, and using the recordset objects methods and
properties, you can work with your data.
An ADO transaction marks the beginning and end of series of data operations that are executed across a
connection. You can cancel or allow changes.

ADO Example
To explain ADO data handling in code, well build an ADO
project. This application lets you open the db1.mdb file of
access using ADO objects to edit records, add, delete records.
You can move through the database using arrow buttons you
see in fig. To edit a record, just type the new value into the
text box and click on update button. To add new record, use
add button and insert new values, after it click on update

ADO: Opening a Connection

KIMS Dergee &PG College
Notes For Visual Basic 6.0 38 P.MallaReddy

The first step to start the ADO project is give reference to Microsoft ActiveX Data Object library item, and
click on OK to add object library to your project
Then create object of Connection and Recordset

Dim Cn As New ADODB.Connection

Dim Rs As New ADODB.Recordset

Now we are free to create a new ADO connection to object with the Connection objects Open method:

Connction.Open ConnectionString[, UserID [, Password [, OpenOption]]]

Here are the arguments for this method.

Connection String-String containing connection information.
UserID- String containing a username to use when establishing the connection
Password String containing a password to use when establishing the connection.
OpenOptions - If set adConnectAsync, the connection will be opened asynchronously.

Private sub form_load()
dim cn as new ADODB.Connection PROVIDER = Microsoft.Jet.OLEDB.3.51;Data source = C:\db1.mdb;
End sub

Creating a Recordset from Connection

Now thats you have created an ADO connection, you open a record set from that connection using the
Recordset objects Open method
Recordset.Open [ Source, [ Active_connection , [Type, [ LockType, [ options]]]]

Here the arguments for this method

Source- A valid command object variable name, an SQL statement, a table name, a stored procedure call, or
the file name of Recordset.
ActiveConnection- A valid Connection object variable name or a string containing ConnectionString
Type- Sets the recordset type (see the following list)
dbopenKeyset: Opens a dynaset-type recordset object, which is like an ODBC keyset cursor.
dbOpenDynamic: Opens a dynamic-type Recordset object, which lets the application see changes
made by other
dbOpenStatic: Open a static type recordset object.
dbOpenForwardOnly: Opens a forward-only-type Recordset object, where you can only use
MoveNext to move.

LockType: A value what determines what type of locking the provider should use when opening the record

Here are the possible values for the LockType:

adLockReadOnly: the default; readonly.
adLockPessimistic: Pessimistic locking, record by record.
adLockOptimistic: Optimistic locking, record by record.
KIMS Dergee &PG College
Notes For Visual Basic 6.0 39 P.MallaReddy

adLockBatchOptimistic: Optimistic batch updates.


Private sub form_load()

dim cn as new ADODB.Connection
dim rs as new ADODB.Recordset PROVIDER = Microsoft.Jet.OLEDB.3.51;Data source = C:\db1.mdb;
rs.Open Select * from lib, cn , adOpenStatic,adLockOptimistic
End sub

ADO: Binding Controls to Record sets

To bind a control to ADO Recordset objects, you just set that controls DataSource property to that object,
and then set whatever other data properties that control needs to have set


Private sub Form_load()

Dim cn as new ADODB.Connection
Dim rs as new ADODB.Recordset PROVIDER = Microsoft.Jet.OLEDB.3.51; Data source = C:\db1.mdb;
rs.Open Select * from lib, cn , adOpenStatic,adLockOptimistic
set text1.datasource = adorecordset
text1.Datafield = Title
set text2.datasource = adorecordset
text2.Datafield = cost
End sub

ADO: Adding a Record to a Recordset

To add a new record to an ADO recordset, you use the AddNew method, after youve updated the fields of
the current record, you save that record to the database with the update method. heres how you use

Recordset.AddNew [ Fields [, Values]]

Fields: a single name or an array of names or ordinal positions of the fields in the new record.
Values: A single value or an array of values for the fields in the new record. If Fields is an array, values must
also be an array with the same number of members.

ADO: Updating A Records in a Record Set.

After changing the data in a records in fields or adding a new record, you update the data source to record
the changes, using the Update method:

Recordset.Update fields,values

Here are the arguments for this method:

Fields - A single name or an array of names or ordinal positions of the fields in the new record.
KIMS Dergee &PG College
Notes For Visual Basic 6.0 40 P.MallaReddy

Values - A single value or an array of values for the fields in the new record. If fields is an array, Values
must also be an array with the same number of members.


ADO: Navigating a Recordset:

After creating a Recordset object, the various methods can be used to navigate through the recordset.
The MoveFirst : Method moves to the first row in the Recordset
The MoveLast : Method moves to the Last row in the Recordset
The MoveNext : Method moves to the Next row in the Recordset
The MovePrevious : Method moves to the Previous row in the Recordset

Using BOF and EOF to navigate through Recordset

The Recordset object provides two properties for the user to know when he has moved to the
beginning or end of the recordset
The EOF (End of File) property is True when the user moves beyond the last record in the recordset.
The BOF (Beginning of file) property is true when the user moved to a position before the first record in the
Modifying and Deleting Records
To manipulate a recordset, the following methods are used.

Edit Method:
The user can edit the current record using the edit method. The Update method is used to save the
necessary changes made to the records.
AddNew Method: AddNew method is used to add a blank record in the recordset.
Delete Method: This method can be used to delete record in the dynaset-type recordset. The Jet-engine
deletes the current record without any warning when the Delete method used.

Input Validation
What is Input Validation?
Input validation is the process of checking the data entered by the user before that data saved to the database.
This is some times referred to as Client-side validation. This is because the validation action happens at
clients workstation.

Common Input Validation Rules

Almost every field in your database required some type of input validation. Before you design form, put
together a list of all fields you need on the form and answer the following questions.
Must data be entered in the field? (Is it required field?).
What characters are valid/invalid for this field (numeric input only, capital letters only, on space
allowed, and so on)?
For numeric field is there high/low range limit?

If possible, limit the keystrokes to valid values only. For example is the field must be numeric, dont
allowed the user to enter character values. If space are not allowed, make sure spacebar is disabled.

Limit input choices with lists. If there is a limited set of valid inputs for a field, give the user a pick
list or set of radio buttons to choose from.
Input the user of range limits. If the field has the low and high limit, tell the user what the limits are.
KIMS Dergee &PG College
Notes For Visual Basic 6.0 41 P.MallaReddy

Point out required fields on a form. Mark required fields with a leading asterisk (*) or some other
appropriate character.

Field level Validation

The first level of validation is at the field level. This is the place where you can make sure the user is
entering the right character in the field, entering the data into the field in proper format, and entering a valid
value based on a list of possible choices.

Discarding Unwanted Keystrokes

Limit data entry in the Key press events

Private sub text1_KeyPress (Keyascii As Integer)

Dim str as string
Str = 0123456789.

If Instr(str,chr(keyascii) ) = 0 then
Keyascii = 0
End if
End sub

You declare a string that holds the list of valid keys. The next line loads the string with the valid key
fields, and the next line checks to see weather the key pressed is in the string of valid keys. It does this by
converting the numeric value passed by Visual Basic in the keyascii parameter (the ASCII value of key
Pressed) into readable character using function chr( ).

To convert the input characters into uppercase

Private Sub text1_Keypress(KeyAscii As Integer)

KeyAscii = Asc(Ucase(chr(KeyAscii))) change to upper case
End sub

Input Masking
It is very common to have fields on your form that required special input formats. Examples of
special formats are telephone numbers, government or employee identification numbers, hour / minute time
entry, and so on. VB 6 ships with a bound data control that handles special input and display formatting: the
MaskedEdit control. The MaskedEdit control works like the standard VB 6 textbox control, with few added
properties that make it a powerful tool for your input validation.
To add MaskedEdit control, first select the project, components and then click on Browse button, scroll
down the list to MSMASK32.OCX select it and click on OK button.

The Masked Edit control provides restricted data input as well as formatted data output. This control
supplies visual cues about the type of data being entered or displayed. This is what the control looks like as
an icon in the Toolbox:

File Name


Class Name
KIMS Dergee &PG College
Notes For Visual Basic 6.0 42 P.MallaReddy


Format: Specifies the format for displaying and printing numbers, dates, times, and text.

Mask: Determines the input mask for the control.

Syntax [form.]MaskedEdit.Mask [ = string$]

Remarks: You can define input masks at both design time and run time. However, the following are
examples of standard input masks that you may want to use at design time. The control can distinguish
between numeric and alphabetic characters for validation, but cannot check for valid content, such as the
correct month or time of day.

Mask Description

Null String (Default) No mask. Acts like a standard text box.

##-???-## Medium date (US). Example: 20-May-92

##-##-## Short date (US). Example: 05-20-92

##:## ?? Medium time. Example: 05:36 AM

##:## Short time. Example: 17:23

The input mask can consist of the following characters.

Mask Description

# Digit placeholder.

. Decimal placeholder. The actual character used is the one specified as the decimal placeholder
in your international settings. This character is treated as a literal for masking purposes.

, Thousands separator. The actual character used is the one specified as the thousands separator
in your international settings. This character is treated as a literal for masking purposes.

: Time separator. The actual character used is the one specified as the time separator in your
international settings. This character is treated as a literal for masking purposes.

/ Date separator. The actual character used is the one specified as the date separator in your
international settings. This character is treated as a literal for masking purposes.

\ Treat the next character in the mask string as a literal. This allows you to include the '#', '&',
'A', and '?' characters in the mask. This character is treated as a literal for masking purposes.

& Character placeholder. Valid values for this placeholder are ANSI characters in the following
ranges: 32-126 and 128-255.

KIMS Dergee &PG College

Notes For Visual Basic 6.0 43 P.MallaReddy

> Convert all the characters that follow to uppercase.

< Convert all the characters that follow to lowercase.

A Alphanumeric character placeholder (entry required). For example: a z, A Z, or 0 9.

A Alphanumeric character placeholder (entry optional).

9 Digit placeholder (entry optional). For example: 0 9.

C Character or space placeholder (entry optional). This operates exactly like the & placeholder,
and ensures compatibility with Microsoft Access.

? Letter placeholder. For example: a z or A Z.

Literal All other symbols are displayed as literals; that is, as themselves.

Prompt: Sets or returns the character used to prompt a user for input.

Syntax [form.]MaskedEdit.PromptChar [ = char$]

Remarks: The underscore character "_" is the default character value for the property. The PromptChar
property can only be set to exactly one character.

Note: To clear the Text property when you have a mask defined, you first need to set the Mask property to
an empty string, and then the Text property to an empty string: MaskedEdit1.Mask = ""

MaskedEdit1.Text = ""

Form Level Validation : Form level validation is an essential part of designing a good validation
scheme for your form. Although many input errors can be caught and corrected at the field level, there are
several validation steps that can be performed well only at the form level.
The form level validation is performed at the time when the user presses Enter, or clicks the OK or Save
button. These are validations that are done after the user has entered all the fields, but before any attempt is
made to store the values to a table.

KIMS Dergee &PG College