Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
20 views

Visual Basic Basics notes

This document serves as an introductory tutorial to Microsoft Visual Basic, covering its integrated development environment (IDE) and basic programming concepts. It explains the elements of the IDE, including the Menu Bar, Toolbars, and Code Editor, and guides the reader through creating a simple 'Welcome' application. Additionally, it discusses properties, methods, events, and the client-server architecture in the context of database applications.

Uploaded by

leslymanjokota8
Copyright
© © All Rights Reserved
Available Formats
Download as DOC, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
20 views

Visual Basic Basics notes

This document serves as an introductory tutorial to Microsoft Visual Basic, covering its integrated development environment (IDE) and basic programming concepts. It explains the elements of the IDE, including the Menu Bar, Toolbars, and Code Editor, and guides the reader through creating a simple 'Welcome' application. Additionally, it discusses properties, methods, events, and the client-server architecture in the context of database applications.

Uploaded by

leslymanjokota8
Copyright
© © All Rights Reserved
Available Formats
Download as DOC, PDF, TXT or read online on Scribd
You are on page 1/ 339

CHAPTER 1

Visual Basic Basics


Introduction
Welcome to Microsoft Visual Basic. This tutorial leads you to the wonderful and fascinating world of
Windows Programming using Visual Basic. In the name Visual Basic, the "Visual" part refers to the
method used to create the Graphical User Interface (GUI) and the "Basic" part refers to the
computer language BASIC (Beginners All-purpose Symbolic Instruction Code).
Visual Basic is widely used because of its Visual Design feature and its capability for Database
Programming, ActiveX Programming and Internet Programming. It provides a complete set of tools
to simplify the Rapid Application Development (RAD). You can get a vivid idea of all concepts of
Visual Basic while going through this study material. In the first step, we shall see what integrated
development environment is.
The Integrated Development Environment (IDE)
Visual Basic has an integrated development environment in which one can develop, run, test and
debug the applications.
To start Visual Basic from Windows
1.
Click Start on the Task bar.
2.
Select Programs, and then go to Microsoft Visual Basic 6.0.
3.
Click on Visual Basic 6.0
You can also create a shortcut to Visual Basic on the desktop, and double-click the shortcut to open
Visual Basic.
When you first start Visual Basic, you see the interface of the integrated development environment.

Visual Basic Integrated development Environment is given below.

Integrated Development Environment Elements


The Visual Basic integrated development environment (IDE) contains the elements with which you
can develop the user interface of your application. The elements are,
Menu Bar
It displays the commands you need to work with Visual Basic. Menus are provided for standard
actions like File, Edit, View, Window, and Help and to access functions specific to programming such
as Project, Format and Debug.
Context Menus

1
They contain shortcuts to frequently performed actions. To open a context menu, click the right
mouse button. The specific list of shortcuts available from context menus depends on the part of
the environment where you click the right mouse button.
Toolbars
They provide quick access to commonly used commands in the programming environment. You can
click a button on the toolbar once to carry out the action represented by that button. Additional
toolbars for editing, form design, and debugging can be toggled on or off from the Toolbars
command on the View menu.
Toolbox
It contains a set of tools that can be used at design time to place controls on a form. You can create
your own custom layouts by selecting Add Tab from the context menu and adding controls to the
resulting tab.

Project Explorer Window


This window lists the forms and modules in your current project. A project is the collection of files
used to build an application.
Properties Window
This window lists the property settings for the selected form or control. A property is a
characteristic of an object, such as name, size, caption, color, etc.
Object Browser
Object Browser is used to explore objects in Visual Basic and other applications. It lists objects
available for use in your project and gives you a quick way to navigate through your code
Form Designer
It is the window where you add controls, graphics, and pictures to a form to create the interface of
your application. Each form has a form designer window.

Code Editor Window


The Code Editor window is used for entering and editing the programming code for an application.
Each form has its own code editor window. By double-clicking on an object, the corresponding Code
Editor window will open.
A Code Editor Window is given below.

Form Layout Window


The Form Layout window allows you to position the forms in your application. It provides a small
graphical representation of the screen.
Form Layout window is given below.

2
Immediate, Locals, and Watch Windows
These windows are included in the IDE for use in debugging your application. They are available
only when you are running your application.
Now you have an idea of the elements in the Visual Basic IDE. To understand the Visual Basic
environment better, you can go through the sample application described in the next topic.
Your First Visual Basic Program
All Right! Now it's time to create a real time, live, small Visual Basic program. Let us write a simple
Welcome application, which displays a Welcome Message after pressing the Print button.
Step 1: Planning and Designing
The most difficult part in creating any application is deciding what it will do. When that's
accomplished, the remaining parts become clearer. The time you spend planning and designing an
application is the most important part of the project. You can gain time for your project by doing
proper planning and analysis before writing any programs.
Let's start our design.
Our Goal: Make a simple program that displays a Welcome Message when the user presses a
Button. In order to make this small program, we need a "user interface" with a button and a way for
displaying the Welcome message.
Step 2: Designing the Interface
The next step in creating a Visual Basic application is the design of the visual interface. This means
we are going to start with a blank form and put the needed controls on it. Since our planning and
designing is already done we can directly go to visual layout-where the controls are placed.
To go into the visual layout window:
1. Start the Visual Basic IDE
2.
In the IDE, the New Project Dialog box will appear.
3.
In the New Project Window Dialog Box Click the Standard Exe Icon, then the Visual layout
window will appear.
In our application we need a Label control for displaying the Welcome message and a Command
Button.
To add a label control into the form:
1.
Click the Label Button in the Toolbox.
2.
Move the mouse pointer to the form, where it will be seen as a cross. Point at the location
where you want the Welcome Message to be displayed.
3.
Click and hold the mouse button and move the pointer to the opposite corner of the label.
As you do this, you will see a rectangular outline following the pointer, indicating the label
size. This technique is called Dragging.
4.
When the required outline size is obtained, release the mouse button. Visual Basic will
place a label with the default caption Label1 on the form.
Now the label control is on the form. Note that the new control has eight small boxes displayed on
its perimeter called handles. They can be used to change the size of the control.
3
Adding the command button is also same as above:
1.
Point the mouse cursor to the Command Button in the Toolbox and click.
2.
Move the mouse pointer to the form, where it will be displayed as a cross. Point at the
location where you want the Command Button to be displayed and proceed as before.
Step 3: Setting Properties
The Properties window provides an easy way to set properties for all objects on a form.
The properties window is shown below.

To set properties from the Properties window


1.
From the View menu , choose Properties or click the Properties Button on the Toolbar .
The Properties window displays the settings for the selected form or control.
2. You can set properties either by typing or selecting one of the listed properties from the
predefined list of settings.
In our Welcome program we can set the properties of the controls as follows:
Object Property Setting
Form Name frmWelcome
Form Caption Welcome
Label1 Name lblWelcome
Label1 Caption (Empty)
Command button Name cmdPrint
Command button Caption Print
Saving the Project:
While Saving the project, first save the Form and then save the project. To save, pull down the File
Menu by clicking on File in the Toolbar, select Save Project command. Visual Basic will then
display the Save File As dialog box, in which you can specify the name as "frmWelcome". The file
will be saved with default extension .frm. You can also open the Save File As dialog box by clicking
the Save Project button on the Toolbar. Next Visual Basic displays the Save Project As dialog box,
in which the default project name, Project1 will be displayed. Here type "Welcome" and press Enter.
The project will be saved with the extension .vbp.

4
Step 4: Writing the Code
The next step is to write the code for the Project to make it work. In our case the "work" consists of
displaying the Welcome message when the Command button is pressed.
The code required for this project is very simple. The first step in adding code is to switch from form
design mode to code editing mode.
You can do this as follows:
By double clicking anywhere in the form or by clicking Code in
the View Menu.
or by selecting View Code from the Popup menu.
or by selecting the View code option from the Project Explorer Window.
The code editor window is shown below,

After opening the code editor window, do the following


1.
In the Object list box, choose cmdPrint (the name of the Command button).
2.
In the Procedure list box, select the name of the event for the selected object that you
wish to place the code into. Here, the Click Event will be already selected, because it's the
default procedure for a command button.
3.
Type the following code between the Sub and End Sub statements.
lblWelcome.Caption = "Welcome to the World of Visual Basic"
Then the code will be seen as Follows:
Private Sub cmdPrint_Click()
lblWelcome.Caption = "Welcome to the World of Visual Basic"
End Sub
Step 5: Running the Application
To run the application, choose Start from the Run menu , or click the Start button on the
toolbar, or press F5 . Click the "Print" button on the form, and you can see the message "Welcome
to the World of Visual Basic" displayed on the label. The sample output of the application is shown
below.

5
You can get familiar with the terms properties, methods and events from the next topic.
Properties, Events and Methods
In the first topic, you have seen various elements in the Visual Basic IDE. Each and every
component in the Visual basic IDE has its own properties, events and methods.
Properties
The Property of an object may be defined as its attributes. For example, a TextBox has the
properties Name for identification, Text for the displayed data, Background Color, Foreground Color,
etc.
Methods
The methods are the actions that an object can perform. Some methods are simple verbs that tell
the objects the action to carry out. For example for a DataControl, the AddNew is a method for
adding a record into a database.
Events
The events will determine a controls responses to external conditions. Different controls will often
have their own "copy" of the same events. For example, the Click is an Event of many different
controls including a Command Button. In the events is where you will often write code that tells
your program what to do, and upon what "event".
In the sample program explained in the previous chapter, when you click the Command Button
named Print, the message "Welcome to the World of Visual Basic" is displayed on the Form. Here
the caption "Print" is a property of the Command Button and Click is the event of the Command
Button. The message is displayed by changing the caption property of the label..
Now you have got a brief idea of properties, methods and events. You will start to understand what
is going on internally if you know what Windows Programming is about. You can learn that in the
next topic.

Windows Programming Concepts


Visual Basic is used for developing Windows based applications. A deep understanding of all of the
technical details of Windows programming isn't necessary in order to write successful programs,
but a basic idea of the working of Windows is necessary. It involves three key concepts- windows,
events and messages.
What is a Window?
As a computer aware person, you probably have an idea what a Windows is. Windows are generally
a defined area on the screen where you interact with the computer. A window may have different
buttons, boxes, lists etc. All applications you use on a Windows PC interact with you through
windows. What is not so obvious, is that most smallerregions of these applications are individual
windows too. For example, the Command Button in the first example is itself, a window.
The Microsoft Windows operating system manages all the windows by assigning each one a unique
id number (window handle). The system continually monitors each windows for events. Events can
occur through user actions such as a mouse click or a key press, through programmatic control, or
6
even as a result of another window's actions. Each time an event occurs, it causes a message to be
sent to the operating system. The system processes the message and broadcasts it to the other
windows. Each window can then take the appropriate action based on its own instructions for
dealing with that particular message.
Visual Basic insulates you from having to deal with all of the low-level message handling. Many of
the messages are handled automatically by Visual Basic; others are exposed as Event procedures
in order for you to write programs that respond to these conditions. This simplification that Visual
Basic creates for you allows you to quickly create powerful applications without having to deal with
many complicated details.
A description of client-server architecture is given in the next topic.
Introduction to Client-Server Architecture
Client-Server architecture refers to distributing the processing of an application between a front-
end client workstation component and a back-end server component. Client-Server Architecture is
used to access heterogeneous data that resides on different hardware platforms, different
operating systems, different network operating systems, and different databases. Much of the data
used today is currently stored in mainframe and mini-computer databases, and the main
functionality of Client-Server Architecture is to bring this mission-critical data to the desktop and
integrate it with the functional, easy-to-use graphical user interfaces (GUIs), that are associated
with personal-computer based tools like Visual Basic.
Ideally, the server is responsible for managing all the requests it receives from other processes,
including request queue management, buffer management, execution of the service, results
management, and notification of service completion.
It is the client’s task to initiate communications, request specific services, acknowledge service
completion notifications, and accept results from its server. User-intensive functions, such as
handling input and displaying data, are left to the user’s Visual Basic application. Data-intensive
functions, such as file I/O and query processing, are left to the relational database management
system (RDBMS).
In client-server application development, two commonly used terms are front-end and back-end.
They are defined in the next topic.
The Idea of Front End and Back End
When we work with Visual Basic to create a database application, we are actually generating a
database front end. A database Front end is an application that can be used to view and manipulate
the data in a database. Then the Back end is the set of related database tables, and in some cases,
the database engine that serves as the interface between the front and back ends of a database.
The idea of front end and back end is introduced to manipulate a complex database system using
the most simple windows based system.
Database front ends generally fall in two categories. The Decision support applications and
Transaction Processing applications.
In Decision support applications, users are permitted to view and query information in the
database, but not to add or modify information.
In transaction processing application users have capability to add, delete, and edit data in the
database.
Self Assessment
Click the Tick mark to select an answer.
(1). Form Layout is used for,
(a) Coding.
(b) Form Designing.
(c) For setting the position of the form.
(d) For setting the properties.
(2). Front End means.
7
(a) All parts of the program that are visibly seen by the user.
(b) The user interface.
(c) The database processing of a client server system.
(d) To stop a program at the front.
(3). Of the following, which one is not a debugging tool.
(a) Immediate Window.
(b) Local Window.
(c) Code Editor Window.
(d) Watch Window.
(e) None of the above.
(4). Visual Basic is a,
(a) GUI.
(b) ActiveX Programming Tool.
(c) Windows Programming Tool.
(d) All the above.
(e) None of the above.
(5). KeyPress is a,
(a) Property.
(b) Event.
(c) Method.
(d) None of the above.
Workshop
1. What are the different ways to start Visual Basic?
2. What is an IDE?
3. What are properties, events and methods?
4. Define the term Client-Server?
5. Define front-end and back-end? Why are they called so?
Exercise
Chapter-1
Workshops – Solution
1. What are the different ways to start Visual Basic?
Microsoft Visual Basic IDE can be started by any of the following methods:
a. By clicking the Start on the Task bar, select Programs
and Click on Visual Basic 6.0
b. By double clicking the shortcut on the desktop.
2. What is an IDE?
IDE stands for Integrated Development Environment. Using this, one can develop, run, test and
debug the applications.
3. What are properties, events and methods?
Property of an object can be defined as its attribute. For example, a TextBox has the properties
Name for identification, Text for the displayed data, Background Color, Foreground Color, etc.
Events are those which controls the responses to the external conditions. For example, the
clicking is an event. This means that, when user clicks the mouse, the actions defined under this
event will occur.
Methods can be defined as the actions that an object can perform. For example, the
“AddNew” is a method of the Data Control.
4. Define the term Client-Server?
The term Client-Server can be defined as an architecture that can distribute the processing of
an application between a front-end workstation component and a back-end server component.
5. Define front-end and back-end? Why are they called so?
8
The front-end can be defined as an application that can be used to view and manipulate the
data in the back-end. The back-end is a set of related database tables. This system is
introduced to simplify the complexity of database-based applications in the windows
environment.
Exercise – Solution
Write a program to display your name as the form loads.
Using the following steps, this problem can be solved.
Step 1:
Create a Standard EXE project.
Step 2:
Then set the properties of the form as given below:
Control Name Property Caption Property
Form frmMyname My Name
Step 3:
Write the following code in the Activate event of the Form.
Private Sub Form_Activate()
’ Give the name to print
Print "Mr.Allen Cooper"
End Sub
Step 4:
Then save and execute the program.
The sample output is shown below.

Write a program to display your name as the form loads

9
CHAPTER 2
Types of Interfaces
The Interface is the media through which the user can interact with the application. In Windows
based applications there are two styles of interface, Single Document interface (SDI) and Multiple
Document Interface (MDI). Of these two, the more widely used one is single document interfaces. In
addition to the these interface styles, a third one is becoming more popular - the explorer-style
interface.
In Multiple Document Interface, one window, called MDI container or MDI parent, contains many
other windows, usually called child windows. You can have only one MDI parent form to a project
and that form must be the startup form. Here you can move the child windows only within the
larger parent window. Microsoft Word is a good example of an MDI Interface.
In Single Document Interface (SDI) there is only one window and only one document at a time can
be opened in it. An independent window should be opened to view another document
simultaneously and any number of independent windows can be opened. WordPad is an example of
single document interface.
The Explorer style interface is like the Windows Explorer program. In this type of Interface the
window has mainly two regions. One region contains a tree view and the other region contains the
display region.
In the next topic you can learn how to add different controls on a form to design the interface of
your application.
Adding and Pasting Controls on a Form
In Visual Basic there are two methods for placing controls on a form. They are described below
By Double Clicking the desired control on the Tool Box.
1.
Double Click the desired control on the Tool Box.
2. Visual Basic will place a control with a default size, in the center of the form.
3.
You can change the control's position and size by dragging and resizing graphically, or, by
setting the Properties.
By the Dragging method
1.
Click the control on the toolbox.
2.
Move the pointer onto your form.
3.
Drag the handles until the control is in the size you want.
4.
Release the mouse button.
Placing a control by dragging is easier than placing by double-clicking. If you have placed a control
and want to place more controls of the same size and type, you can copy the original. This will
generate a Control array. A group of controls that share the same name, type and event
procedures is called a control array. The procedure for creating a control array is shown below:
1.
Select a control, which is on the form.
2.
Copy the selected control into clipboard.
3.
Select Paste from the Edit menu, Visual Basic displays a dialog box asking whether you
want to create a control array.
4.
Select Yes.
5.
To place additional copies of the control on the form, select Paste from Edit Menu.
Next topic explains how to manipulate a form. Some of the important properties of forms are also
given there.
Manipulating the Form
For a Visual Basic Programmer the design of the user Interface is an important task. This is because
the interface is the part that the user sees and it is how we, as programmers communicate what
the user should do. While designing an application, start with the interface, through which the user
first interacts with the application.
10
You can use the Form Layout Window to change the Form's position when in the Run mode. To
change the size, point at one of the Form's borders and drag to the new size. Alternatively, you can
do this by using code or by setting properties.
The important Properties which influences the Form design are given below:
1.
Border Style: This property is used for setting the form's border style, to set whether it is
none, sizable, FixedSingle or FixedDouble .
2.
ControlBox: This property indicates whether a Control-menu Box is displayed on a Form.
3.
Height, Width: This properties determines the height and width of the Form.
4.
MaxButton, MinButton: This property determines whether the Form will have a Maximize
Button or Minimize Button.
The Form Layout Window is shown below.

In the last topic you saw how to add controls on a form. The next topic describes how to align and
change size and position of a control.
Moving, Sizing and Aligning Controls
Placing controls is also an important part of Interface design. To move or align controls on a Form,
first select the control or controls you wish to work with. To select a control, simply click it. To select
multiple controls, click on any one control, then press and hold the shift key while you click the
others.
You can change the size of a selected control by pointing at one of its handles and dragging the
outline to the desired size. The position can be changed by clicking the control and dragging it to
the new position. If you have selected more than one control, you can move them as a group, with
individual controls retaining their positions relative to each other.
Another important problem for the Visual Basic Programmers is the alignment of controls. This can
be made easier by using the Visual Basic design grid. Another feature of controls is that they can be
overlapped, with one completely or partially hidden by the other control. You can make a
combination of overlapped controls by Setting the Order property as "Bring to front" or "Send to
back" from the Format menu. Bring to front brings the selected control as the top of several
overlapping controls, so that it will be visible and hide other controls. Send to back have the
opposite effect.
You can also lock the controls on a form to prevent them form being modified. This can be done by
selecting the Lock controls command on the Format menu. Select this command again, to unlock
the controls.
A sample application using Labels, TextBoxes and Command Buttons is described in the next topic.
Sample Project: Salary Calculation
Description
This application is for calculating the salary of an employee by giving the information such as Basic
Salary, Federal Tax Amount, State Tax Amount, 401(K) Deduction Amount and Health Insurance
Amount. You can create and run this application by following the steps given below. The steps are,
1. Open the Visual Basic IDE and start a Standard EXE Project

11
2. Here we need Labels to display data, TextBoxes to display and enter data and
CommandButtons for getting the user interaction and response to invoke the
events.
3. Place three Command Buttons, eleven Labels, and six TextBoxes on the Form
4. Set the Properties as shown below:
Control Name Property Caption/Text Property
Form frmSalcal Salary Calculator
Command Button1 cmdClear Clear
Command Button2 cmdCompute Compute
Command Button3 cmdClose Close
Label1 lblCaption Salary Calculator
Label2 lblName Employee Name
Label3 lblBaSal Basic Salary
Label4 lblFedTaxAmt Federal Tax Amount
Label5 lblStateTaxAmt State Tax Amount
Label6 lbl401DedAmt 401(K) Deduction Amount
Label7 lblHInsAmt Health Insurance Amount
Label8 lblTotsal Total Salary
Label9 lblEmpName (Empty)
Label10 lblTotsalary (Empty)
Label11 lblEName Employee Name
TextBox1 txtName (Empty)
TextBox2 txtBaSal (Empty)
TextBox3 txtFedTaxAmt (Empty)
TextBox4 txtStateTaxAmt (Empty)
TextBox5 txt401DedAmt (Empty)
TextBox6 txtHInsAmt (Empty)
The Net Salary is calculated using the formula,

txtTotSalary = txtBaSal - txtFedTaxAmt - txtStateTaxAmt - txt401DedAmt - txtHInsAmt.


This procedure is written in the click event of Compute Button as follows:
Private Sub cmdCompute_Click()
'Clears the label
lblTotSalary = ""
‘Salary calculated is assigned to the lable lblTotSalary
lblTotSalary =Val(txtBaSal) - Val(txtFedTaxAmt) - Val(txtStateTaxAmt) - Val((txt401DedAmt) -
Val(txtHInsAmt)
'Concatenating it with the '$' sign
lblTotSalary = Chr(36) & " " & lblTotSalary
lblEmpname = txtName
‘To make the label controls visible.
lblTotSalary.Visible = True
lblTotSal.Visible = True
12
lblEmpName.Visible = True
lblEName.Visible = True
End Sub
The Total Salary is calculated and assigned to the caption property of the label, lblTotSalary. As the
Total Salary is calculated, the Labels lblEmpName, lblEName, lblTotSalary and lblTotSal will be
made visible to display the result.
5. Then in the Click event of the Command Button, cmdClear the following code is written
for clearing the controls and to make the Labels invisible, that were used to display the result.
Private Sub cmdClear_Click()
‘To clear the controls.
txtName = ""
txtBasal = ""
txtFedTaxAmt = ""
txtStateTaxAmt = ""
txt401DedAmt = ""
txtHInsAmt=""
‘To make the controls invisible.
lblTotSalary.Visible = False
lblTotSal.Visible = False
lblEmpName.Visible = False
lblEName.Visible = False
'Setting the focus to the Text
txtName.SetFocus
End Sub
6. To terminate the application write the following code,
Private Sub cmdClose_Click()
‘Terminating the application.
End
End Sub
The output form of this application is shown below,

Self Assessment
Click the Tick mark to select an answer.
1. How many types of Interfaces are there in Windows ?

13
(a) One

(b) Two

(c) Three

(d) Four

(b) None of the above.


2. The term MDI stands for:
(a) Multiple Device Interface

( b) Multiple Document Interface

(c) Multimedia Digital Interface

(d) Microsoft's Developer Interface

(e) None of the above.


3. An Example for MDI is:
(a) Microsoft's WordPad

(b) Microsoft Word

(c) Windows Explorer

(d) All the above

(e) None of the above.


4. The properties "Height and Width" is used in Form control to:
(a) Change the Interface style.

(b) Resize the Form.

(c) Give 3-D effect to the controls in a Form.

(d) All the above

(e) None of the above.


5. Of the following which command is used to pervent the controls from being modified:
(a) LockControls

(b) FixControls

(c) Bring to Front

(d) All the above

(e) None of the above.


Workshop
14
1. What are the methods to place a control on the form?
2. What is a control array?
Exercise
Create an SDI application to move a TextBox as the Command Button is clicked.

15
Chapter-2
Workshops – Solution
1. What are the methods to place a control on the form?
There are two methods for placing controls on the form. They are given below:
a. By double clicking the desired control in the Tool box. This method involves the following
steps:
1. Double Click the desired control on the Tool Box.
2. Visual Basic will place a control with a default size, in the center of the form. Using the
properties the size and the position of the controls can be alter.
b. By using the Dragging method
This involves the following steps:
1. Click the control on the toolbox.
2. Move the pointer onto your form.
3. Drag the handles until the control is in the size you want.
4. Release the mouse button.
2. What is a Control array?
The Control array is a group of controls that share the same name, type and event procedures.
Exercise – Solution
Create an SDI application to move a Textbox as the Command Button is clicked.
By using the following steps, this problem can be solved.
Step 1:
Create a Standard EXE project.
Step 2:
Select a Text Box and a Command Button in the form.
Then set the properties as shown below:
Control Name Property Caption/Text property
Form frmMove Moving the TextBox
Command Button cmdClick Click Me
TextBox txtBox Visual Basic
Step 3:
Then write the following code in the Click event of the Command Button, cmdClick.
Private Sub cmdClick_Click()
' Changing the Text box's positions
txtBox.Top = txtBox.Top + 10
txtBox.Left = txtBox.Left + 10
End Sub
Step 4:
Then save and run the application. The sample output is given below.

16
CHAPTER 3
Visual Basic Code Editor Window
One thing that you should be aware of is the number of different things you must keep track of
inside a program. There can be hundreds of different controls; each control can have several
different small programs and so on. The idea is that there are many details to keep track of when
programming. This reality creates a necessity for the ability to organize and control all materials
associated with a program so you do not spend too much time looking for things.
The code for a Visual Basic application is written in a specialized window called Code Editor. It is like
a word processor with a number of features that make writing Visual Basic code easier. The code
window has a caption that displays the name of the form being worked on.
The Visual Basic code is stored as modules. If you have only one form, then the entire code can be
written in a single module. If you have more than one form and if you want some of the code
common to different modules, you can use a standard module. There is also module for storing
"class" code for the projects standard classes... You will learn more about classes later.
Each module contains a declaration section and procedure section.
A separate Code Editor window is opened for each module that you select from the Project Explorer.
Code within each module is further subdivided into separate sections for each object contained
within the module. Switching between code sections is done by selecting a particular object from
the Object Listbox. In a form module, the list includes a general section, a section for the form itself,
and a section for each control contained on the form. For a class module, the list includes a general
section and a class section and for a standard module only a general section is shown.
The Visual Basic Code Editor window is shown below.

A basic idea about coding conventions and suggested conventions which you can use while coding
are described in the next topic.
Coding Conventions
While coding, one should follow some type of convention so that the code becomes readable and
understandable to yourself and others. In large projects, common naming standards are essential
to reduce the occurence of bugs, and to make your programming intentions clearer to others and
theirs to you.
The conventions below aim only on the physical structure and appearance of the code. Different
organizations will have different standards. A consistent set of coding conventions can be used to
standardize the structure and coding style of an application. It can include the following:
 Conventions for naming.
 Formats for labeling.
 Conventions for commenting the code.
 Conventions for spacing, formatting, and indenting.

17
The coding conventions defined should satisfy a minimum set of requirements so that the
programmer becomes free to implement the program's logic and functional flow. Try to write the
code as modules so that it can be more easily understood.

Conventions for Naming Objects

While naming objects, a prefix should be included so that the type of the object can be identified
easily. Conventions generally used in Visual Basic for some of the objects are listed below.
Prefixes for Controls
Controls Prefix Example
3DPanel pnl pnlEx
Animated button ani aniDo
Check box chk chkStyle
Combo box cbo cboGrade
Command button cmd cmdCompute
Common dialog dlg dlgAsp
Communications com comAbc
Data control dat datTab1
Data-bound combo box dbcbo dbcboList
Data-bound list box dblst dblstTab2
Directory list box dir dirMyc
Drive list box drl drlMydt
File list box flb flbMyd
Form frm frmExg
Frame fra fraComb
Graph gra graBr
Grid grd grdFr1
Horizontal scroll bar hsb hsbFr2
Image img imgVB
Key status key keyA1
Label lbl lblName
Line ln lnXY
List box lst lstCoun
MDI child form mdi mdiMain
Menu mnu mnuHelp
MS Tab mst mstBb
OLE ole oleCom
Picture pic picBg
Report rpt rptSal
Shape shp shpRect
18
Spin spn spnS5
Text box txt txtIdno
Timer tmr tmrAni
UpDown upd updU1
Vertical scroll bar vsb vsbFr2
Slider sld sldDs
ImageList imls imlsAni
TreeView tre treDir
Toolbar tlb tlbMain
TabStrip tab tabNb
StatusBar stb stbHelp
ListView lvw lvwNum
ProgressBar prb prbInst
RichTextBox rtxt rtxtAdd
Prefixes for Data Access Objects (DAO)
The prefixes to indicate Data Access Objects are as follows:

Database object Prefix Example


Container con conFrm
Database db dbPurchase
DBEngine dbe dbeDetails
Document doc docDer
Field fld fldFr2
Group gr grTab1
Index idx idxId
QueryDef qrd qrdSq1
Recordset rec recSq2
Relation rel rel12
TableDef tbd tbdSam1
User usr usr1
Workspace wsp wspUs1
Prefixes for Menus
While naming menu controls an additional prefix for each level of nesting should be added to the label mnu. The final menu caption is added at the end of this string. This convention helps to identify the menu items

to which each menu control is attached. Some examples are given below.

Menu caption sequence Menu handler name


Open Document mnuOpenDocument
Read Document mnuReadDocument
Help mnuHelp
Prefixes for Other Controls

19
For controls not listed in this topic, a standard format can be followed, like a prefix consisting of two
or three character can be added. If you need more clarity, then use more than three characters.
Conventions for Naming Constants And Variables
A good set of conventions should be followed while naming constants and variables. Variables
should be defined where they will be used.Try to avoid the use of global variables but use them if
you must. When they are used, declare them all in a single module, grouped by functions.

Variable Scope Prefixes


It is generally a safer programming practice to allow a variable to be changed in certain parts of a
program. In most modern programming languages, the concept of Scope gives the programmer
control of what parts of the program has access to a particular variable. The Scope of a variable
identifies where it is available to be used, and not used.
Determining the scope of a variable becomes a tedious task as the size of the project grows. This confusion can be avoided by adding a one-letter scope prefix to the variable name.

Scope Prefix Example


Global g gintx
Module-level m mstrNm
Local to a procedure None None
Constants
A constant name can be in mixed case with capitals as the first letter. Data type and scope
information are not usually included while naming constants, but you can use prefixes like i, s, g,
and m to show its value and scope. The conventions for naming variables can be used for constants
also.
Variables
Although Visual Basic allows creating variables as needed, all variables should be declared initially
to reduce the occurrence of bugs. Variable name should be prefixed to indicate their data type and
scope.
Variable Data Types
The following prefixes can be used to indicate a variable's data type.

Data type Prefix Example


Boolean bln blnOpt
Byte byt bytMt
Collection object col colIm
Constant cst cstAbc
Currency cur curInd
Date dt dtDisp
Double dbl dblSal
Error err errCd1
Integer int intFlag
Long lng lngIy
Object obj objF1
Single sgl sglB3
String str strName
User-defined type udt udtHm

20
Variant vnt vntX
Descriptive Variable and Procedure Names
In the name of a variable or procedure, use mixed case. The name should be long enough to
describe their purpose. Function name should begin with a verb, which indicates its purpose. Name
lengths can be kept reasonable by using standard abbreviations.
User-Defined Types
A large project can contain many user-defined types. While naming them, a three-character prefix
can be added. The user-defined types can be easily identified by using the prefixes beginning with
"u".
Structured Coding Conventions
The readability of the code be improved by using structured coding conventions, such as code
commenting and consistent indenting.
Code Commenting Conventions
It is a good practice to include comments while coding, so that anyone can easily follow the code. A
brief comment describing the functional characteristics of a small group of instructions as well at
the beginning of a procedure or function. The range of the arguments and their functions should be
described. Return values of the functions and global variables must also be described at the
beginning of each procedure.
Formatting Your Code
The code should be formatted in such a way to achieve maximum readability. The formatting
should be done so that the structure and nesting in the code is highlighted. The inner procedures
should be written with a tabspace more than its higher-level statement. Procedures should be
separated with a blank line.
The data types in Visual Basic are illustrated in the next topic.
Data Types in Visual Basic
Variables usually hold information. They are a named area in the computer's memory used
to store information. Visual Basic variables can have names up to 255 characters long, but you
want to keep the much shorter. The first character of the name of a variable should be a alphabetic
character and the rest can be combination of alphabets, numbers, and underscores. The variables
are not case sensitive. Variable names should be meaningful and no reserved words should be
used. It is a usual practice to use mixed case variable names. Variables can never have spaces in
them.
Types Of Variables
Visual Basic has 14 standard types of variables. It is also possible to define your own Variable
Types. This section introduces standard types of variables used in Visual Basic.
String
String variable is used to hold characters. String variables can have a variable-length or a fixed
length. Variable length strings and can hold a string of about 2 billion characters and a fixed-length
can hold a string of up to about 65,400 characters.
For example, if you have a Textbox named txtName and a variable named strName, then the value
(text) of the Textbox can be assigned to the variable as
strName= txtName
Integer
Integer variables hold small integer values compared to other integer types. The range is between -
32,768 and +32,767.

21
Long Integer
The long integer variable holds integers between -2,147,483,648 and +2,147,483,647. Long
Integer arithmetic is also as fast as integer arithmetic.
Single precision
These variables hold numbers that are approximated. They can be fractions and can provide
accuracy up to seven total digits. Calculations will always be accurate for these types of variables.
However arithmetic operations will be slower than that with integers and long integer variables.
Double Precision
Double precision variables hold more than 300 digits. These variables are used in scientific
calculations in Visual Basic.
Currency
Certain problems arise when using decimal fractions. Currency variables are designed to avoid
these problems. To the left of the decimal point in currency type variables there can be up to 4
digits and to the right 4 digits.
Date
Date information can be stored using the Date data type. It can hold date values for any time in the
range from midnight on January 1,100 to midnight on December 31, 9999.
Byte
This data type byte can hold integers between 0 and 255. This is also used for handling binary data
in Visual Basic.
Boolean
Sometimes you need a variable with only two values, either True or False. To hold these type of
values, use the Boolean data type .
Variant
The variant type can hold any type of variables. By declaring a variable of variant type we can
assign any type of data to the variable. If any variable is left undeclared in a program Visual Basic
will treat that particular variable as variant type. Variants are the catch-all and easy to work with.
They are also the slowest variables to use and may affect programs that have speed concerns.
Declaring Variables
Variables can be declared in two ways - implicit declaration and explicit declaration. Visual Basic
automatically declares and uses a variable if it has not previously been declared. This is called
implicit declaration. Explicit declaration is done using Dim statement. Dim specifies the type of
variable to be used in a procedure. It is a good programming practice to declare variable before
they are used in code. Declaring variables makes your programs more reliable and less error prone.
Example:
Private Sub cmdCompute_Click
' Declaring the Variables
Dim intY As Integer
Dim strD As String
Dim curS As Currency
Dim intZ As Integer
End Sub
The declarations can be done on single line, for example:
Dim intY As Integer, strD As String, curS As Currency, intZ As Integer
You will make a mistake by using,
Dim strX, strY, strZ as String
On the assumption that all three will be String variables. In fact, in this declaration strX and strY will
be Variants and only strZ will be a String variable.
If you do not specify a type of a variable, by default you are choosing a variant.
Variants can be declared in two ways :
22
Dim vnt1 ' means var1 is a Variant data type.
Dim vnt1 As Variant ' declaring explicitly.
Need for Declaring Variables
One of the most common bugs in a program is the misspelled variable name. If the name of a
variable that already exists in your program is misspelled, then Visual Basic will just treat a new,
properly spelled variable as a new variable that has nothing to do with the one you wanted to work
with.
By forcing all variables to be declared initially, one can avoid this problem. The statement needed
for forcing all variables to be declared before use is Option Explicit. This statement is not used
within event procedures.
Option Explicit can be added to the code as follows:
1. Open the Code Window.
2. From the Object ListBox select General.
3. From the procedure list box select Declarations.
4.
Type Option Explicit in the space available.
If Option Explicit command is used in Visual Basic all the variables should be declared before use. If
you use a variable without declaring, an error message will be displayed.
A variable can also be declared as Static or Constant. Static is used to declare variables and
allocate space for reading and writing values. Constant is used to declare read only variables.
Changing the Default Types
In the Dim statement, if you are declaring variables without specifying the type, they will
automatically take the Variant type. To prevent this, the DefType statement can be used. A range
can be specified in the DefType statement. The variables beginning with letters in the specified
range will have the type specified in the DefType statement.
For Example, DefInt A-Z will define all the variables beginning with A-Z as integers even if the type
specification in the Dim statement is avoided.
Scope of Variables
Scope of a variable is the availability of that variable in a particular procedure. In some
programming languages, a variable declared is available throughout the program. This may create
problems where in larger programs when two variables which fundamentally are supposed to be
different, end up with the same name. In Visual Basic this problem is avoided by isolating variables
within the procedure where they are used. If several procedures have a variable with the same
name, each will be treated as different variables in Visual Basic as each variable within a procedure
is "local" to it's respective procedure.
Strings
Strings are more important in Visual Basic. Two Strings can be put together using the symbol, " &" .
This symbol can be used to join as many Strings as required.
Fixed Length Strings
A Fixed Length String is a special type of String. They are declared with the Dim statement as
shown below.
Dim strX As String * 10
If you assign a string of width more than 10 to the above String variable, it will accept only 10
characters. Even if the string has characters less than 10, the string variable will be assigned with
10 characters with spaces right padded, if necessary.
Numbers
Commas cannot be used with numbers. Decimal points can not be used with integers. Variable are
assigned a value by giving the value in the right hand side of the assignment statement and the
variable in the left hand side.
Example:

23
num_students = 14
stock_price = 35.625
If a number with decimal point is assigned to an integer type variable, only the real part of the
number will be assigned, this is generally on oversite. A string of digits can be converted into
Integer type using the built in function Val.
Eg: Val( "8432 ") will convert the String 8432 to Integer the 8432..
A number can be changed to String using Str function.
Str(123) will convert 123 to String 123.
Constants
In Visual Basic the Constant data type can be used to declare names or values that never change.
The declaration is similar to variables. Their names can have a maximum of 200 characters, but
never use this many. First character should be letter, and then the remaining can be any
combination of letters, underscores, and numerals. A constant can be declared as follows,
Const cstPrice = 450
Const cstUsername = "Philip"
Now you have seen various data types in Visual Basic. To implement an application you need
several coding structures to control the program flow. They are discussed in the next topic.
Control Structures
Control Structures are used to control the flow of execution of a program. They are used in a
program to repeat a set of operations (looping) and for making decisions according to the
conditions when a program is executing. In general, this process is known as looping.
Looping Operations
In programming, many tasks are repeats of the same set of instructions over and over. In this
scenario, you will need to create a loop. In programming there are two types of loops. A
determinate loop is repeating a set of operations a fixed number of times. An Indeterminate loop is
repeating a set of operations until you reach a predetermined condition without knowing in advance
when the condition will occur. The first situation is called determinate loop and the latter is called
indeterminate loop.
Determinate Loops
Determinate loops are those that repeat a certain lines of code a fixed number of times. Visual
Basic supports the For...Next determinate loop structure.
For....Next Statement
The For....Next loop structure is used for repeating operations in a predetermined number of times.
The syntax for For....Next statement is:
For counter = Initial Value To Final Value
Program statements
Next counter
Suppose you want to print the numbers from 1 to 10, the following lines of code can be used in a
procedure:
For intNum = 1 To 10
Print intNum
Next intNum
In the example, the initial value of intNum is 1 and then the value of intNum will be incremented
and printed from 1 to 10 .The Next keyword increments the value of intNum and the To keyword
specifies the last value for the variable intNum.

You can define the quantity to be incremented in each execution by using the Step keyword. The
syntax for that is given below:

24
For counter = Initial Value To Final Value [Step increment]
Program statements
Next counter

25
Example:
For intNum = 1 to 9 step2
Print intNum
Next intNum
The value of intNum will be printed as 1 3 5 7 9
Nested For-Next loops are those in which there are inner For-Next loops within one For-Next loop.
Example:
For intNum1=1 to 5
For intNum2=1 to 10
Print intNum1 *intNum2
Next intNum1
Next intNum2
Here the entire inner For loop will be done 10 times as indicated by the outer loop. The inner For
loop itself will then do what's within it 10 times, in this case printing out the results of some
calculations.
Indeterminate Loops
There are two types of indeterminate loops. One will be repeating until a predetermined goal is
achieved and the other will be repeating until some initial conditions change.

When you write an indeterminate loop something must change, otherwise program will lock-up with
the resulting "infinite loop". The indeterminate loops supported by Visual Basic are Do-Loop-Until,
Do-Loop-While, Do-While-Loop and While-Wend-Loop. Before that we want to understand the
meaning of the term Relational Operators.
Relational Operators
In most programs there may have need for comparing things in different ways besides equality. This can
be done using relational operators. The relational operators are listed below:
Symbol Used to Check Whether
< Less than
> Greater than
<= Less than or equal To
>= Greater than or equal To
<> Not Equal To
Do .... Until and Do .... While Statements
The Do.. Until and Do...While loop structures are used for repeating operations until some condition
is reached.
The syntax for the Do-Loop is
Do
Statements
Loop Until condition
The statements within the Do-loop will be executed whenever the Until condition is false. As soon
as the Until condition is True the control will move out of the loop.
Example:
intNum = 1
Do
intNum = intNum + 1
Print intNum
Loop Until intNum = 10

26
In the above example intNum will take value 1 for the first time and will be incremented and printed
each time the loop executes. This is repeated until intNum becomes 10. So values from 1 to 9 will
be printed. When the value of intNum becomes 10 the program control will move out of the loop.
That is, when the Until condition is True the control goes out of the loop.
If we replace the Until loop with a While loop, the statements will be executed when the while
condition is true and otherwise the control will exit from the loop.
The while condition checking is done at the top of the loop as given in the following code,
intNum = 1
Do While intNum < 10
Print intNum
intNum = intNum + 1
Loop
Here the statements are executed only if the while condition is true. In the previous loop, the
statements will be executed at least once regardless of the loop checking.

27
While .... Wend Statement
The While .... Wend looping structure is used for performing the looping operations until some initial
condition changes.
Syntax is,
While condition
Statements
Wend
The statements will be executed whenever the condition evaluates to True.
Decisions Making control structures
While programming, you can write instructions for shifting, switching, or otherwise changing the
flow of the program. Generally, after testing some conditions and depending on the results of this
test, different operations can be performed. The decision instructions occur in nearly every program
and are a crucial part of all programming languages.
The decision structures supported by Visual basic are,
If....Then....EndIf Statement
The If - Then statement is used for making a decision in a program.
The syntax of If-Then structure is,
If Condition Then statement EndIf
If the condition is true then the statements after `Then' will be executed, otherwise the statements
will be skipped.
Example,
If intNum1=0 Then
intNum1= intNum1+1
EndIf
In this example if intNum = 0, then the instruction incrementing intNum will be executed, otherwise
the control will go to the statement(s) following the end if statement.

28
Block-If Statement
This structure is used when there are multiple statements to be executed after the checking, hence
named Block-If statement. Syntax is,
If condition1 Then
[statements]
[Else If condition2 Then
[Else if statements]
....
[Else [else statements] ]
End If
If the condition1 is true then the corresponding statements will be executed, otherwise condition2
is checked. If it is true then corresponding statements will be executed. The process will be
repeated like this. The last statement is the End If statement. It is used to denote that end of the
loop.
Example:
If intNum1 > intNum2 then
If intNum1 > intNum3 then
Print "The first number is Greater"
Else Print "The third number is Greater"
Endif
Elseif intNum2 > intNum3 then
Print " The second number is Greater"
Else Print "The third number is Greater"
Endif
In this example, if intNum1 > intNum2 is True, then it is checked whether intNum1 > intNum3.
If True, then intNum1 is greater, otherwise intNum3 is greater.
If intNum1 > intNum2 is not True, then the Elseif part is checked to see whether intNum2 >
intNum3.
If this condition is True, then intNum2 is greater, otherwise intNum3.
These if-then-else statements can be used within the loops like Do-While or For-Next Loops.
Select Case Statement
Select Case structure is often used instead of the nested-If Loop. Select - Case instruction are easier
to write, and decode than complex nested if statements. The "case" that matches the condition is
selected and all instructions within the matching case are executed.
The syntax of Select Case is,
Select Case Variable1
Case value1
Statements
Case value2
Statements
...................
...................
End Select
Example:
intChoice=3
Select Case intChoice
Case 1
answer="wrong"
Case 2
answer="wrong"
29
Case 3
answer="Right"
End Select
In the above example if the value of intChoice is one or two, the answer to a quiz will be marked
wrong, otherwise, if it is 3 the answer will be marked right
A description of events and details of various mouse and key events are given in the next topic.
Event Handling
Events are... well events. They are things that occur within the computer. Things like mouse
movements, clicks, Keyboard things like pressing keys, window actions like opening and closing
windows. Events are used to control when things occur within your program. For example, in a
simple system where there is a button to "press", the clicking of a mouse on the button generates
an event. This event will ultimately run the programming code associated with the button's Click
event. In order to write or modify the event procedure for a particular control, open the code editor
and select that control from the Object ListBox and the appropriate event from the Event ListBox.
Then the corresponding procedure body will be displayed on the code editor. The programming
instructions should be written inside the procedure body.
For example, in the First Visual Basic application for this course, when the user clicks the Command
Button "Print", a message will be displayed on the Label control on the form.
MOUSE EVENTS
The events triggered by mouse activities are the most common events in programming with Visual
Basic.
Click, DblClick: The Click event takes place when the user clicks the left mouse button. The
DblClick event takes place when the user double clicks the left mouse button.
MouseDown, MouseUp: The MouseDown event takes place when the mouse button is pressed
down, and the MouseUp event takes place after it is released.
MouseMove: This event takes place continuously as the mouse is moved over a control.
The order in which mouse events take place is as follows:
1. As the mouse is moved across, the MouseMove event is triggered continuously.
2. When the mouse button is pressed, the MouseDown event takes place.
3. If the user continues to move the mouse around while holding down the mouse, the program
keeps receiving mouse move events.
4. When the mouse button is released, the MouseUp event is triggered.
5. If the left mouse button was held down, the Click event is triggered immediately after the
MouseUp event.
KEYBOARD EVENTS
Keyboard events are generated by keystrokes. Not all controls can accept keyboard input, so they
do not have any keyboard events. Keyboard events are often used to control the movement
through the boxes of an input form, or to do things like smart lookup and more.
KeyDown, KeyUp: The KeyDown event is generated when a key is pressed, and the KeyUp event
is triggered when a key is released.
KeyPress: This is the most commonly used keyboard event. This event is triggered when any key
is pressed. This event is used frequently to write keyboard handlers for text boxes, because this
event takes place before the character pressed is displayed in the text box.
Change: the Change event is triggered by various controls when their contents change. The
Change event is triggered for the Textbox control each time a new character is typed or deleted.
Self Assessment
Click the Tick mark to select an answer.
(1). Byte Variables can hold characters up to,
(a) 255.
(b) 512.
30
(c) 127.
(d) 8.
(e) None of the above.
(2) Dim Statement is used for,
(a) Variable declaration.
(b) Variable initialization.
(c) Looping.
(d) None of the above.
(3) Of the following which is not a Mouse Event
(a) Click.
(b) DblClick.
(c) Mouse Move.
(d) Change.
(e) None of the above.
(4) Which is the right prefix for ComboBox according to coding convention.
(a) Cmb.
(b) cbo.
(c) Combo.
(d) Com
(e) None of the above.
(5) Which one is a determinate loop,
(a) If – Then.
(b) Do-While.
(c) For-Next.
(d) While-Wend.
(e) Do-Until.
(6) Which one is used for decision making,
(a) If –Then.
(b) Do-While.
(c) For-Next.
(d) While – Wend.
(e) Do-Until.
Workshops
1. What are the advantages of using coding conventions?
2. What are the data types in Visual Basic?
3. What are user-defined data types?
4. What is the scope of a variable?
5. Distinguish between determinate and indeterminate loops with example?
6. Distinguish between Do-While and While-Wend?
Exercises
1. Write a program to find greatest of five numbers.
2. Using loops, write a program to print a the sum of all numbers between two input values.
E.G. (2,6) = 2+3+4+5+6

CHAPTER-3
Workshops – Solution

Note: on the course CD in the VBAVU\VBCOdeSample\Chapter3 you will find working


examples similar to the examples shown here.
31
1. What are the advantages of using coding conventions?
The Coding conventions are used so that the code becomes readable and understandable. It
helps for error checking, cross reference etc. In large projects, common naming standards are
essential to reduce the occurrence of bugs, and to make your programming intentions clearer to
others and theirs to you.
The conventions are aimed on the physical structure and appearance of the code. Different
organizations will have different standards. A consistent set of coding conventions can be used
to standardize the structure and coding style of an application.
 Conventions for naming.
 Formats for labeling.
 Conventions for commenting the code.
 Conventions for spacing, formatting, and indenting.
The coding conventions defined should satisfy a minimum set of requirements so that the
programmer becomes free to implement the program's logic and functional flow. Try to write
the code as modules so that it can be more easily understood.
2. What are the data types in Visual Basic?
Visual Basic is having a number of data types. The important data type are given below:

32
a. String
String variable is used to hold characters. String variables can have a variable-length or a fixed
length. Variable length strings and can hold a string of about 2 billion characters and a fixed-
length can hold a string of up to about 65,400 characters.
For example, if you have a Textbox named txtName and a variable named strName, then the
value (text) of the Textbox can be assigned to the variable as
strName= txtName
b. Integer
Integer variables hold small integer values compared to other integer types. The range is
between -32,768 and +32,767.
c. Long Integer
The long integer variable holds integers between -2,147,483,648 and +2,147,483,647. Long
Integer arithmetic is also as fast as integer arithmetic.
d. Double Precision
Double precision variables hold more than 300 digits. These variables are used in scientific
calculations in Visual Basic.
e. Currency
Certain problems arise when using decimal fractions. Currency variables are designed to avoid
these problems. To the left of the decimal point in currency type variables there can be up to 4
digits and to the right 4 digits.
f. Date
Date information can be stored using the Date data type. It can hold date values for any time in
the range from midnight on January 1,100 to midnight on December 31, 9999.
g. Byte
This data type byte can hold integers between 0 and 255. This is also used for handling binary
data in Visual Basic.
h. Boolean
Sometimes you need a variable with only two values, either True or False. To hold these type of
values, use the Boolean data type.
i. Variant
The variant type can hold any type of variables. By declaring a variable of variant type we can
assign any type of data to the variable. If any variable is left undeclared in a program Visual
Basic will treat that particular variable as variant type. Variants are the catch-all and easy to
work with. They are also the slowest variables to use and may affect programs that have speed
concerns.
3. What are user-defined data types?
In a large project there are occasions to create a single variable that records several related
pieces of information. This can be done using user defined data type.
To create a user-defined type the declarations can be placed in the declaration section of a
module. The syntax is:
Private Type MyDataType
For example :
Private Type MyInfo
Name as String
HouseName as String
Salary as currency
End type
4. What is the scope of a variable?
The Scope of the variable means the availability of that variable in a particular procedure. In
some programming languages, a variable declared is available throughout the program. This
33
may create problems where in larger programs when two variables which fundamentally are
supposed to be different, end up with the same name. In Visual Basic this problem is avoided by
isolating variables within the procedure where they are used. If several procedures have a
variable with the same name, each will be treated as different variables in Visual Basic as each
variable within a procedure is "local" to it's respective procedure.
5. Distinguish between determinate and indeterminate loops with example?
Determinate loops are those that repeat a certain lines of code a fixed number of times. For
example the For…Next is having the determinate looping structure.
The indeterminate loops are those which repeating until a predetermined goal is achieved or
until some initial conditions change.
While…Wend and Do…Until are the examples for indeterminate loops.
Exercises – Solution
Exercise-1
Write a program to find greatest of five numbers
Solution:
The requirement is to write an application that can find the greatest of five given numbers. For that
do the steps below:

Step 1:
Create a Standard EXE project and place four Label controls and one Command Button on the form.
Step 2: Set the Name property Caption/Text property
properties as shown
below:

Control
Form frmGreatest Greatest Number
Command Button cmdClick Click Me
Label1 lblDisplay The numbers are :
Label2 lblAnsDisplay The greatest number is:
Label3 lblNumbers (empty)
Label4 LblGreatest (empty)
Step 3:
Declare an array and two integer variables in the General declarations as shown below:
Option Explicit
Dim number() ' declaring array
Dim big As Integer ' variable for keeping biggest number
Dim cnt As Integer ' counter

Step 4:
Then initialize the array variable in the Click event of the Command Button, cmdClick.
'initializing the array
number = Array(17, 11, 27, 10, 6)
big = number(0) ' assign the first array element to the variable
Step 5:
Then write the following code for finding the largest number in the Click event of the Command
Button, cmdClick.
' loop for finding the biggest number
For cnt = 1 To 4
' in each loop the variable is compared with the
' array element and if it is found bigger than
34
' the variable, then, the variable is assigned the
' value of that element
If big < number(cnt) Then
big = number(cnt)
End If
Next cnt
Step 6:
Then write the following code for assigning the values to the labels for displaying with the above
code, in the Click event of cmdClick.
' assign the values to the labels for displaying
lblNumbers = number(0) & ", " & number(1) & ", " _
& number(2) & ", " & number(3) & ", " & number(4)
lblGreatest = big
Step 7:
Then save and run the project.
Sample output is given below.

35
CHAPTER 4
More About Forms
Form objects have an important role in Windows based applications, because Forms are the
Interfaces with which a user interacts while running an application. The appearance and behavior of
forms can be controlled with their properties, events, and methods.
There are two main styles of user interface - the single-document interface (SDI) and the multiple-
document interface (MDI). In addition to these common interface styles, there is a third interface
style named the explorer-style interface.
The MDI interface allows multiple windows to be displayed all within the "container" of a parent
form. Examples of the MDI interface are Microsoft Word and Microsoft Excel.
The SDI interface allows only one window to be opened at a time. WordPad is an example of an SDI.
Setting Form Properties
Setting Form Properties is very important for a Visual Basic Programmer, because it will affect
the physical appearance of the Interface.
The Form's Caption property determines the text that is shown in the form's title bar.
The Icon property sets the icon that is displayed when a form is minimized.
The MaxButton and MinButton properties determine whether the form can be maximized or
minimized.
By changing the BorderStyle property, you can control the resizing behavior of the form. Height and
Width properties determine the initial size of a form.
The Left and Top properties determine the form's location in relation to the upper left-hand corner
of the screen.
The WindowState property can be set to start the form in a maximized, minimized, or normal state.
The Name property sets the name by which you will refer to the form in code.
Common Methods and Events of a Form
Methods are the actions that can be done with a Form Object and Events are the ways that a form
responds to computing activities. The Form has a number of Events and Methods available to you
for controlling its operation.
The Resize event of a form is triggered whenever a form is resized, either by user interaction or
through code. The resize event allows you to perform actions such as moving or resizing controls on
a form when its dimensions have changed.
The Activate event occurs whenever a form becomes the active form; the Deactivate event occurs
when the form becomes inactive and another form or application becomes active. These events are
convenient for initializing or finalizing the form's behavior.
You can "call" or run the Show method to make a form visible. This has the same effect as setting a
form's Visible property to True. The Unload event is triggered when a form is unloaded or closed
The QueryUnload event is triggered when the form first begins to close. This is often used to decide
whether to save changes that have been made within one of the forms of your application.
Splash Screen
A Splash screen is a special form that is displayed when you start an application. Usually
information such as the name of the application, copyright information, and about the company
which developed the application are displayed on the splash screen. This type of screen is used
when a lengthy procedure has to be executed on startup, such as loading a large amount of data
from a database or loading several large bitmaps. When the startup routine is completed, the first
form of the application will be loaded.
To see the sample program, click here.
In the coming topics, various controls are discussed in detail. Next topic is about CommandButtons.

36
Exercise-2

Using loops, write a program to print the sum of all numbers between two input
values.
e.g. 1 and 6 as input will give result as 21, which is 1+2+3+4+5+6.

This problem can be solved using the following steps.


Step 1:
Create a Standard EXE project. Then place three Command Buttons, two Text Boxes and four
Label controls on the form.
Step 2:
Then set the properties of the controls as shown below:
Control Name property Caption/Text property
Form frmSum Sum of Numbers
Command Button1 cmdAdd Add
Command Button2 cmdClear Clear
Command Button3 cmdClose Close
Text Box1 txtFirst (empty)
Text Box2 txtLast (empty)
Label1 lblFirst Enter First Number :
Label2 lblLast Enter Last Number :
Label3 lblRes Result is:
Label4 lblResult (empty)

Step 3:
Then declare the following in the general section:
OptionExplicit
Dim intK As Integer ‘ variable for counting
Dim intSum As Integer ' variable for keeping sum
Step 4:
Then write the following code in the Click event of the cmdAdd button.
Public Sub cmdAdd_Click()
' check for proper inputs
If txtFirst = "" Or txtLast = "" Then
MsgBox "Enter the numbers", , "No Data"
ElseIf Val(txtFirst) > Val(txtLast) Then
MsgBox "First number should be less than last number", , "Invalid Data"
Else
' initializing the values
intK = Val(txtFirst)
intSum = intK
' loop for calculating the sum
Do While intK < Val(txtLast)
intK = intK + 1 ' incrementing the counter
intSum = intSum + intK ' adding the values
Loop
lblResult = intSum ' asssigning the values to the label

37
End If
End Sub
Step 5:
Then write the following code in the Click event of the cmdClear button.
Private Sub cmdClear_Click()
' to clear the textboxes and label
txtFirst = ""
txtLast = ""
lblResult = ""
' set the focus to TextBox txtFirst
txtFirst.SetFocus
End Sub
Step 6:
Then write the following code in the Click event of the cmdClose button.
Private Sub cmdClose_Click()
' unload the form
Unload Me
End Sub

Step 7:
Save and Run the program by putting the correct inputs.
Sample output is shown below.

Example: Print Form Application


This Application will show you how to write a Visual Basic application using Form. See how
the Activate event is used.
Follow the steps below:
1. Start Visual Basic IDE and Select the Standard EXE from the New Project Dialog Box.
2. In the IDE you can see a Form.
3 Make the Property Settings of the Form as given below,
Control Name Caption
Form1 frmPrint Print Form
4. Write the code in the Activate Event of the Form as shown below:
Private Sub Form_Activate()
' Printing the Message on Form activating
Print "Hello World"
End Sub
5. Run the Application by pressing F5 or clicking on the Start button. Run Form of the application
is given below.

38
Command Buttons
Most Windows based applications have Command Buttons. They allow the user to click on them to
perform actions. The easiest way to allow the user to interact with an application is to provide
buttons. When the user clicks a button, it will be seen as it is being pushed and released. The click
event of the button carries out the action according to code written when it is clicked.
For adding Command Buttons to a form, you can either use the dragging method or can double
click the Command Button icon (shown in the Figure) in the ToolBox.

If you don't like the appearance of the command button provided by Visual basic, you can
alternatively create your own Command Buttons by using an image control containing a picture or
image, and using the click event of the image control. You will however loose the animated look as
if the button is being pressed.
Setting Properties and Events

Setting the Properties of a CommandButton is also simple.


To change the text displayed on the CommandButton, use the Caption property. The caption can be
a string of length not more than 255 characters. You can also use a special capability of the caption
property to create access key shortcuts for your CommandButtons by adding an ampersand (&)
before the letter you want to use as the access key. These access keys are shortcuts built into most
Windows applications that allow the user to specify the Alt key and a letter in order to do the
function associated with a button.
You can set a CommandButton to be the default CommandButton. Within a particular form and
when that form is the active one (has focus), there is a default action that will occur if the user
merely hits the return key. By setting the default property of a particular button to true, you are
identifying which button will respond to the carriage return..
You can also specify a default Cancel button. When the Cancel property of a CommandButton is set
to True, it will be activated whenever the user presses the ESC key.
The Click event is the default event of the command button. Whenever the CommandButton is
clicked or otherwise selected, its Value property is set to True and the Click event is triggered. If
Value is False (default), it indicates that the button is not selected at the moment
To see the sample program, Click here.
Label and TextBox controls are discussed in the next topic.

Example - Command Button


This Application will give an idea of how to use buttons. Here, the Form contains a "Click Me" button
and a "Close" button. On clicking the "Click Me" button, a message will be displayed on the Form.
On clicking the "Close" button the Form will be unloaded and the application will be terminated.
To create this application, follow these steps.

39
1. Start Visual Basic and Select the Standard EXE from the New Project Dialog Box.
2. In the IDE you can see a Form.
3. Place two Command Buttons and a Label on the Form by dragging.

4. Make the Property Settings as Shown below:

Control Name Caption


Form1 frmClick Click Button Sample
Label1 lblDisplay (Empty)
Command1 cmdClick Click Me
Command2 cmdClose &Close
5. Write the following code in the Click Event of cmdClick.
Private Sub cmdClick_Click()
' When Clicking the Command Button
' the Label's Caption has to change.
lblDisplay.Caption = "Button Clicked"
End Sub
6. Write the following code in the Click Event of cmdClose.
Private Sub cmdClose_Click()
'Unloading the Form
Unload frmClick
End Sub
7. Run the Application by pressing F5 or by clicking the Start button. The Run form of the
application is given below.

Label and TextBox Controls


Label controls are used for displaying text on the form and TextBox controls are used to enter text.
The user cannot directly change the text displayed on a label control. You can use labels to identify
controls, such as Text Boxes, which do not have their own Caption property. The actual text
displayed in a label is controlled by the Caption property, which can be set at design time in the
Properties window or while the program is running by assigning it a value in code.
TextBox can be used to allow user to enter text. For example, a name or zip code box. TextBoxes
are versatile controls that can be used to get input from the user or to display text. TextBoxes
should not be used to display text that you don't want the user to change.
You can add the Label control to your form by selecting the Label control icon (as shown in the
Figure) from the ToolBox.

You can add the Text Box by selecting the Text Box control icon from the Tool Box

40
Common Properties
When we design a Form, setting the properties of the controls on it is very important, because the
appearance of the form will help your application become used and therefore successful.

For a label, the Caption is generally the first property to set. It sets the text to be displayed on the
form.
In the case of a TextBox,the Text property can be set in three different ways - at design time in the
Property window, at run time by setting it in code, or by input from the user at run time. The
current contents of a TextBox can be retrieved at run time by reading the Text property.
The Alignment property sets the alignment of the text inside the Label and TextBox.
To allow the control to automatically adjust to the size of its contents, set the AutoSize property to
True.
To allow the contents of a text box to wrap down and expand vertically, set the WordWrap property
to True.
If you set the BorderStyle property to 1, the label appears with a border giving it a look similar to a
TextBox Control.
You can also change the appearance of the label by setting the BackColor, BackStyle, ForeColor,
and Font properties.
You can control the insertion point (cusror postion) and selection behavior in the TextBox with the
SelStart, SelLength and SetText properties.
PasswordChar specifies the character displayed in the TextBox when you enter data, use the *
character to allow the user to type in information that you don't want displayed on the screen.
Common Methods and Events
Usually when creating an application, the TextBox is used to enter Text. You can use the Change
method of the TextBox to check the entered data against some rules like dollar amount limits and
so on. The GotFocus and LostFocus methods are invoked when the cursor enters and leaves the
TextBox and can be used to make your forms "smart" where data entered in one place can affect
the form or other text boxes etc.
MsgBox Function
This function is used to display messages while executing a program. It is used to
communicate between the application and the user, where user attention or
special actions are needed. As the programmer, you will select the message, and
the button that you want shown to the user. When the user responds to the
message an integer value will be returned from the MsgBox function. Your program
can then pick-up the returned value as an indication to which button the user
clicked and respond accordingly. The MsgBox function has the following syntax.
Syntax
MsgBox (prompt[, buttons] [, title] [, helpfile, context])
The parameters are,
prompt - The message to be displayed.The maximum length of prompt is approximately 1024
characters, depending on the width of the characters used. Keep your messages short and to the
point, or your users will not read them.
buttons - This is a Numeric expression that specifies the number and type of buttons to display,
the icon style to use, the identity of the default button and how the box should function in regards
to the user being able to control the box, or visa-versa. The default value is 0.
title - It is a String expression displayed in the title bar of the Message box. If you do not specify it,
the application name is placed in the title bar.
helpfile - This is a String expression that identifies the Help file to use to provide context-sensitive
Help for the message box. If helpfile is provided, the context parameter must also be provided.
41
Context - Numeric expression which is the Help context number assigned to the appropriate Help
topic by the author of the help file.
Some of the button argument settings are:
Valu
Constant Description
e
vbOKOnly 0 Display OK button only
vbOKCancel 1 Display OK and Cancel buttons
vbAbortRetryIgnor Display Abort, Retry, and Ignore
2
e buttons
vbYesNoCancel 3 Display Yes, No, and Cancel buttons
The MsgBox function has the following return values based on the user response.
Return Values
Constant Value Description
vbOK 1 OK
vbCancel 2 Cancel
vbAbort 3 Abort
vbRetry 4 Retry
vbIgnore 5 Ignore
vbYes 6 Yes
vbNo 7 No
In the next Topic you can learn about Choice controls, which can be placed on your application to
allow users to choose from different choices.

Example - An Addition Application


This Application will give an idea about how the Text and Label controls work. This Application is a
real time application that can be used for performing basic levels of addition.
To create this application, do the following steps.
1. Start Visual Basic and Select the Standard EXE icon from the New Project Dialog Box.
2. In the IDE you can see a Form.
3. Add two Text Boxes, three Label Boxes and three Command Buttons to the form from the ToolBox.

4 Make the Property Settings as Shown below:

Control Name Caption/Text


Form1 frmAddtion Addition Program
Text1 txtAdd1 (Empty)
Text2 txtAdd2 (Empty)
Label1 lblAdd +
Label2 lblEqual =
Label3 lblRes (Empty)
Command1 &Add cmdAdd
Command2 &Clear cmdClear
Command3 E&xit cmdExit
5. Write the following code in the Click Event of the cmdAdd.
42
Private Sub cmdAdd_Click()
' Display the result of Addition
' in the Label Control
lblRes.Caption = Val(txtAdd1) + Val(txtAdd2)
End Sub
6. Write the following code in the Click Event of the cmdClear.
Private Sub cmdClear_Click()
' Clearing the Text Fields and
txtAdd1.Text = " "
txtAdd2.Text = " "
' Setting the Focus in the first Text Box
txtAdd1.SetFocus
End Sub
7. Write the following code in the Click Event of the cmdExit.
Private Sub cmdExit_Click()
' Ending the Program
End
End Sub
8. Run the application by pressing F5 or clicking the Start button. The Run form of the application is
given below.

Choice Controls
Most applications need to present choices to the users, ranging from a simple yes/no option to
select from a list containing hundreds of possibilities. Microsoft Visual Basic provides the following
Choice controls.
1.
Check boxes - used to select none, one or more items from a set of Choices.
2.
Option buttons - used to choose one item from a set of more than one choice.
3.
ListBox - gives a scrollable list of choices from which the user can choose.
4.
Combo Box - gives a scrollable list of choices along with a text edit field. The user can either
choose from the list or type a choice in the edit field.
CheckBox
A check box indicates whether a particular choice is on or off. The CheckBoxes are used to give
users true/false or yes/no options. , a user can select any number of the CheckBoxes at the same
time, because CheckBoxes work independently of each other. To add a check box on your form
select the following icon from the Tool Box.

Setting Properties of Check Box


The Value property of the CheckBox control indicates whether it is checked, or unchecked. The
value is set to 1 when it is checked. Whenever the user clicks on the CheckBox control, the Click
event is triggered. When the Focus is shifted to a CheckBox control by the user with the keyboard
by using the TAB key and then by pressing the SPACEBAR, the value is set to 1 and the click event
is run or "fired"..
43
Option Button
Option buttons present a set of two or more choices to the user. Unlike check boxes, option buttons
always work as a group. Selecting one option button will immediately clear any other selected
button in the group.
All the option buttons inside any given frame constitute a separate group. When you need to create
a separate group of option buttons, always draw a frame or picture box first, and then place the
option buttons on it. To add an option button to your form, select the icon shown below from the
Tool Box.

To group controls in a frame


1.
Select the Frame Control from the toolbox and draw the frame on the form.
2.
Make sure the frame is selected, and then select the Option button control from the
toolbox and draw the control within the frame.
3. Repeat step 2 for each Additional option button you wish to add to the frame.
Setting Properties and Events for an Option Button
The important event for an Option button is its Click Event. When an Option button is selected, its
Click event is triggered. The Value property of the Option button control indicates whether the
option button is selected or not. When selected, the value is changed to True. Like in command
buttons, you can also use the Caption property to create access key shortcuts for your option
buttons by adding an ampersand (&) before the letter you want to use as the access key.
ListBox
ListBoxes present a list of choices to the user from which the user can select one. If the number of
items exceeds the displayed height of the list box, scrollbars automatically appear on the control.
To add a List box on your form select the following icon from the Tool Box.

Important Properties, Events, Methods and Features of ListBox


The ListBox control allow you to display, edit and update information from most standard types of
databases. The DataList control provides advanced data access features. The DataList control also
supports a different set of properties and methods than the standard ListBox control.
You can add data to the ListBox by using the AddItem Method. Its syntax is,
box.AddItem item [, index]
where box is the Name of the ListBox; item is a String expression which is to be added to the list
and index is a number that specifies where the new item is to be inserted in the list.
You can specify that items are shown in alphabetical order by setting the Sorted property to True
and omitting the index.
You can use the RemoveItem method to delete items from a ListBox. RemoveItem has one
argument; index, which specifies the item to be removed:
box.RemoveItem index
The List property provides access to all items in the list. This property should be treated as an array
in which each item in the list is an element of the array. Each item is stored as a string. To refer an
item in the list, use the following statement
box.List (index)
The Columns property allows you to specify the number of columns in a ListBox.

44
Combo Box
A Combo Box control combines the features of a TextBox and a ListBox. This control allows the user
to select an item either by typing text into the ComboBox, or by selecting it from the list. A
ComboBox is appropriate when there is a list of suggested choices, and a ListBox is appropriate
when you want to limit input to what is on the list. A ComboBox contains an edit field, so choices
that are not present on the list can be typed in this field. To add a combo box on your form select
the following icon from the Tool Box.

There are three ComboBox styles. The style can be set at design time.
Drop-Down ComboBox
This is the default style of ComboBox, in which the user can either enter text directly (as in a
TextBox) or select an item from the list of choices.
Simple ComboBox
The Simple Combo specifies a simple ComboBox in which the list is always displayed. You can draw
the ListBox large enough to display all the entries. A vertical scrollbar will be automatically inserted
when there are more entries. The user can still enter text directly or select from the list.
Drop-Down ListBox
A drop-down ListBox is like a regular ListBox. It displays a list of items from which a user can choose
one. Like ListBoxes the list is not displayed until you click the arrow at the right end of the box. The
key difference between this and a Drop-Down ComboBox is that the user cannot type into the box
and can only select an item from the list.
Important Properties, Events, Methods and Features of a ComboBox
The ComboBox can display, edit and update information from all standard types of databases. The
Data-Bound ComboBox provides more advanced data access features. The Data-Bound ComboBox
control also supports a different set of properties and methods than the standard ComboBox
control. Other Actions such as adding an item and removing an item can also be carried out as
done in the ListBox.

You can include images and pictures on the form of your application using Image and
PictureBox controls. These controls are described in th Example: Choice Controls
Description

This sample program uses the choice controls. The characteristics of each choice controls can be
studied from this program. Start a new project. In the Form place the controls such as Textbox,
OptionButton, CheckBox, Listbox, and ComboBox and set the property of each control as given in
the following table.

Note: There is a similar example on the course CD located at VBAVU\VBCOdesamples\


chapter4\project7
Property Settings
Caption/Text
Control Name Name Property
Property
Form frmChoice Choice Controls
Label1 lblData Enter Any Text
Label2 lblSize Font Size
Label3 lblFonttype Font Type

45
TextBox1 txtData (Empty)
ListBox1 lstFont (Empty)
ComboBox1 cboSize (Empty)
Frame1 fraFont Font
Frame2 fraStyle Style
OptionButton1 optBold Bold
OptionButton2 optItalic Italic
OptionButton3 optBolditalic Bold Italic
Check Box chkStr Strikethrough
Check Box chkUnder Underline
Command1 cmdClose Close
Do the following steps:
1. First place the controls, TextBox, Label, Listbox, OptionButton, Command Button, Frame
Control, CheckBox, ComboBox etc in the form.
2. Set the properties of the controls as shown above in the table.
3. Place three option buttons in the frame, fraFont to select the font styles namely bold, italic,
bold italic.
4. Place the two check boxes in the frame, fraStyle to select the styles of representation
namely strike through and underline.
5. Load the ListBox with the fonts available in the system using the screen object and load the
ComboBox with the font sizes. In the form load event write the code for loading ListBox,
lstFont and ComboBox, cboSize as shown below.
Private Sub Form_Load()
' To load the variable intn with the number of fonts available
intNum = Screen.FontCount
' Loads the listbox,lstFont with the fonts available in the system
For intInc = 1 To intNum
lstFont.AddItem Screen.Fonts(intInc)
Next intInc
' Loads the combobox,cboSize with number of font size
For intInc = 2 To 24 Step 2
cboSize.AddItem intInc
Next intInc
End Sub
6.
In the click event of ListBox write the code for changing the value of the text in the TextBox
with respect to the ListBox value as shown below.

Private Sub Lstfont_Click()


‘To change the font of txtdata as selected from lstfont.
txtData.Font=lstfont.Text
End Sub
7. In the click and change events of the combobox, cbosize write the code given below to
increase the font size of the text as the combo is clicked or changed.

Private Sub cboSize_Change()


46
‘To change the font size of the text in
'txtData whenever ComboBox is clicked.
txtData.FontSize=cboSize.Text
EndSub

Private Sub cboSize_Click()


‘To change the font size of the text in txtdata
'whenever ComboBox’s value changes.
txtData.FontSize=cboSize.Text
End Sub
8. To select the font style write the code in the click event and lostfocus events as shown
below,

Private Sub OptItalic_Click()


‘To change the font style.
txtData.FontBold=False
txtData.FontItalic=True
End Sub

Private Sub OptItalic_LostFocus()


‘To change the style from Italic.
txtData.FontItalic=False
End Sub

Private Sub OptBold_Click()


'To change the style to bold.
txtData.FontItalic=False
txtData.FontBold=True
End Sub

Private Sub OptBold_LostFocus()


‘To change the Italic font type.
txtData.FontItalic=False
End Sub

Private Sub OptBolditalic_Click()


‘To change the style to bolditalic.
txtData.FontBold=True
txtData.FontItalic=True
End Sub
9. To give the pattern of strikethrough and underline write the code in the click event of the
check boxes.
Private Sub chkStr_Click()
‘To check the value of CheckBox,chkstr
'and set according to it.
If chkStr=CheckedThen
txtData.Font.Strikethrough=True
Else
txtData.Font.Strikethrough=False
EndIf
47
End Sub

Private Sub chkUnder_Click()


‘To check the value of CheckBox,chkStr and set according to it.
If chkUnder=Checked Then
txtData.Font.Underline=True
Else
txtData.Font.Underline=False
EndIf
End Sub
10. The code for Close button to terminate the application is,
Private Sub cmdClose_Click()
'To terminate the program
End
End Sub
The sample output is,

Image and PictureBox Controls


A windows application should have a good-looking user interface because it is the only thing a user
sees while running an application. This is created by adding various controls to your Form. We can
make this form attractive by adding pictures and images to it. Four controls are present in the
Visual Basic Toolbox with which you can easily work with graphics. They are the PictureBox control,
Image control, Shape control and Line control. Of these, Image, Shape and Line controls are
referred to as light weight controls because they use less memory in the computer they are running
on.
PictureBox Control
The PictureBox control is a blank canvas and can be used to display a picture on the form. Set the
picture property of the PictureBox control with the file name of the picture you want to display.
LoadPicture function can be used for displaying or replacing a picture at run time by giving the path
of the picture file. The AutoSize property of the picture box can be set to resize it automatically to
match the dimensions of its contents. It can be used as a container for other controls and thus can
be used as a toolbar or status bar. Using the Print method, text can be printed on PictureBox
control much like common graphics programs work with text. Using the PaintPicture method images
can be moved and changed rapidly in the picture box creating animated effects.
Lightweight Graphical Controls
The image, shape and line controls are considered lightweight controls. Compared to picture box
control they require less system resources and they do not support all properties, methods and
events supported by the PictureBox.
An image control can be used only for displaying pictures. The Stretch property can be set to resize
it to the size of the picture. It cannot be used as a container. An image control can be used as a
replacement for a command button by using the click event. The BorderStyle property is used to
set the appearance of its border.
48
Shape and Line controls can be used for drawing various graphical constructs. These controls have
no events and therefore can be used only for decorative purposes. You can draw rectangles,
squares or circles by setting the Shape property of the shape control. The shape control have
properties like BorderColor, FillColor, BorderStyle, BorderWidth, FillStyle, and DrawMode. The line
control is used for drawing lines.

Other than the controls we have discussed till now, there are some special controls like the Data
Access controls, the Timer, etc. They are discussed in the next topic.
Example: Image Control
This is a sample application for using an image control in Visual Basic. In this application, the size of
the image in the Image control can be changed when a CommandButton is clicked. To do the
apllication, follow the steps given below.
Note this example is on the course CD in the directory VBAVU\VBCodesamples\Chapter4\
project8
1. First choose Programs/Visual Basic from the Start menu.
2. Start a new project for this application by selecting Standard EXE.
3. Place the controls needed in the Visual Basic form with following property settings.

Control Name Name Caption


Form frmPicture Image Control
Command Button1 cmdClick Click
Command Button2 cmdClose Close
Image1 imgExp (Empty)
4. Set the Stretch property of the Image control to true. Then the image control will adjust to the
size of the image which is attached to it. The picture property of the Image control is set with the
filename of the bitmap.
5. In the click event of the Command Button cmdClick, write the code for maximizing and
minimizing the image.
Private Sub cmdClick_Click()
Static intSts As Integer
If intSts = 0 Then
'To decrese the size of image by increasing top,left
' and decreasing height and width.
imgExp.Height = imgExp.Height - 1000
imgExp.Width = imgExp.Width - 1000
imgExp.Left = imgExp.Left + 500
imgExp.Top = imgExp.Top + 350
intSts = 1
Else
‘To increse the size of image by decreasing top,left
' and increasing height and width.
imgExp.Height = imgExp.Height + 1000
imgExp.Width = imgExp.Width + 1000
imgExp.Left = imgExp.Left - 500
imgExp.Top = imgExp.Top - 350
intSts = 0
End If
End Sub
6. The code for Close button to terminate the application is,

49
Private Sub cmdClose_Click()
'To terminate the program
End
End Sub
The Run Forms of the application is as shown below:

Go to Details Of Image and Picture Controls

Miscellaneous Controls
Visual Basic toolbox contains many other controls that can be used for specific purposes like
working with large amounts of data in an external database or accessing the Windows file system.
ActiveX controls can also be used in a Visual Basic application. In this topic, controls like the data
access control, the file system control, the timer control, the OLE container control and the common
dialog are discussed.
Data Access Controls
Large centralized databases are used in all types of organizations to store information. Since the
amount of data is increasing day-by-day, new technologies and software are being developed to
retrieve data from these databases. Several data access controls are provided with Visual Basic
greatly simplifying your programming job in regards to databases. Using these tools, you can
access database systems like Microsoft Access and SQL Server. The popular controls you can use
with Visual Basic are ADO data control, DBList control, DBCombo control, DBGrid control and
MSFlexGrid control.
To connect with a database, you can use the data control. It acts as an intermediary for the other
controls in your form allowing communications with a database. You can use DBList control with
data control to display a list of data from a field in a database. DBCombo is also like DBList, but it
has an editable Text field. To get many rows of data from a database, you can use DBGrid control.
It displays data in a grid-like table where you can edit the data from the database directly. To get
multiple views of data at run time, you can use MSFlexGrid. It allows the rearranging of rows and
columns to give different views of the data.
File System Controls
To include file-handling capabilities in your application you can use controls like DriveListBox
control, DirListBox control and FileListBox control. They can be used together to provide a view of
drives, directories and files.
50
The DriveListBox control is like a combo box where the drop down list contains a list of disk drives.
The DirListBox and FileListBox are similar to a ListBox control. The DirListBox can be used for
displaying a list of directories which are within the drive selected from the associated DriveListBox.
The FileListBox control can be used to list the files in a selected directory.
Timer Control
If you want code in your application to continuously be repeated at regular intervals without user
interaction, you can use the timer control. It can also be used for making some code work as a
background process. Set the interval property of the Timer to execute code at regular intervals. The
code you wish to run should be in the timer event.
Properties And Events
The timer has only six properties. The Enabled property can be set to true to allow the timer to run
as soon as the form loads. Setting this property to false will cancel the timer's functioning. The
Interval property specifies the length of time in milliseconds between running of the timer event
within the control. The Tag property can be set to identify the Timer control. The Top and Left
properties sets and reports the timer controls position on the form.
The Timer has only one event named "Timer". It occurs every time the interval property has
elapsed. In this event is where you write code you wish to run after each interval. The frequency of
the interval is stored in the Interval property, which specifies the interval between Timer events in
milliseconds (1/1000 of seconds). Whenever the Enabled property is set to True and the Interval
property is greater than 0, the Timer event waits for the period specified in the Interval property
and fires the timer event.

OLE Container Controls


The OLE container control is an easy way to add capabilities like linking and embedding to your
application. Through the OLE container control, you can provide access to the functionality of any
OLE-enabled application such as Microsoft Excel and Word. Document centered applications can be
developed with the help of OLE container controls. Also you can add objects from other applications
to a Visual Basic application using OLE container control. Using this control you can create a
placeholder for an object in your application and display objects as icons. It also provides backward
compatibility with an application containing OLE container controls.
The CommonDialog Control
The CommonDialog control is a very helpful control in Visual Basic applications. If you add this
control in your application it will appear as an icon. By clicking it you can activate standard dialog
boxes for operations such as opening and saving files, setting printer options and selecting colors
and fonts. It can also be used to display help by running the Windows Help engine.
The methods of the CommonDialog control for displaying various dialogs boxes are
1. ShowOpen - used to show an "Open" Dialog Box
2. ShowSave - used to show a "Save As" Dialog Box
3. ShowColor - used to show a "Color" Dialog Box
4. ShowFont - used to show a "Font" Dialog Box
5. ShowPrinter - used to show a "Print Options" Dialog Box
6. ShowHelp - used to invoke the Windows Help Engine.
The CommonDialog control provides context sensitive help on the interface of the dialog boxes. It
can be viewed by clicking the What's This Help Button in the title bar and then selecting the item
for which you want more information.
If CommonDialog control is not present in the ToolBox, you can add it by slightly reconfiguring
Visual Basic using the Components dialog box in the Project menu.

Now you are familiar with most of the controls in Visual Basic. In the next topic you can learn about
focus and tab order.
51
Example: Timer
This application is an example for using Timer control. Here an animation program is done. The
Timer event will be repeated in each interval. If the interval is less, the execution becomes faster.
For creating this application, follow the steps given below.
1. First choose Programs/Visual Basic from the Start menu.
2. Start a new project for this application by choosing Standard EXE icon.

3. Place the controls needed in the Visual Basic form with following property settings.

4. Set the properties of Timer Control, Form and CommandButton as follows:


For Timer
Name : tmrAnim
Interval : 300
For CommandButton
Name : cmdClose
Caption : Close
For Form
Name : frmTimer
Caption : Miscellaneous Controls-Timer
5.Settings for Image controls are given below:

Control Name Name Property


Image1 imgButr1
Image2 imgButr2
Image3 imgButr3
Image4 imgPer1
Image5 imgPer2
Image6 imgper3
6. For animating the image controls a user procedure, named Animate, is written. To create a user
procedure go to the tools menu and select Add Procedure. Then a dialog box appears. Give a name
for the procedure, select the procedure type as sub and click OK. Then write the code given below.
Public Sub Animate()
Static intCnt As Integer
varSts =intCnt Mod 2
If varSts = 0 Then
‘To assign of imgButr1 to imgButr3
imgButr3.Picture = imgButr1.Picture
‘To move image.
imgButr3.Move imgButr3.Left + 100, imgButr3.Top - 100
Else
imgButr3.Picture = imgButr2.Picture
imgButr3.Move imgButr3.Left + 100, imgButr3.Top - 100
End If
intCnt = intCnt + 1
End Sub
7.In the Timer event, write the following code. The user procedure anim is called in this event in
each interval.

52
Private Sub tmrAnim_Timer()
Call Anim
‘To assign imgPer3 with the other image.
If imgPer3 = imgPer1 Then
imgPer3 = imgPer2
ElseIf imgPer3 = imgPer2 Then
imgPer3 = imgPer1
End If
End Sub
The code for Stop button to terminate the application is,
Private Sub cmdClose_Click()
'To terminate the program
End
End Sub
The output is shown below:

Go to the topic, Miscellaneous Controls.


Example: Common Dialog Box
This Visual Basic application gives an idea of using the Common Dialog Box. In this Application,
when you press the Change Color Command Button, it will give the Window's Color Palette from
which you can select a Color. It will also show the Windows Common Dialog Box showing Fonts from
which you can select the Font.
Step 1:
Start a Standard EXE Visual Basic application.
Step 2:
Place a Common Dialog control from the Components Dialog box.
Step 3:
Place a Rich Text Box, a Label Control and three Command Buttons.
Step 4:

Set the Properties as given below:

Control Name Caption

Form frmCldg Common Dialog


Common
dlgStyle (Empty)
Dialog

Label1 lblEnter Enter TheText :

Rich Text Box txtEnter (Empty)

Command cmdColor Change Color

53
Button1
Command
cmdFont Change Font
Button2
Command
cmdExit Exit
Button3
Step 5:
Write the following code on the Click Event of the cmdColor Command Button.
Private Sub cmdColor_Click()
'For Showing the Color Palette
dlgStyle.ShowColor
'For Changing the Selected Text
'into the Color Palette's Color
txtEnter.SelColor = dlgStyle.Color
End Sub
Step 6:
Write the following code on the Click Event of the cmdFont Command Button
Private Sub cmdFont_Click()
'For showing the Font Dialog
dlgStyle.ShowFont
'For Changing the Font
txtEnter.SelFontName = dlgStyle.FontName
'For changing the Font Size
txtEnter.SelFontSize = dlgStyle.FontSize
End Sub
Step 7:
Write the following code on the Click Event of the cmdFont Command Button
Private Sub cmdExit_Click()
'Ending the Application
End
End Sub
Step 8:
Run the application. In the Running mode select the Text and click the Change Color button. Then
the color Palette will appear. Select the Color you want to set. Then the color of the selected Text
will change. The Font can be changed by clicking the Change Font button. The Run form of
Common Dialog application is shown below.

54
Go to Miscellaneous Controls
Focus and Tab Order
Focus
As a user works through an application, they normally move from screen to screen, and within a
screen from control to control. The currently active control is known as the control with "focus".
In a form only the object having Focus can accept user inputs through the keyboard and mouse.
Only the object having focus will be active. Almost all controls in Visual basic can receive focus
except the frame, label, line, shape, timer, image, and a few others. Also, controls not visible on the
screen and disabled controls cannot and do not receive focus.
Event Description
The GotFocus event of a control occurs when the object first receives focus. When an object loses
LostFocus event can be used for verification and
focus the Lostfocus event occurs. The
validation of changes made to data.
You can give focus to an object either by selecting the object at run time or using an object's access
key (if you've defined it) to select the object at run time. You can set focus to a particular object
programmatically by using the SetFocus method of the desired object.
You can make an Object receive focus by setting its Enabled and Visible properties to True. If the
Enabled property is set to true, then the object can respond to keyboard or mouse events. You can
make a control appear and disappear by setting it's Visible property to in either design mode or at
run time.
Tab Order

In a form, you can move to a particular object by clicking on it, or you can change the focus from
one control to another by pressing the TAB key. The order in which you can move is determined by
the Tab Order property of each control. The tab order is the same as the order in which the controls
are placed on the form. Each form has its own tab order. You can set the tab order of all controls on
a form to insure the user moves through the form in a particular order.
You can set the TabIndex property of a control, to change its tab order. The TabIndex property
determines the position of the control in the tab order. The TabIndex value of the first control
placed on the form will be 0, that of second will be 1, and so on. Since the numbering starts from 0,
the highest TabIndex will be one less than the number of controls in the tab order. When the tab

55
order of a control is changed the tab order positions of the other controls will be automatically
adjusted .
Controls that cannot receive focus, disabled and invisible controls either do not have or ignore the
TabIndex property. You can remove a control from the tab order by setting its TabStop property to
False. Only the selected button in an Option button group has the TabStop property true while
others have their TabStop property set to False.
A description of menu controls is given in the next topic.
Menus
Menus can be used as a convenient way to group user commands in your application for easy
access. Most modern applications have menus. You can use Menus if you want your application to
provide a set of commands to users.
If you include menus in the form, they will appear just below the title bar. You can add one or more
Menu categories like file, edit, help etc. to it. By clicking a one of the Menu choices, a Menu
containing a list of corresponding muen choices drops down. Each Menu item corresponds to a
Menu control defined in the Menu Editor. Menu items defined in a menu should be grouped
according to some criteria like the function of the controls so that user can easily access them.
A Menu control has properties that define its appearance and behavior. It also has a Caption
property, Enabled property, Visible property and Checked property. You can set these properties at
design time or at run time. Menu controls have only one event, the Click event. This event is
invoked when the Menu control is selected with the mouse or keyboard.
Using the Menu Editor
With the help of Menu Editor, you can create new Menus and Menubars. Also you can add or
replace commands to an existing Menu and change or delete existing Menus and Menubars. It is
very easy to work with Menu Editor. You can change the properties of a menu by using either the
Menu Editor or the properties window. To display the Menu Editor, choose Menu Editor from the
Tools menu in Visual Basic IDE.
Menu Naming Convention
To make your code more readable and easier to maintain, it's a good idea to follow established naming conventions when setting the Name property in the Menu Editor. While naming menu controls an additional

prefix for each level of nesting should be added to the label mnu. The final menu caption is added at the end of this string. This convention helps to identify the menu items to which each menu control is attached.

Some examples are given below.

Menu caption Menu handler name


Open mnuOpen
Save mnuSave
Exit mnuExit
SubMenu
If a menubar is full or if a particular menu control is not always used, then you can create a
submenu. It branches from another menu and can include submenu items, separator bars and
submenu titles.
To create a SubMenu first create the Menu item that you want to be the submenu title. Next, create
the items for the new subMenu, and indent them by clicking the right arrow button in the Menu
Editor. Each indent level will be preceded by four dots (....). You can click the left arrow button to
remove one level of indentation.
Menu Control Array
You can create a set of Menu items within the same Menu that share the same name and event
procedures using a feature known as a Menu Control Array. A menu control array can be used to
create a new Menu item at runtime. Since common blocks of code can be used for all Menu items
within a control array, coding can be considerably reduced. The index value given in the Index
property box of the Menu Editor can be used to identify a Menu Control Array element. Elements of

56
a Menu control array must have the same level of indentation. You can include separator bars that
appear on the Menu to group items in a menu.
Pop-up Menus
A Pop-up Menu is a floating Menu displayed over a form independent of the Menubar. This Menu is
opened by right-clicking on the form and it will be opened at the location of the mouse pointer
when you clicked. These menus are also called Context Menus. Pop-up Menus can be used to
provide an efficient method for accessing common and contextual commands. You can use the
PopupMenu method to display a Pop-up Menu.

Menus in MDI Application


In an MDI application you can create separate menus for each child form. The menu of child forms
will be displayed on the MDI form only, rather than on the child forms. The menu of the parent MDI
form will be replaced by a child's menus when the child form which gets the focus. The MDI form's
Menu will be visible when there are no child forms visible or if the child with the focus does not
have a Menu. MDI applications usually have several sets of Menus.
Most MDI applications include a Window Menu that displays the captions of all child forms which are
currently opened within the application. In addition it can include child window display formatting
commands to manipulate the child windows such as Cascade, Tile and Arrange. By setting the
WindowList property for a Menu control to True, it can be used to display the list of open child
forms.
Go to the next topic to see the sample project for this chapter.
Sample Project - Ticket Printing Application
The ticket printing application describes how to use Multiple Document Interface and common
controls. This application consists of one MDI Form and two child Forms.The first child Form is for
entering data and is called the Entry form. The data entered in the Entry Form is displayed by the
second child form known as the Ticket form.This Project will also give you an idea about Menu
Design.
Note: There is a working sample of this project located on the course CD at VBAVU\
VBCodesamples\Chapter4\TicketProject
Let's Start the Project:
Planning and Designing
The main aim of the Project is to take the data entered through the Entry Form and display it in the
Ticket form. This is a simple application that has little real-world applications and should be
considered a training exercise for your learning.
Starting the Project
Step1:
Start the application as a Standard Exe.
Step2:
Add an MDI Form from the Project menu.
Step 3:
Add 2 regular forms

Form Layout
In addition to one MDI form, two child forms are needed for this project. One is the Entry Form
which collects the details from the user and the other is the Ticket Form where the details have to
be displayed.
The Design of the Entry Form and the ticket form are given later:

Property Settings
The Property Settings for MDI Form are as follows:
57
Control Property Setting
MDI Form Name mdiFrmControls
MDI Form Caption Ticket Printing
Select the Menu Editor and design a menu named Enter with New and Exit menu items. Name the
new menu item as mnuNew and the Exit menu item as mnuExit. Again design another Menu named
Display with menu items Ticket and New Entry. Set their names as mnuTicket and mnuNewEntry.
Place two Text Boxes, two Labels, a Combo Box, a Set of Option Buttons, a Set of Check Boxes and
two Command Buttons on the Entry form.
Set the properties of these controls as given below:
Control Name Caption
Form frmEnter New Entry
TextBox1 txtName (Empty)
TextBox2 txtSs (Empty)
Label1 lblEnter Enter Your Name
Enter Social Security
Label2 lblSs
No
Frame1 fraSex Sex
Educational
Frame2 fraEducation
Qualifications
Option1 optMale Male
Option2 optFemale Female
Check Box1 chkEdu1 Matriculation
Check Box2 chkEdu2 Graduation
Check Box3 chkEdu3 PostGraduation
Command Btn1 cmdTicket Ticket
Command Btn2 cmdExit E&xit
Set the Properties of the Ticket Form as below:
In this Form place 8 Labels for displaying the information collected from the Entry Form.
Control Name Caption
Form frmTicket Ticket
Label1 lblName Name
Label2 lblNameDisp (Empty)
Label3 lblSs Social Security No
Label4 lblSsNo (Empty)
Educational
Label5 lblEducation
Qualification
Label6 lblEdu (Empty)
Label7 lblSex Sex
Label8 lblSexDisp (Empty)
Coding
58
In the MDI Form add the code on the Clicking events of the menu items like below:
Private Sub mnuExit_Click()
'Ending the Application
End
End Sub
Private Sub mnuNew_Click()
'Display the Entry Form
frmEnter.Show
End Sub
Private Sub mnuNewEntry_Click()
'Unloading the Ticket Running
Unload frmTicket
'Display the Entry Form
frmEnter.Show
End Sub
Private Sub mnuTicket_Click()
'Display the Ticket Form
frmTicket.Show
End Sub
In the Entry Form add the following code on the Command Buttons click menu.
Private Sub cmdExit_Click()
'Close the form
Unload Me
End Sub
Private Sub cmdTicket_Click()
'Show the Ticket Form
frmTicket.Show
End Sub
In the Ticket Form add the following code in the Form Activate Window.
Private Sub Form_Activate()
' Display the Name
lblName = frmEnter.txtName
' Display the Social Security No
lblSsNo = frmEnter.txtSs
' Display the Sex if Male option is selected
If frmEnter.optMale = True Then
lblSexDisp.Caption = "Male"
End If
' Display the Sex if Female option is selected
If frmEnter.optFemale = True Then
lblSexDisp.Caption = "Female"
End If
' Display Educational Qualifications
If frmEnter.chkEdu1.Value = 1 Then
lblEdu.Caption = "Matriculation"
End If
If frmEnter.chkEdu2.Value = 1 Then
lblEdu.Caption = "Graduate"
End If
If frmEnter.chkEdu3.Value = 1 Then
59
lblEdu.Caption = "PostGraduate"
End If
The Run Forms of the application is given below.

Self Assessment
Click the Tick mark to select an answer.
(1) Which is not a Form event,
60
(a) Resize.
(b) Click.
(c) DropDown.
(d) DragDrop.
(e) Activate.
(2) Which is the default event of the CommandButton.
(a) GotFocus.

(b) KeyPress.

(c) Click.

(d) DblClick.

(e) Caption.
(3) SetFocus is used for
(a) Setting the focus on a control.

(b) Clearing a TextBox.

(c) Making a control invisible.

(d) Enabling a control.

(e) None of the above.

(4) Which control is used for choosing Boolean values


(a) ListBox.

(b) ComboBox.

(c) OptionButton

(d) DbListBox.
(5) How many events a Timer has,
(a) No events.

(b) One.

(c) Two.

(d) Three.

(e) Four.

Workshops
1. What is a splash form?
2. What are the Choice controls in Visual Basic?
3. Distinguish between PictureBox and Image control?
4. Distinguish between ListBox and ComboBox?
61
Exercises
Create a calculator application for adding, subtracting, multiplying and dividing
numbers. Chapter - 4
Workshops – Solution

1. What is a splash form?


The Splash Screen is a special form that is displayed when you start an application. Usually
information such as the name of the application, copyright information, and about the company,
which developed the application are displayed on the splash screen. This type of screen is used
when a lengthy procedure has to be executed on startup, such as loading a large amount of
data from a database or loading several large bitmaps. When the startup routine is completed,
the first form of the application will be loaded.
2. What are the Choice controls in Visual Basic?
Microsoft Visual Basic provides the following Choice controls.
I Check boxes - used to select none, one or more items from a set of Choices.
II. Option buttons - used to choose one item from a set of more than one choice.
III. ListBox - gives a scrollable list of choices from which the user can choose.
IV Combo Box - gives a scrollable list of choices along with a text edit field. The user can
either choose from the list or type a choice in the edit field.
3. Distinguish between Picture Box and Image control?
Both are used for displaying the pictures or images. The image control is a lightweight control
comparing with the picture control. Because the image control needs only less system
resources comparing with the picture box.
The picture box can be used as a container for other controls. That is the picture box can
contain other controls. But the image control can’t be used as a container.
4. Distinguish between a List Box and a Combo Box?
The List box control allows you to display, edit and update information while the combo box
combines the properties of a text box and a list box.
The Combo Box is appropriate when there is a list of suggested choices, and a List Box is
appropriate when you want to limit input to what is on the list.

62
Exercise - Solution
Create a calculator application for adding, subtracting, multiplying and dividing numbers.
Note: There is a working example of this exercise, located on the course CD at VBAVU\
VBCodesamples\Calculatorproject1 In that example we hid the two labels, lblNum and
lblSign behind the number button array.
The Calculator application is a real time application that can be used to perform the operations
such as addition, subtraction, multiplication and division.
Step 1:
Create a Standard EXE project.
Step 2:
Create a control array of 10 Command Buttons for representing the digits and another array of 4
Command Buttons for representing the operators or signs.
Step 3:
In addition to these two arrays of Command Buttons, place a Text Box, two Label boxes and two
Command Buttons on the form. The Label controls are for using as temporary storage of number
and sign.
Step 4:
Set the properties of the controls as shown below:
Control Name Property Caption/ Text
Form frmCalculator Calculator
Text Box txtAns (empty)
Command Button array cmdDigit(0 to 9) 0 to 9
Command Button oper1 cmdOper(0) +
Command Button oper2 cmdOper(1) -
Command Button oper3 cmdOper(2) x
Command Button oper4 cmdOper(3) /
Command Button 3 cmdEqual =
Command Button 4 cmdDot .
Label1 lblNum (empty)
Label2 LblSign (empty)

Step 5:
Give the following code in the General declarations. Here you have to declare a Boolean variable
to check whether the entering number is the first operand.
Option Explicit
' boolean variable or flag to
' determine whether you are entering
' the first number in the calculator
Dim bFlag As Boolean
Step 6:
Then write the following code in the Load event of the form.
Private Sub Form_Load()
' Initialize the temporary storage labels.
lblNum = "p"
lblSign = "p"
' Set the content of txtAns as "0"
txtAns = "0"
End Sub
Step 7:
63
Then write the following code in the Click event of cmdDigit button.

Private Sub cmdDigit_Click(Index As Integer)


' Clear txtAns if the bFlag is true
If bFlag Then
txtAns = ""
bFlag = False
End If
' if the value on txtAns is 0, then the index
' of the button pressed will be placed on txtAns,
' otherwise the index will be concatenated with
' the index of the button pressed
If txtAns = "0" Then
txtAns = Index
Else
txtAns = txtAns & Index
End If
End Sub
Step 8:
Then write the code in the Click event of the cmdEqual button.
Private Sub cmdEqual_Click()
bFlag = False
' According to the content of lblSign
' calculate the values
Select Case Trim(lblSign)
Case 0
txtAns = Val(lblNum) + Val(txtAns)
Case 1
txtAns = Val(lblNum) - Val(txtAns)
Case 2
txtAns = Val(lblNum) * Val(txtAns)
Case 3
' Check whether divisor is zero. If so
' display the error message.
If txtAns = "0" Then
txtAns = "Error"
Else
txtAns = Val(lblNum) / Val(txtAns)
End If
End Select
' Reset the temporary storage labels
lblNum = "p"
lblSign = "p"
bFlag = True
End Sub
Step 9:
Then write the code for the Click event of the cmdDot.
Private Sub cmdDot_Click()
' Clear txtAns if the bFlag is true
If bFlag Then
txtAns = ""
bFlag = False
End If

64
' If the value of txtAns is 0 then
' assign it as "0." when dot is clicked
If Len(txtAns) = 0 Then
txtAns = "0."
Else
' Check the content of txtAns, whether it
' contains a dot. If not add a dot to it.
If InStr(txtAns, ".") = 0 Then
txtAns = txtAns & "."
End If
End If
End Sub

Step 10:
The next step is to write the code in the Click event of the cmdOper button.
Private Sub cmdOper_Click(Index As Integer)
If lblNum = "p" Then
lblNum = txtAns
lblSign = Index
Else
' According to the content of lblSign
' calculate the values
Select Case Trim(lblSign)
Case 0
lblNum = Val(lblNum) + Val(txtAns)
Case 1
lblNum = Val(lblNum) - Val(txtAns)
Case 2
lblNum = Val(lblNum) * Val(txtAns)
Case 3
' Check whether divisor is zero. If so
' display the error message.
If txtAns = "0" Then
txtAns = "Error"
' Reset the temporary storage labels
lblNum = "p"
lblSign = "p"
bFlag = True
Exit Sub
Else
lblNum = Val(lblNum) / Val(txtAns)
End If
End Select
txtAns = lblNum
lblSign = Index
End If
bFlag = True
End Sub
Step 11:
65
Save the code then run to get the real calculator for your purposes.
The sample output is shown below.

66
CHAPTER 5
Introduction to COM/DCOM
The term COM stands for Component Object Model (COM). The model is based on the concept of
reusable programming. COM is a software architecture that allows programmers to create reusable
components. COM allows the programmers to create reusable software components that are usable
by programs written in other programming languages and are available on any platforms that
supports the COM model.
First of all, you want to understand the meaning of the term Component. Before the component-
based technology was introduced, applications were contained within a binary file. The main
disadvantage of the old way was the application's operation cannot be changed until the changes
are recompiled and the software is redistributed. This approach is slow and makes development of
applications with many programmers difficult to coordinate and manage.
The solution for this slow, complex development is to break an application into separate
replaceable pieces or modules. With this new modular design, the application can be modified by
replacing the old pieces with the new one without disturbing the rest of the application. Another
important factor is that the replaceable pieces are language independent. Thus several teams,
which are building components for a single system can choose there own programming language
and work independently.
Thus a component is a binary bundle of code that is compiled, linked and ready to use. In short it is
like a mini-application. It can be developed by using languages such as C++, Visual Basic, Java,
Delphi and even COBOL. So when several teams are building components for a single application,
each team can choose a programming language that matches its technical requirements, team
expertise and productivity.
So, The Component Object Model (COM) is a model or specification which specifies how to build
language independent, binary, upgradeable components for efficient, more easily modifiable
applications.
The term DCOM stands for Distributed Component Object Model (DCOM). It takes the COM model
and expands it's function to other, connected computers. That is, it assumes the computer needing
to run an application using an object (Client) and another computer (server) are connected and the
server is able to provide computing to the client through the DCOM specification as if the DCOM
object was part of the client. DCOM is a specification that provides the infrastructure for remote
object creation and activation. DCOM also ensures security over these distributed objects.
Principles of COM and DCOM are discussed in the next topic.
Principles of COM/DCOM
Before going to study the principles of COM, you must understand the meaning of some key terms
like Objects, Classes and Clients.
Objects, Classes and Clients
In an object oriented approach to programming, any problem that is to be solved is divided into
Objects. The set of data and the code to manipulate that data is known as a Class. A class is the
plan for how to process information about a particular logically grouped data and actions on that
data. The term Client may be defined as a program or a component which uses another
component. The communication between the Client and Component is carried out through an
Interface.
In an Object based system, the communication between the client and object takes place through
a set of publicly accessible properties (values) or methods (actions). So the method names and
property names in the Interface is important to the client. The important benefit of using the
classes is that they allow the code to be used by different applications. That is once a class has
been written, you can use it wherever necessary eliminating redundancy. It also helps with the task
of maintaining code. Perhaps the most important thing in object oriented method is the designing
67
of public interface. Once the interface to the class is designed and applications have been written
to use the interface, changes to the interface becomes more difficult and causes rippling changes
through the application. Changes to existing methods and properties become troublesome, but
additions are somewhat easier to handle.
Virtual Function Table (vtable)
Another important concept in the Component Object Model is the Virtual Function Table (vtable). It
defines an array that points into the virtual functions of a particular object. It defines a standard
way to call functions of any languages through the use of "pointers". Thus any language that can
call functions through pointers can be used to use these type of components. These components
can interoperate with other components written to the same standard.
The Diagram for a Virtual Table is given below:

Interfaces
The basic idea behind COM technology is that it uses interface-based programming. The interface is
the instructions through which the client communicates with a component. It has strict rules
involving the kind of data needed (type) for communication between software components. In this
style of programming the Interface is separate from the actual code behind it. It is based on black-
box reuse in which the implementation details of a class are never revealed to the client and all the
client needs to understand is how to set and read properties and call methods.
Figure of an Interface

The COM interfaces are identified by the Globally Unique Identifiers (GUIDs), which is a 128-bit
unique integer for each Interface. The function named CoCreateGUID is used to generate new
GUIDs. This function can create the GUID from the computer's network card and system clock, to
ensure that the GUID to be unique across the world. The Visual Basic IDE is capable of creating the
GUID whenever needed.
The GUID which is associated with an interface is known as an Interface ID (IID) and the GUID which
is associated with a class is called class ID (CLSID).
The Type Library helps the client application to discover the interface it supports at run time. The
process of loading and binding an object into an application from a COM library is called activation.
The part of the computer that supports activation is called the Service Control Manager (SCM)
which is a system wide service that resides in the file RPCSS.EXE.
68
COM supports server-side activation using the technique FACTORY PATTERN, in which the code that
creates the object is contained in the same binary file. This technique allows the programmer of a
class to revise their code without worrying about the client dependencies. The class factory is a
software agent that creates copies or instances of a class associated with a specific CLSID.
IUnknown Interface
Every COM interfaces is derived from the IUnknown interface. IUnknown is the root of every COM
component as sub-component. The IUnknown interface has mainly three functions. They are
QueryInterface, AddRef, Release.
The Query Interface method allows the clients to navigate among various interfaces supported by
an object. It is used for dynamically changing to different interfaces. The AddRef and Release
functions are used for Reference Counting, which is a simple and fast method for handling the
interfaces of a component. That is when a client gets an interface from a component, the Reference
Count is incremented and subsequently decremented when it is finished using the interface.
Visual Basic implements the QueryInterface, which allows the clients to move among interface
references. It is invoked when you implement one or more user-defined interfaces in a class.
In COM, the components should be reusable. That is, it should have the capability to link
dynamically and it should hide the details of how they were implemented. The component must be
capable to plug into and unplug from an application. All COM objects are capable of making any
number of Interfaces with a new client without changing the binary compatibility with the existing
client code. This is the correct solution for the problem of software versions and is a fundamental
requirement for the component software market.
The COM Technology thus solves many of the problems in the software market today. It solves the
Basic Interoperability by implementing the vtable Technology. It provides a standard method for
communicating between components. It also solves the problem of versioning by implementing the
QueryInterface method of IUnknown. It also helps to adopt the language independence feature by
using the vtable technology that allows calling functions of any language through its pointers
without changing its binary or underlying language standard.
Advantages of COM objects are discussed in the next topic.
Advantages of COM Object
The Component Object Model (COM) Technology is a total solution for most of the problems in a
component software market which in turn is a good solution for most of the problems in the
software industry. So before going into details of component software solutions you should
understand the problems in the component software market.
The main problems in the component software market are given below:
In component technology, each component may be created by different software developers with
different programming languages. How can we these different components easily be combined to
form a single system ?
Another problem is that how one can upgrade a system without changing all of its associated
system files, and, what if this needs to be done across thousands of computers?
Component technology implements language independence. A problem is how the components
created by different language can communicate with each other ?
Component technology enables the developers to create components which are capable of
communicating between computer processes. How is it possible to create both in-process and
cross-process components by using a single programming model ?
Each problem with its corresponding solution are discussed in the following section.
Inter-operability between different components
Vtable technology. The term vtable stands for virtual function table. It has a binary interface
standard allowing calling between components. Thus COM solves the problem of inter-operability
between components.

69
Versioning.
Versioning is done by replacing the components which need to change with new components and is
implemented by the QueryInterface method of IUnknown interface. In this technology, new
functionality is added to the existing components to upgrade it and make it support the new
interfaces. So the existing interfaces do not change and can continue their functionality. Clients
that depend on the existing components will generally not need to be changed and therefore
supports downward compatibility.
Inter Process Communication
IPC encapsulates all the things associated with the communication between components and
insulates the components from it's location.
Distributed Component Object Model (DCOM) is discussed in the next topic.
Using DCOM
The Microsoft Distributed Component Object Model (DCOM) is designed to extend the processing
boundaries irrespective of computer boundaries. COM technology has extended the process
boundaries and DCOM extends the Component Object Model to support the communication of
objects which are residing on different computers connected with a networking system. DCOM
technology evolved from the COM technology that uses the existing COM-based applications with a
distributed technology. It also handles the low-level details of networking, which makes the
component technology provide solutions for many problems.
First of all you must understand the meaning of the term distributed applications. A distributed
application must contain at least two components running on different machines and should
accommodate different clients with different capabilities. The distributed application is also capable
of remote object creation and activation. That is, it is capable to create and use objects that run on
computers anywhere in the world attached with a network. These components should also have
high security capabilities.
COM technology enables the components to interact with each other and the interaction is defined
in such a way that the client can connect the component without an intermediate component as
shown below.

However, a client cannot communicate with a component directly. It has to use some inter-process
communication provided by the operating system. But in COM technology, the operating system
intercepts calls from the client and forwards them to the component in another process.
Here is the importance of DCOM. When the client and the component reside on different machines,
DCOM simply replaces the local Inter-process communication with a network protocol.

70
The important features of the DCOM Technology are given below:
The most important feature of COM technology is the Activation mechanism. This may be defined
as the capability to establish connections with the components and the ability to create new
instance of components.
In the COM Technology the object classes are named with globally unique identifiers (GUIDs).
When GUIDs are used to refer particular classes of objects, they are called Class IDs. These Class
IDs are nothing more than fairly large integers (128 bits) that provide a collision free, decentralized
naming convention for object classes.
If you want to create a new object, you can call one of several functions in the COM libraries such
as CoCreateInstance, CoGetInstanceFromFile, etc. Using this approach, you can create an instance
of a component which resides anywhere as long as it is attached to a common network.
The DCOM technology enables the rapid integration of components which reside in a distributed
computing environment. It provides interfaces for the components from different vendors,
constructed with different programming languages.
The DCOM Technology also enables developers to build solutions faster by assembling software
from pre-built parts.
The DCOM Technology also extends the idea of marshaling. This is useful when a client wants to
call an object in another part of the computer's address space. The parameters for calling this must
be passed from the client process to the object's process. If it is a direct object invocation, the
parameter passing is done in the traditional way where the object reads the parameters from the
stack and writes return values back to the stack for the client's use. When invoking a remote object
some additional code is needed to read all parameters from the stack and write them to a memory
buffer so that they can be transmitted over a network. This process is called Marshaling.
The process Unmarshaling is the process of reading the memory buffer's parameter data and
recreating a stack that looks exactly like the original stack set up by the caller. Once the stack is
recreated, the object can be called. As it returns the call, the return values and output parameters
need to be marshaled from the object's stack, sent back to the client and unmarshaled into the
client's stack.
The DCOM Technology provides the sophisticated mechanisms for marshaling and unmarshaling
method parameters by using remote procedure call (RPC) with Distributed computing environment

71
(DCE) standards. In order to provide these technologies, the exact method signature should be
known. This description is provided using an interface definition language (IDL).
The DCOM also provides efficient methods for connection management. This is carried out by using
the concept of Reference Counting. This is made possible by using the AddRef and Release
methods of IUnknown. The DCOM optimizes AddRef and Release calls for remote objects. The
optimization process uses OXID objects, which implement the IRemUnknown interface. This
determines the RPC string bindings used to contact a group of objects. The Remote reference
counting is conducted per interface (per IPID) using the RemAddRef and RemRelease methods of
IRemUnknown. With IRemUnknown, RemAddRef and RemRelease can increment or decrement the
reference count of many different IPIDs.
Another important problem while designing a distributed application is that of security issues such
as the accessibility options, administration, etc. DCOM technology manages this by using the
following aspects of security.
The first security issue is access. The system should ensure that only authorized users can connect
to an object.
The second aspect is related with the object creation. This is very important for DCOM technology
and is made possible with the implementation of COM libraries. If a client wants to create a new
instance of a component, COM validates whether the caller has sufficient privileges to perform this
operation. This information is configured in the system registry external to the object.
The next aspect is related with controlling the object. Actions such as the file access, network
access and registry access have to be controlled. This approach works well for objects that are used
exclusively by one caller, because the security identity is established once at object creation time.
The Distributed Component Technology provides all the necessary solutions for problems faced by
the Component Technology in a distributed environment.
Self Assessment
Click the Tick mark to select an answer.
(1). COM can be developed using
(a) Visual Basic
(b) Java
(c) VC++
(d) COBOL
(e) Any of the above
(2). A set of data and the code to manipulate that data is referred to as
(a) an object
(b) a class
(c) a client
(d) a function
(e) None of these
(3). To make a connection possible between a client and an object, the properties and methods
should be declared as
(a) public
(b) private
(c) protected
(d) Any of these
(4). The function used to create an object is
(a) CoCreateInstance
(b) CoCreateGUID
(c) AddRef
(d) Release
(e) None of these
72
(5). Additional feature of DCOM compared to COM is its
(a) Distributed technology
(b) Reusable Components
(c) Language independency
(d) Platform independency
(e) All of these.
Workshops
1. What is the advantage of using Component Object Model?
2. Explain objects, classes and clients ?
3. What is Virtual Function table? What is its advantage ?
4. What are the problems in the component software market which are solved by using COM?
5. What are the features of DCOM ?
Chapter-5
Workshops – Solution
1. What is the advantage of using Component Object Model?
The Component Object Model (COM) is a model or specification, which specifies how to build
language independent, binary, upgradable components for efficient, more easily modifiable
applications. The COM Technology allows creating components that are independent of the
languages and platforms. The COM Technology also allow to invoke remote activation.
The major advantage of the COM Technology is that it helps versioning. This means that it
allows upgrading the existing software component with out modifying it.
2. Explain objects, classes and clients?
In an object oriented approach to programming, any problem that is to be solved is divided into
Objects. The set of data and the code to manipulate that data is known as a Class. A class is the
plan for how to process information about a particular logically grouped data and actions on that
data. The term Client may be defined as a program or a component which uses another
component. The communication between the Client and Component is carried out through an
Interface.
3. What is Virtual Function table? What is its advantage?
The Virtual Function table defines an array that points into the virtual functions of a particular
object. It defines a standard way to call functions of any languages through the use of
"pointers". Thus any language that can call functions through pointers can be used to use these
types of components. These components can interoperate with other components written to the
same standard.
4. What are the problems in the component software market which are solved by using
COM?
The Component Object Model (COM) is a total solution for most of the problems in a component
software market, which in turn is a good solution for most of the problems in the software
industry.
In component technology, different software developers with different programming languages
may create each component. How can these different components be easily combined to form a
single system?
Another problem is that how one can upgrade a system without changing all of its associated
system files, and what if this needs to be done across thousands of computers?
Component technology implements language independence. A problem is how the components
created by different language can communicate with each other?
Component technology enables the developers to create components, which are capable of
communicating between computer processes. How is it possible to create both in-process and
cross-process components by using a single programming model?
Each problem with its corresponding solution is discussed in the following section.
73
Inter-operability between different components.
Vtable technology. The term vtable stands for virtual function table. It has a binary interface
standard allowing calling between components. Thus COM solves the problem of inter-
operability between components.
5. What are the features of DCOM?
The important features of the DCOM Technology are given below:
The most important feature of COM technology is the Activation mechanism. This may be
defined as the capability to establish connections with the components and the ability to create
new instance of components.
In the COM Technology the object classes are named with globally unique identifiers (GUIDs).
When GUIDs are used to refer particular classes of objects, they are called Class IDs. These
Class IDs are nothing more than fairly large integers (128 bits) that provide a collision free,
decentralized naming convention for object classes.
If you want to create a new object, you can call one of several functions in the COM libraries
such as CoCreateInstance, CoGetInstanceFromFile, etc. Using this approach, you can create an
instance of a component which resides anywhere as long as it is attached to a common
network.
The DCOM technology enables the rapid integration of components which reside in a distributed
computing environment. It provides interfaces for the components from different vendors,
constructed with different programming languages.
The DCOM Technology also enables developers to build solutions faster by assembling software
from pre-built parts.

74
CHAPTER 6
Introduction to ActiveX
Note: there are some examples of the code shown in this section located on the course
CD in VBAVU\VBCodeSamples\Chapter6.
ActiveX has an important role in the Internet technology arena. Microsoft ActiveX technology is a
framework that allows programmers to build real business applications for the Internet and
intranets that can run across multiple platforms. ActiveX Programmers can write ActiveX
applications using the programming languages C, C++ and Java and run these applications across
different computing platforms such as the Microsoft Windows family, Macintosh and UNIX. Simply
said, ActiveX is the new generation of OLE Technology with Internet capability.
In this chapter we can study the following AcitveX Technologies.
ActiveX Controls
The ActiveX controls provide a method of programming and packaging client components for reuse
across platforms and development environments which can then be included and dynamically
downloaded as needed within web pages. You can use an ActiveX control as you do with standard
built-in controls including them into your programs adding new functionality to your application.
ActiveX Documents
ActiveX Documents enables the browser to support non-HTML documents. The ActiveX Documents
will allow in-place viewing or visual editing. ActiveX Documents allows you to create applications
that can be accessed through the Internet Explorer. The Technology behind the ActiveX is the
Component Object Model (COM), which defines the binary interface between objects. COM is
described in the previous chapter.
Microsoft Visual Basic is a very good tool for creating ActiveX based technologies. It consists of
Wizards that are necessary for constructing ActiveX Controls and Documents.
Next topic is about ActiveX controls.
ActiveX Controls
ActiveX controls, an extension of the older OLE controls, allows you to develop sophisticated
controls based on the Component Object Model (COM). They can be installed in dialog boxes or any
ActiveX control container application. The ActiveX Technology provides a method of packaging
client components for reuse across platforms and development environments. We can use ActiveX
controls just like any of the standard built-in controls. When you add an ActiveX control to a
program, it becomes part of the development and run-time environment and provides new
functionality for your application.
Using ActiveX Controls
To add an existing ActiveX Control into a Visual Basic Environment, follow the steps given below:
Step 1:
On the Project menu, click Components to display the Components dialog box or Right click on
the Toolbox and select the Components Menu Item. Then a Components Dialog box will appear as
given below,

75
Step 2:
The items listed in this dialog box include all registered insertable objects, designers and ActiveX
controls. To add an ActiveX control to the Toolbox, select the check box to the left of the control
name.
Step 3:
Click OK to close the Components dialog box. All of the ActiveX controls' icons you selected will
now appear in the Toolbox.
Step 4:
You can add the new ActiveX control into your Form Designer window and can begin to use the
control like other controls by setting properties, calling methods etc...
Step 5:
Finally, you can run the application by pressing F5.
Creating an ActiveX Control
SmartX Application
The SmartX Application is developed for demonstrating the basic steps for creating an ActiveX
Control. This a simple ActiveX Control that having a Command button. When you click the
Command Button, it responds with a message.
To create the Control Demo project
Step 1:
On the File menu, click New Project to open the New Project dialog box, Double-click the ActiveX
Control icon to create an ActiveX Control project. An ActiveX control project can contain as many
controls as you like. When you build the project, the resulting .ocx file (Active X file) automatically
contains all the controls you have added. Visual Basic automatically adds an ActiveX Control
designer to the project. The default name, UserControl1, appears as the caption of the designer.
Step 2:
On the Project menu, click Project1 Properties to open the Project Properties dialog box. Select
the General tab, fill in the information as given below:

76
Project Name: SmartX
Project Type: Select ActiveX EXE from the Combo Box.
Then Press OK.
The Project properties dialog box is as given below.

Step 3:
In the Control Designer Window place a Label Control and a Command Button and set the Properties as
follows:
Control Name Caption
User Control Smarter SmartX
Label lblSmart Welcome to ActiveX
Command Button cmdSmart Message

Step 4:
Next add the following code in the Click Event Procedure of the Command Button:
Private Sub cmdSmart_Click()
' Display MessageBox
MsgBox "Welcome to ActiveX", vbOKCancel + vbInformation, "VbTutorial"
End Sub
Step 5:
Save the project files. Name them as shown below. Visual Basic will provide the indicated extensions
automatically.
File Filename Extension
User control Smarter .ctl
Project SmartX .vbp

Step 6:
Select the menu item Make SmartX.ocx on the File Menu. This will create the corresponding .ocx
file.
77
Step 7:
To test the newly created ActiveX Control, do the steps mentioned at the beginning of this topic.
The Run form of this application is as follows,

In the next topic, the ActiveX document is described.


ActiveX Documents
ActiveX Document is an application that is designed to run inside a Web Browser. ActiveX
Documents are based on the OLE DocObjects technology that allows in-place viewing and visual
editing. An ActiveX Document container can support any application that supports the interface
defined by the ActiveX Document specifications. This means that, as we navigate through
numerous informational resources within an Intranet, we no longer need to invoke separate word
processors, spreadsheets, etc. to access the various items of information, instead the Internet
Explorer can do this for us and display the information within it's own display on it. This powerful
technology allows a web browser to use the core parts of other PC installed applications thus
extending itself with a relatively minor effort.
Creating an ActiveX Document
Instead of Creation, it is very easy to convert a Standard EXE application into the ActiveX
Document, using ActiveX Doc Migration Wizard. To run the ActiveX Document Migration Wizard, it
must be available in the Visual Basic Add-Ins Menu.
The Steps for Converting a Standard EXE file into an ActiveX Document is shown below:
Step 1:
Open the Visual Basic Project which you want to convert into the ActiveX Doc.
Step 2:
Run the ActiveX Doc Migration Wizard from the Add-Ins Menu. Not if you can't see this menu
item, then click on the Add-In Manager. Then a Dialog will appear. Select the item Loaded/
UnLoaded then press OK. The Add-In-Manager dialog appears as follows.

78
Step 3:
In the first dialog it will ask for the forms which you wish to convert into an ActiveX Document.
Select the Forms and press Next button. The dialog box is as follows,

Step 4:
In the Second Dialog Box it will ask some options. Here select the Default options and press Next.

79
Step 5:
In the last Dialog box press Finish to complete the application.
Step 6:
To Run the Application press F5 or click the Start button.
The sample ActiveX Document is given below.

The next topic describes how to distribute the ActiveX controls.


Distributing ActiveX Controls
You can create and distribute applications containing ActiveX controls in the same way as
distributing other applications. Some problems may occur while distributing applications containing
ActiveX controls. These problems are discussed in this topic.
If you want to run an EXE file containing an ActiveX control, the .Ocx file associated with the
ActiveX control must be registered in the Windows system registry, otherwise the application will
give the error message "File Not Found". Always make a backup copy of the registry before making
any changes to it. See your Windows documentation for working with the registry.
The best solution is to include the necessary .Ocx files in the \Windows\System or System32
directory while installing your application.
Another valid suggestion is that you must include the information on ActiveX controls in the
Setup.lst file found within the installation wizard.
You can also distribute your ActiveX control through the Internet. For that just make a Web Site
including a download area for your ActiveX controls. From here, your user can download the
ActiveX control into their system directory.
Self Assessment
Select the correct answer below
(1). The ActiveX Document is a
(a) A Non-HTML Document which is supported by the Internet Explorer
(b) A Non-HTML Document which is not supported by the Internet Explorer
(c) An HTML Document which is supported by the Internet Explorer
(d) An HTML Document which is not supported by the Internet Explorer
(2). The ActiveX Technology is introduced for
(a) Enhancing database applications
(b) Enhancing Internet related applications
(c) Enhancing Network related applications
80
(d) All the above
(e) None of the Above
(3). The Technology behind the ActiveX control is:
(a) Component Object Model (COM)
(b) Object Oriented Technology
(c) Windows programming
(d) Artificial Intelligence
(4). Which wizard is used for creating ActiveX Document from an application
(a) ActiveX Document Wizard
(b) ActiveX Doc Migration Wizard
(c) ActiveX Control Interface Wizard
(d) All the above.
(5). Which of the following directory in windows typically contains the ActiveX controls:
(a) \\Windows\System Directory.
(b) \\Windows\Temp Directory.
(c) \\Windows\Setup Directory.
(d) \\Windows\Ocx Directory.

Workshops
1. What is an ActiveX Control?
2. What is an ActiveX Document?

81
Exercises
1. Create an ActiveX Control to display the Print preview.
2. Create a database application which can access the database through Internet Explorer.
Chapter - 6
Workshops – Solution
1. What is an ActiveX Control?
ActiveX Controls, are groups of controls, which enables to develop and use the sophisticated
controls based on Component Object Model (COM). They provide the method of programming
and packaging client components for reuse across platforms and development environments,
which can then be included and dynamically downloaded as needed within web pages.

2. What is an ActiveX Document?


ActiveX Document is an application that is designed to run inside a Web Browser. ActiveX
Documents are based on the OLE Doc Objects technology that allows in-place viewing and
visual editing. An ActiveX Document container can support any application that supports the
interface defined by the ActiveX Document specifications. This means that, as we navigate
through numerous informational resources within an Intranet, we no longer need to invoke
separate word processors, spreadsheets, etc. to access the various items of information, instead
the Internet Explorer can do this for us and display the information within it's own display on it.
This powerful technology allows a web browser to use the core parts of other PC installed
applications thus extending itself with a relatively minor effort.

82
Exercises – Solution
Exercise-1
Create an ActiveX Control, which enables the printing.

For solving this problem create an ActiveX Control Project. Follow the steps given below to create
the required ActiveX control.
Step 1:
Start a new ActiveX control project. Place a Command Button and a Common Dialog component in
the ActiveX Control Wizard. (The Common Dialog component can be selected from the component
tab.)
Step 2:
Set the properties of the controls as shown below:

Control Name property Caption/Text property


UserControl1 PrintCtl (empty)
CommonDialog1 comdlgPrint (empty)
Command Button CmdPrint Print
Step 3:
Then write the following code in the Click event of the Command Button, cmdPrint.
Private Sub cmdPrint_Click()
Dim BeginPage, EndPage, NumCopies, Orientation, i
' Set Cancel to True.
comdlgPrint.CancelError = True
On Error GoTo ErrHandler
' Display the Print dialog box.
comdlgPrint.ShowPrinter
' Get user-selected values from the dialog box.
BeginPage = comdlgPrint .FromPage
EndPage = comdlgPrint.ToPage
NumCopies = comdlgPrint.Copies
Orientation = comdlgPrint.Orientation
For i = 1 To NumCopies
' Put code here to send data to your printer.
Next
Exit Sub
ErrHandler:
' User pressed Cancel button.
Exit Sub
End Sub
Step 4:
Save the project files and make the .ocx file.

Step 5:
Create another Standard EXE project. Add the ActiveX control you have created to the project using
the Components dialog box. Set the properties of the control and you can use it like other controls.

Exercise-2
Create a database application, which can access the database through Internet Explorer.
Step 1:
Create a Standard EXE project. Then place three Labels, three Text Boxes and an ADO Control on
the form.
83
Step 2:
Set the properties of the controls as shown below:

Control Name Property Caption/Text property


Text Box1 txtStuName (empty)
Text Box2 txtStuId (empty)
Text Box3 txtStuClass (empty)
Label1 lblStuName Student Name :
Label2 lblStuId Student ID:
Label3 lblClass Class:
Step 3:
Then set the connection string of the ADO Control as below:

User Connection String - Provider=Microsoft.Jet.OLEDB.3.51; Persist Security


Info=False;Data Source=C:\My Documents\student.mdb
Step 4:
Save and Compile this Standard EXE project. Then select the ActiveX Migration Wizard from the
Add-Ins Menu.
Step 5:
Using the ActiveX Migration Wizard create the ActiveX Document.
Step 6:
Test and Run the application in your default browser. The Sample output is shown below:

Introduction to Database Programming


Nowadays database processing is common in almost all applications. Databases are used to store
data in an organized manner. Visual Basic can be used to create complex database applications.
When using a database, the important part is in designing it. Designing databases is a speciality
within itself. In order to design a database, you must have a good understanding of the nature and
size of the data to be managed. Many of the rules of designing a database are the same with
designing a program, but the complexities differ. Some applications will be complex and the
database will be simple. In other case the application will be simple and the database will be
complex.

84
Before the invention of databases data was organized in files with fixed formats. There were
different file formats, such as sequential files and random files. The main drawbacks of a File
system are given below:
The Major Disadvantages of a File-Processing System
1. Redundancy and Inconsistency
If an application is created by different programmers over a long period of time, the same programs
and data files may be duplicated in several places. This redundancy leads to complexity, difficulty
of making changes, higher storage cost and higher access costs. This is one of the major
disadvantages of the file system approach.
2. Data accessing difficulty
The file system approach does not allow the retrieval of the needed information in a convenient and
efficient manner. The file system approach cannot easily provide access to the information
according to the user's changing wishes.
3. Problems in concurrent accessing
Most modern systems must allow multiple users to access information at the same time. Giving
multiple access at the same time in a file based database can lead to locking problems and may
lead inconsistency in the data.
4. Security issues
In a file processing environment, the implementation of security and access rights is more difficult.
Data Abstraction
The important advantage of a modern, relational database system is that it can hide the details
such as how the data is stored and maintained within the database. It also provides efficient
retrieval of data. In database management system there are mainly three ways to think about the
organization of the data or "data abstraction methods". The abstraction levels are the Physical
level, the Conceptual level and the View level.

The Physical level abstraction describes how the data is actually stored, bits and bytes and actual
locations within the database.
The Conceptual level describes what data is actually stored in the database.
The View level abstraction can only access a part of the entire database.
The database structure is defined with the concept of the Data Model described in the next topic.
Concept of Database
The database is a set of related information. There is also a set of instructions to manipulate that
data. These two makes the Database Management System (DBMS). That is the Database

85
Management System can be defined as a set of interrelated data and a set of rules to manipulate
that data.
Different data models and database structures are discussed in the next topic.
Data Models and Database Structures
The Data Model may be defined as a set of conceptual tools for describing data, data relationships,
data semantics and consistency constraints. The data models are currently classified into three
categories. They are given below:
a. Object-Based Model
b. Record-Based Logical Model
c. Physical Data Model
a. Object-Based Database Model
The Object-based logical model provides fairly flexible structuring capabilities and allows data
constraints to be specified explicitly. The most often used object based models are Entity
Relationship model and Object-oriented model.
a.1 The Entity-Relationship model
This model consists of a collection of basic objects called entities and relationships among these
objects. The entity can be defined as an object with a set of attributes. The logical structure of a
database can be expressed graphically with the help of an Entity-Relationship diagram.
The Entity-relationship diagram consists of the following components for representing the entities
of a database. It consists of rectangles for representing entity sets, ellipses for representing
attributes, diamonds for representing the relationships among entity sets and lines for linking the
attributes to entity sets and entity sets to relationships.
The sample of an Entity Relationship diagram is shown below:

a.2 Object-Oriented Model


This model is based on a collection of objects. It consists of values called attributes and a set of
code that operate on object. These set of code is called methods. One object can access the data of
another object by invoking the method of that object. This is called passing message to that object.
b. Record-Based Logical Models
These models are used to describe a database in a fixed format of records of several types. That is,
each record type defines a fixed number of fields or attributes and each field is of fixed length.
Three important Record models are Relational, Network and Hierarchical models.
b.1 Relational Model
The Relational Model, currently the most widely used, represents the data and relationships among
data by a collection of tables. Each table has a set of columns and rows. The rows are called
records and the columns are called fields.
A database represented with the relational model is given below.

86
b.2 Network Model
In the Network Model the data collection and the relationships among data are represented by links
and can be viewed as a mesh or network of pointers.
c. Physical Data Model
The physical data model can be used to describe the data at the basic model. The Unifying model
and the Frame memory are the commonly used physical data models.
Database Structures
Based on one of these models the Database can be defined and data can be stored in many ways.
The three important storage models are indexed, hierarchical and relational data storage
technologies. These types have different conceptual models. The storing and retrieval of data also
differ in each model.
In Indexed databases, the data can be searched easily and can be retrieved efficiently. The
retrieval is done using the index key. Using the index approach fast retrieval of data from
sequential lists, random lists, and complex file relationships can be done using the indexed key.
Indexed databases do not provide referential integrity and data validation processes. Code should
be written for handling those situations.
A hierarchical database is implemented as a tree structured database. Here the data structures
are linked directly. So fast data access is possible in the case of hierarchical databases. A record
above a particular record is the parent of the latter record, i.e. the latter record will be child.
Referential integrity is supported in this data model so the deletion in the parent record will cause
the deletion in the linked records also. For defining complex relationships, the hierarchical model
will be very complex and hence an experienced programmer will be required.
In Relational databases, the database consists of a collection of tables, each of which is assigned
with a unique name. In this model, the related information is stored in a table. There will be
relations between tables. A table will have a set of fields. One field of a table can relate two tables,
referencing one field in another table. This model has provisions to handle the referential integrity
and data validation to organize the data efficiently.
Of the three, the Relational Model is the most widely used database model. This model allows the
use of Structured Query Language, SQL. Using SQL many database tools and products can be made
to work together. Currently Oracle, SQL Server, Sybase, Informix, Access and even DB2 are all
relational databases.
Database design concepts are discussed in the next topic.
Database Design Concepts
Designing a database is the first task in making a database application. When you design your
application, you not only need to design your program code for performance, but you must pay
attention to the logical and physical design of the database. A good database design allows data to
87
be stored efficiently, makes data updating easier, allows addition of new functions, tables and data
with flexible design, and makes the searching of records much easier and efficient.
Relational database have certain additional features. In a relational database the tables have
relations between each other and they are maintained by certain keys in the tables. For example, if
you have to keep employee records for a company, you can have two different tables - one to keep
private information and other to keep job-oriented information of each employee. The two tables
can be linked to appear as one with a key field such as employee number so the employee name,
job etc. will not be repeated in both the tables. By referring the employee number, the job
information can be obtained from the second table.
Data Designing
Before designing the database for an application you must complete the data design. This means
that when you start an application you must do the following steps.
First of all you must know in great detail, all about the problem to be solved. Generally, you need to
know as much about the data to be managed as the people who manage the data for a living. The
next step is the database design. Here you have to arrange all the information to be tracked and
organize it into logical groups of data. Always make sure to identify individual pieces of information
into their smallest possible manageable parts of information. For example, don't list "name" as a
storage item, break the name into first, middle and last name. Next study the relationships
between the collected data. Finally organize the related data into tables. It is not unusual to have
tens of tables, and some applications can even have thousands of tables, each with 3-50 fields. This
can be a big, detailed job, and is a specialty that is often left to professional database designers.
You can study in detail about this in the coming topics. The application's data characteristics and
processes are defined while designing the data. A good data design can make your application work
faster, become more easily maintained and adapt to future changes with less disruption. While
designing a database the many informational concepts and processes specific to the task at hand
will be encountered.
At the beginning of the design process, the storage specifications will not be clear. As the designing
of the database progresses a data modeling technique should be used.
Data Modeling
The identification, documentation and implementation of the data requirements of an application is
called "Data modeling". In this process, the existing data models will be checked and the
disadvantages can be discovered. Then a new model is designed to overcome the drawbacks of the
existing model and enhancements can be created that encompass all new, and future expected
needs.
Data modeling consists of the following processes,
1. First, data should be identified for a particular application. To identify the data the
requirements of the application should be determined and clarified.
2. After identifying the data, the type and size of the data should be defined.
3. The data integrity should be maintained. Constraints or data rules should be defined for data
validation and satisfying business rules.
4. Security and backup processes should be defined.
5. An appropriate data storage method should be chosen.
Data modeling have some involvement in the business management field. The company's top
management will need to verify and understand the application. Data modeling can be used to
model the structure and usage of data and express in a way that the top management can
sometimes understand. The users such as the top management in a company will be more
concerned with the data and how it is organized, collected and accessed. Data modeling can be
used to help this difficult process. Data modeling should include a complete background on the
data requirements of the current application.

88
After the data modeling is completed, you can start the database design. The database design is
very important because it is the key part of the application design.
Database Design
When designing a database, certain objectives should be met. Some of them are
 Exclusion of redundant data.
 Efficient searching of records should be possible
 Database maintenance should be made easy and efficient data access should be possible.
A good design allows you to store the data efficiently and provides easy data updating. The steps
involved in design process are:
Step 1:
Complete the data design.
Step 2:
Organize this information into tables. That is, you have to create a table for each entity of the
problem and then give unique name for each table.
Step 3
Detect the relationship between the information contained in different tables and set the relations
for the tables.
Step 4:
For each table the indexes can be created as they needed. Next determine the need for validation
of data in all the tables by enforcing constraints.
By following these steps, you can design a database satisfying the requirements of the application.
You can see in detail how to define tables and set relationships in the next topic.
Defining Tables and Columns
The collection of related data can be grouped to form a table. For each and every piece of
information in the table, you must decide whether a piece of information should belong to a table or
not. In a table there should be information, which naturally belong to each other. A table should not
be created in such a way that there are many blank spaces when information is stored. Disk Space
can be saved by separating the fields in one table to form more tables.
Normalization
Repetitive data should attempt to be reduced or eliminated using the process of Normalization. The
process of normalization involves three steps. Each step reduces the amount of redundant data in
the tables.
First Normal Form
Move the data into separate tables so that the data in each table is of similar type. Give each table
a main or primary key. This will eliminate any repeating groups of data. After performing this
process, the information will be separated into two tables, one with repeating fields and the other
with non-repeating fields of the main table.
Second Normal Form
If the non-repeating table has a composite primary key, which is made up of more than one column,
then the columns that depend only on part of the composite key, should be separated along with
the key to form another table.
Third Normal Form
The is the final step in the process of normalizing a database. The data that does not depend only
on the primary key is avoided in this step. If any field does not depend on the primary key that
fields will be separated into a new table.
Indexing the Information
Indexing can be used to define the way in which the records are accessed. The data is stored in the
order related to the order they are entered to the database (The physical order). If the data is to be
accessed in an order, the logical order for the storage should be defined. The logical order can be
defined as the programmer needs. Indexing is used to implement logical ordering.
89
Indexing can be done on a table with respect to a field. A table can have more than one index.
Index will in effect create another database table. The fields of this table will be copies of the
original table and be listed in the indexed order so the original tables can be searched quickly, but
only on the indexed fields. Some tables need more indexes than others. Creating indexes slows the
process of adding records to the database, and uses additional storage space.
Relationships
After normalization and defining indexes the tables should be related to one another. Tables often
have data relationships between them. In typical SQL statements the relationship can be specified
using a JOIN condition in the WHERE clause. Two tables can be related using an identical field in
both the tables. An example of the relation between two tables is shown below.

Queries

In complex databases the SQL statements used to access data will vary for different operations on
one or groups of tables. A query is a part of a database where a specific type of access is
predefined and saved inside of the database. Queries can be defined for certain operations and
can be used wherever needed. A query is a bit more than an SQL statement defined directly in the
database. As the database has a chance to process the query in advance, the performance of
queries is enhanced.
For example, you can use a query for the operations given below:
1. For Creating a table you can use the Create Table Query.
2. For Adding records to a table you can use the Append Query.
3. For Updating a record you can use the Update query.
4. For deleting a particular record you can use the Delete Query.
You have to choose an appropriate architecture while designing an application.
The next topic discusses how to choose an architecture while designing a database application.
Choosing an Architecture
Choosing an architecture involves choosing the data access method that connects the application
and the data source.
Choosing the Data Access Technology
Almost all applications require some form of data access. Stand-alone applications usually use local
data access. The local data access is easy to implement and only very little programming is
needed. For large applications, data access is more complex. For remote databases data access is
considerably more complex. It may involve remote data sources with different data formats and
storage mechanisms, and involve issues like bandwidth of connections and replication of data.
Choosing a best data access technology is a crucial task. An access method should be selected
based on the requirements, the corporate standards, available computer and financial resources,
and the technical requirements. Also the developer should be able to implement the particular
access method efficiently and the code should be potentially reusable. If an exotic methodology is
chosen, it will result in expensive development and maintenance, and may lock you into a dying

90
technology. So the data access method should be chosen in such a way that it can reduce the
development time, simplify coding and provide high performance with the required functionality.
Microsoft data access technologies can be used in almost all situations. Each technology has it's
relative strength. The data access implementation and usage issues of each data access
technology should be known to the developer. If you know the details corresponding to each
method, you can choose the best one according to the requirement at hand.
The data needed for your application may be stored in various departments of the organization in
different formats. Each department will be using different systems for manipulating database, such
as mainframes, local workstations or remote data files. The data access method chosen, should be
able to access data from all the different formats in various departments of the organization. This
will be a complex data access process, since the data is stored in different formats and processed
in unique ways.
OLE DB with ADO provides an excellent data access solution for different file structures and data
storage types. The OLE DB and ADO combination together provides a uniform data access solution
which is fast and easily maintainable.
Choosing a Data Access Strategy
Here are some strategies to follow when you choose a data access technology:
You will often have to deal with new systems and modification of existing systems. The modified
application will typically be using old data access technology which may reduce the cost for data
access. But using an old data access method will make programming much more difficult and lead
to unnecessary program overhead. Everything will have to be controlled using programming. For a
new design, you can use ADO which is the latest among the data access technologies.
The location where data is stored is the next important factor. The data may be in your local
system, on the web or in a remote server. If the data is stored in the local system there is no need
to build separate server to manage it. For remote data, asynchronous data access technology such
as ADO or RDO can be used.
The developers should have experience in the specific data access technology chosen. If the staff is
not experienced, the cost for their training should be included in the development estimates. If a
new technology like ADO is used, you must have an idea of the maintenance costs in the future.
The type of data source, whether relational or non-relational, should be identified in order to choose
the data access technology and to verify connectivity to it.
At the time of developing the application, you can connect the database using a standard way of
connecting to databases known as ODBC. But in the future the ODBC "data source" may be
changed. It should be determined whether the application will be able to continue using ODBC or it
can use other kinds of data sources.
The data access technology can be selected according to the requirement. The advantage of each
data access technology is given below.
ADO
ADO provides uniform access to a variety of data sources and data types. It can be used as a
common interface for all data access requirements. The operational cost with ADO is less, since it is
uniform, consistent and easy to handle. Because of it's uniformity, developers can be trained only
once. If the application uses Active Server Pages(ASP), then ADO can be used for data access.
RDO
The Remote Data Objects (RDO) can access remote databases directly and hence the data access
can be made faster. One of its features is that it does not need a local query processor for making
connection with the database.
ODBCDirect
By this feature, the Jet Database Engine can directly access the ODBC databases. ODBCDirect
improves the performance of old DAO technology.
DAO
91
If the data access services are to be provided with Jet Database Engine, then DAO can be used. This
is a consistent programming model for the Jet Database Engine. It is the only data access
technology that can be used in a 16-bit environment.
These technologies are discussed more in the coming chapters.
In the next topic you can learn how to connect your application with a database.
Accessing A Database in Visual Basic
A Visual Basic database application has three parts - The User Interface, The Database Engine and
Data Storage. They are related to each other as shown below.

The User Interface is the media through which the user interacts with the application. It may be a
Form or group of forms, a Window or an ActiveX Document Form.
The Database Engine connects the application program with the physical database files. This gives
you modularity and independence from the particular database you are accessing. For all types of
databases, the same data access object and programming technique can be used in Visual Basic.
The Datastore is the source of the data. It may be a database or a text file.
Database processing has become an integral part of almost all type of complex applications. A
database is a system that contains different objects which can be used together to store data.
Using Visual Basic, you can create applications easily and make them have efficient access to data.
An application can perform well only if the database is well designed. You can access any type of
database with your application. When working with Visual basic, there are two types of databases
you can choose - local and remote databases.
Local Databases
These databases can be accessed directly from Visual Basic through Visual Basic's Jet Database
engine. Local databases are simple when compared to Remote databases. Some of the local
databases are,
 Microsoft Access
 Microsoft FoxPro
 dBASE
 Paradox
 Lotus Worksheet
These databases are PC resident and can be connected to the front-end of the application without
special software support. For stand-alone, one user or a few user applications, a local databases
can be used. For more users or high traffic applications, local databases will not be sufficient. It is
better to select the database for a particular application after clearly understanding the
requirement.
Remote Databases
These databases are those which can't be accessed by using Visual Basic's basic database access
capabilities . A remote database requires an ODBC (Open Database Connectivity) driver for an
application to access it. Usually remote databases will not reside in PCs. Remote, ODBC connected
92
databases can be run on single PCs and on large server machines with lot of memory capacity
depending on the requirements of the application. Using database servers, the workload on the
client machines can be reduced. These databases can be shared by a few or even hundreds or
thousands of users. Most of these server type databases can also be run on stand alone PC's.
Some of the popular remote databases are,
 Oracle
 Sybase
 Microsoft SQL Server
The Remote Databases can be accessed using Remote Data Objects, which is a good choice. While
creating a large applications, first design the application and the database in a stand-alone PC.
Then as the development progresses, an ODBC connection can be used and the main database
created for the large server based system.
Although Microsoft Visual Basic can access all types of databases, there are two important
databases which are fully dedicated to the Microsoft Visual Studio: Microsoft Access and Microsoft
SQL Server. Let's take a closer look at them.
Microsoft Access
Microsoft Access is a desktop relational database management system (RDBMS) which provides
access to information stored in different related tables. Microsoft Access has a single file
architecture. That is, in Microsoft Access, the components such as tables, reports, Queries and
forms are the collection of objects stored in a single file with .Mdb extension.
A Table is a collection of related data or records. The Table object is the basis of any database
application. Each table consists of a set of columns and rows. The column represents the field and
each row represents a record.
The relationships between the tables are made with the help of Relationships window.
Queries are used to perform some actions on subset of the data in the database. In Microsoft
Access you can build, modify and run the queries.
In addition to these database features Access has, Forms with which user interface can be created,
and custom reports created and run in the database.
Microsoft SQL Server
Microsoft SQL Server is a Relational, Remote, client server database that has the capabilities for
developing data tools, database design, application structure, query design and a choice of
interfaces.
The Microsoft SQL Server can be used to create "three-tier" applications. Three tier applications is a
modular way of dividing the processing of an application for maximum modularity, ease of
management, and flexibility. The three Tiers are
a. Data services
Data services are used to manage data, join the records and maintain the integrity between them
b. Business services
These services are used to handle business transactions. They are used for applying the business
rules and logic.
c. Presentation services
These services are mainly used for handling the user interface. That is, they are used for handling
the user input and user transactions.
In SQL server based applications, the Internet is starting to be used for presentation services. These
types of applications can run the presentation services in a web browser.
Interfaces for Accessing SQL Server
There are two types of Interfaces for accessing the SQL Server from a Visual Basic application. They
are Call Level Interface and Object Level Interface
a. Call level Interface

93
The Call Level Interface offers a set of function calls that enable the client application to interact
with the server database. SQL server offers mainly two types of call level interfaces. They are the
Open Database Connectivity Interface (ODBC) and the Database Library (DB-Library). These call
level interfaces can be called from Visual Basic.

94
b. Object level interface
The object level interface offers a number of objects that can be used for sending and retrieving
data from the database. Each object has its own methods for each operation. Each software vendor
has their own object interfaces for accessing the database. Microsoft Corporation offers several
such objects like ActiveX Data Objects (ADO), Remote Data Object (RDO) and Data Access Object
(DAO).
In addition to these features, SQL Server has a lot of additional features.
In the next topic, you can learn about sharing data and database locking.
Database Locking
The locking system is used to maximize the performance of database applications. Using locking,
consistent data can be assured to the users. If one particular piece of data is to be modified it can
be locked to ensure data integrity. Without locking one user may change a data which another user
is currently using. This may cause the collapse of the entire system as the data becomes unreliable
and wrong. So by locking the database, these problems can be avoided.
By locking, a particular user can prevent other users from changing the same data. All database
management systems use locking for data integrity and concurrent data. Each system uses
different types of locking. They may be page level locks, row level blocks or table level blocks which
can be specified while creating the table.
Locking Data in Recordsets
Data in the recordsets can be locked at three different levels: Exclusive mode, Recordset locking
and Page locking.
Exclusive mode locks the entire database. Other users will not be able to access any table in the
database as long as the database is locked.
Recordset locking locks the tables that are currently being used.
Page locking locks the "page" or fixed size block of data in which the edited data is stored.

The level of locking needed should be determined before coding. What should be looked at is the
multi-user needs of the application. If only one user at a time should be in the database, you should
use exclusive locking. Typically in multi-user applications you will use page locking. Page locking
locks small chunks of that database. What you need to be aware of is what the affect of locking is in
a dynamic environment where other user is accessing the database. You will need to write
instructions for the situation when the part of the database needed is currently being used by
someone else.
Exclusive Mode Locking
Exclusive mode will allow only one user access to the entire database at a time. Using this mode,
database maintenance and backups can be done safely.
In a single user environment, exclusive mode provide better performance since there is no need to
write code for locking and unlocking the database. In a multi-user environment it is practically
required to open the database in a shared mode.
In a multi-user environment, the database should not be opened in exclusive mode. None of the
users should open the database in exclusive mode. Microsoft Access has security features to
prevent users from using the exclusive mode. If any database maintenance is to be performed, the
database administrator can open the database exclusively using Open Exclusive permission. You
will need code to determine the current status of the database when first opening a database, and,
if it is exclusively locked, provide a message to the user indicating the status.
A database can be opened in exclusive mode by making the optional argument in the open
command to true. For example, a database named Customer can be opened explicitly as follows,
Dim dbCustomer As Database
Set dbCustomer=OpenDatabase("Customer",True)
Read-only Mode
95
Any database opened in exclusive mode can be made readable, but not writeable to other users by
setting the Read-only argument in the OpenDatabase method. The read-only argument can be set
in the OpenDatabase statement as follows, (The second True is the read only indicator)
Dim dbCustomer As Database
Private Sub Form_Load()
Set dbCustomer=OpenDatabase("Customer",True,True)
End Sub
Errors may occur when any level of lock is attempted to be set in the code. These errors should be
handled to make the database access smooth.
Recordset Locking
By using the exclusive mode the entire database will be locked. To lock a table the Recordset
locking can be used. Using Recordset locking only the table and dynaset sub-types can be locked.
There are two types of locks in Recordset locking: write lock and read lock. Write lock which is the
default can be used to prevent other users from changing the data. Read lock is used to prevent
other users from reading the data. Read locking is useful when it is needed to hide the changes
from other users until the updating of a record is completed. Read lock can be specified in the
OpenRecordset method by setting the options argument to the constant,dbDenyRead.
The Recordset lock can be specified in the option argument of OpenRecordset method. The
combination of two types of Recordset locking can be used in the OpenRecordset method if
necessary. The database should be opened in the shared mode. A database is opened in the shared
mode by specifying the option argument to False. Now, whenever your code works with data, the
locks are automatically put on. Locks can subsequently be released by closing the Recordset object.
The code for locking a table in the OpenRecordset method is as follows,
Dim dbCustomer As Database
Dim recCustomer As RecordSet

Private Sub Form_Load()


Set dbCustomer=OpenDatabase("Customer",False)
Set recCustomer=dbCustomer.OpenRecordset(tabCustomer, dbOpenTable, dbDenyRead +
dbDenyWrite)
End Sub
The above code opens the database, dbCustomer in the shared mode by specifying the option
argument as False in the OpenDatabase method. The Recordset is locked with both read and write
locks by specifying dbDenyRead+dbDenyWrite in the option argument when the recordset is
opened.
If the Recordset object is opened without specifying any value in the option argument page locking
will be done as the default.
If any lock fails, the attempt to set a Recordset lock will cause an error. Your code should check for
errors after attempting an open on both a database and the recordset. If you discover an error, you
could write code to retry the open three times and then provide a message to the user asking for
direction.

For Example, you can write a loop to assume the open attempt will fail. The loop could try three
times, and if there is a failure, set a timer to wait one second. after the second elapses, another
attempt could be made. The loop could be written to give a msgbox every three tries, with choices
being to cancel or continue trying to open the database or recordset.
Page Locking
Page locking will lock only the page containing the record that has to be edited at that time. The
size of a page varies from database to database and a size of 1k is common. Other users can read
the data in the locked page, but they will not be allowed to write data during the locked time. In
96
Recordset objects the default locking is Page locking.

There are two types of Page locking available: pessimistic and optimistic. The type of Page locking
can be specified in the lockedits argument dbPessimistic or dbOptimistic. After opening the
recordset, the type of Page locking desired can be specified using the LockEdits property. If the
value of LockEdits property is True, then the type will be pessimistic locking and otherwise,
optimistic. Pessimistic is the default Page locking.
Pessimistic Locking
In the case of pessimistic locking a page will be locked as a user trys to edit a record in that page
with the Edit method. After the changes are saved using the Update method the lock will be
released. The lock will also be released when the Edit operation is cancelled. The advantage of
pessimistic locking is that the user can be guaranteed to have the most current data. Once a user
starts editing a record in a page no other user can change the data.
The disadvantage of pessimistic locking is that the entire page will be locked until the operation is
completed. Other users cannot change any records on the page until the lock is released. More
locking conflicts will occur with pessimistic locking.

Optimistic Locking
In the case of optimistic locking the page will be locked as the changes are saved using the Update
method. With optimistic locking the period of locking is shorter. Only during the actual time of
saving, other users cannot change the data. The lock will be released as soon as the saving is
complete. With optimistic locking another user can also begin to edit the same data that a
particular user is editing. So one user cannot be sure of the success of the updating. This is a
disadvantage of optimistic locking. The Update method may fail with optimistic locking.
When transactions are used, an optimistic lock turns into pessimistic lock. A transaction locks the
data until the transaction is committed. In the case of transaction, pessimistic locking will be used
even though the LockEdits property is set to false.
Handling Errors with Page Locking
The success of page locking should be checked using code. The method for checking is similar to
that used in exclusive and recordset locking. At first, turn off error handling, do the operation, find
out the error, handle the error occurred and turn on error handling.
An introduction to structured query language (SQL) is given in the next topic.
Introduction to SQL
The Structured Query Language (SQL) is used to interact with a database and access and edit data
in it. SQL statements are divided, according to their nature, into two parts- Data Definition
Language (DDL) and Data Manipulation Language (DML).
To perform an operation, SQL requires only few lines of code compared to other languages. SQL
statements include select which is used to access fields, tables and range of records in a database,
inserts for adding new data, and deletes for removing data. When a query is processed the result
will be returned in a RecordSet.
DDL (Data Definition Language)

Data Definition Language is the language used to define the organization and storage of data.
Some of the DDL statements are,
CREATE TABLE Statement
The Create Table statement is used for creating a table with the given table name and field types.
Syntax
CREATE TABLE tablename (field1 type [(size)] [NOT NULL] [index1] [, field2 type [(size)] [NOT NULL]
[index2] [, ...]] [, CONSTRAINT constraintname [, ...]]) ;
Example

97
Create table tabStudent
(varStud_id Varchar2(12) NOT NULL,
varLast_Name Varchar2(12) NULL,
varFirst_Name Varchar2(30) NOT NULL,
varSS_No Varchar2(12) NOT NULL );

This statement will create a table with name tabStudent with the fields varStud_id, varLast_Name,
varFirst_Name and varSS_No, in which the field varLast_Name can be NULL.
ALTER TABLE Statement
The Alter Table statement is used for adding a new column to existing database or changing the
width of an existing column and specifying a default value for an existing column.
Syntax
ALTER TABLE tablename {ADD {COLUMN field type[(size)] [NOT NULL] [CONSTRAINT index]
[CONSTRAINT multifieldindex} ] ;
Example
ALTER TABLE tabStudent MODIFY (varStud_id Varchar2(12) NOT NULL);
DROP TABLE statement
The Drop Table statement is used for deleting a table from the database.
Syntax
DROP {TABLE table | INDEX index ON table} ;
Example
DROP tabStudent;
The arguments within square brackets are optional.
DML (Data Manipulation Language)
Data Manipulation Language is the language which is used to manipulate data in a database.
Some of the DML statements are,

SELECT statement
The SELECT statement is the most commonly used SQL statement. It is used to retrieve a group of
records from the database and place them in a recordset or dynaset for use by the application
program.
Syntax
SELECT fields FROM tablenames WHERE condition [sort option] [Group Option].
Example
The statement given below will retrieve all fields from the table, tabABC,
SELECT * from tabABC;
The asterisk (*) character stands for all the fields in that particular table. The fields part of the
Select instruction defines the fields included in the output recordset. Any number of fields can be
selected by specifying the names of the fields in the SELECT statement. Calculated fields can also
be selected using the SELECT statement.
INSERT INTO statement
The Insert into statement is used to insert new records into a table.
Syntax
INSERT INTO tablename [(field1[, field2[, ...]])]
VALUES (value1[, value2[, ...])
Example
Insert Into tabStudent
(tabStud_id, varLast_Name, varFirst_Name, varSS_No)
values ('1001','Philip','George','X10101');
UPDATE statement
The Update statement updates the values in a table.
98
Syntax
UPDATE table
SET new value
WHERE criteria;
Example
Update tabStudent
Set varStud_id='1010'
where student_id=14;
DELETE FROM Statement
The Delete From statement removes the specified records from the database.
Syntax
Delete From table_name
[Where condition];
Example
Delete From tabStudent
where varStud_id='1010';
Accessing Multiple Tables
Typically, data will be stored in different tables after the Normalization process covered in an earlier
section. Normalization is done in order to reduce duplicate data. The tables formed after
normalization will be related with each other. Related data can be retrieved using join operations
within an SQL statement. When data is to be retrieved from multiple tables, three things should be
known: knowledge about tables from which the data is to be retrieved, the fields required and the
relationship between the tables.
In some cases two tables will have fields with same name. In this case, the table name and a period
should be added with the field name within your SQL instruction in order to specifically identify the
field name. If you want to retrieve some fields in one table and all fields from another, you can use
the asterisk field selection character with the name of the second table only. Each table used in the
earlier part of the SQL instruction should be specified in the FROM clause of the SELECT statement.
Relationships between the tables is specified in the WHERE clause by using a JOIN condition. The
WHERE clause is used more often than the "JOIN" instruction in SQL statements. The complete SQL
statement is as follows:
SELECT tabEmp.[Firstname], tabEmp.[Lastname], tabDep.* FROM tabEmp, tabDep WHERE
tabEmp.varDepid = tabDep.varDepid;
In the above statement two tables are tabEmp and tabDep, related using the field, varDepid and
the relation is specified with the JOIN condition, tabEmp.varDepid = tabDep.varDepid. The result of
the query is the first and last name from tabEmp table and all related data from tabDep table are
selected.
Creating Calculated Values
Calculation can be done on fields and can be used in the SQL statement for further operations. A
calculated field can be the result of an arithmetic operation or the result of a string operation . In
addition, there are many operations and functions unique to the database. In SQL some arithmetic
functions are available to you such as sum(), avg(), min() ,max(). The following SQL statement
shows how to get the average age of employees in the tabEmp table:
SELECT varName,avg(intAge) FROM tabEmp;
In the resulting recordset the calculated fields will be read only.
Alias Name for Tables
Some tables will have long names which will make SQL statements more complex. You can assign a
short name to any table instead of the large name and then use the short name in the statements.
By using aliases in the FROM clause, you can assign a name to each table that makes sense to you.
For example, the alias name "e" can be given for the table tabEmp.
99
Controlling the Data
SQL can control the range of records to be processed by specifying the filter condition. The filter
conditions are specified in the WHERE clause. The syntax of the WHERE clause is,
WHERE condition
In the condition there are different logical statements. The various types of logical statements are,
Comparison - used to compare a field to another field or a given value
(Example: (ftSalary) >10000)
LIKE - compares a field to a specified match pattern.
IN - A list of acceptable values is compared with a field. It checks whether a particular field value is
in the given set of values. (For example, State IN (" NY" ," NJ"," CT" ).
BETWEEN - Used to specify the value within a range.
The predicates LIKE, IN, BETWEEN have lot of options. In the WHERE clause multiple conditions can
be specified to filter more than one field at a time.
ORDER BY CLAUSE - Clauses can be used to specify the records that are retrieved be sorted in a
specific order. ORDER BY CLAUSE can be used for this purpose in the SELECT statement to get the
rows in the recordset in a specific order. The records in a dynaset can be sorted using the SORT
order in the ORDER BY clause. Multiple fields can be specified in the SORT method.
Example:
SELECT * FROM tabEmp ORDER BY intAge, varName Desc;
The above query will select the records in descending order with respect to intAge and varName
from the table tabEmp.
Self Assessment
Select the correct answer below
1. Database Management System is a defined as:
(a) A set of interrelated data
(b) A set of tables
(c) A set of interrelated data and a set of rules to manipulate that data.
(d) A set of data and the management
2 .Which is not a type of data abstraction?
(a) Physical level
(b) Conceptual level
(c) View level
(d) Structural level
3. The physical level abstraction is actually used for representing:
(a) How the data is actually stored
(b) What data is actually stored
(c) The details of the database relations
(d) All the above
4. How many types of Database Normalization were covered in the text:
(a) One
(b) Two
(c) Three
(d) Four
(e) None of the above
5. Which of the following is not a data access technology
(a) DAO
(b) ADO
(c) ODBC
(d) RDO
(e) None of the above
100
6. RDO is a
(a) Call level interface
(b) Object level interface
(c) Application level interface
(d) None of these
7. How many types of locking are there in Page locking:
(a) One
(b) Two
(c) Three
(d) Four
8. The Abbreviation DDL stands for:
(a) Database Definition Language
(b) Data Definition Language
(c) Data Description Language
(d) All the above
9. The DROP TABLE command is used for
(a) Deleting a table from the database
(b) Deleting the records from a table
(c) Adding a table
(d) None of the above
10. Which is a DML statement?
(a) Select.
(b) Alter Table.
(c) Create Table.
(d) Drop Table.

Workshops
1. Discuss the disadvantages of File system.
2. Define the term Database and Database Management System (DBMS).
3. What are the different types of data abstraction? Explain each level with a real life example?
4. What are the different types of Data models? Explain each one in detail?
5. What is a three-tier application? Explain in detail?
Exercises
Collect the information related to a real world application and do the following:
a. Data design
b. Table design and Normalization
c. Make relationships between the tables.
. Discuss the disadvantages of a File System?
The Major Disadvantages of a File-Processing System are given below:
a. Redundancy and Inconsistency
If different programmers create an application over a long period of time, the same programs and
data files may be duplicated in several places. This redundancy leads to complexity, difficulty of
making changes, higher storage cost and higher access costs. This is one of the major
disadvantages of the file system approach.
b. Data accessing difficulty
The file system approach does not allow the retrieval of the needed information in a convenient and
efficient manner. The file system approach cannot easily provide access to the information
according to the user's changing wishes.
c. Problems in concurrent accessing

101
Most modern systems must allow multiple users to access information at the same time. Giving
multiple access at the same time in a file based database can lead to locking problems and may
lead inconsistency in the data.

d. Security issues
In a file-processing environment, the implementation of security and access rights is more difficult.
2. Define the term Database and Database Management System (DBMS).
The term Database may be defined as a collection of inter-related data. Database Management
System may be defined as a set of inter-related data and a set of rules to manipulate that data.
3. What are the different types of data abstraction? Explain each level with a real life example?
The important methods for data abstractions are:
a. Physical Level abstraction:
This describes how the data is actually stored, bits and bytes and actual locations within the
database.
b. Conceptual level abstraction:
This describes what data is actually stored in the database.
c. View Level:
This can only access a part of the entire database.
4. What are the different types of Data models? Explain each one in detail?
The Data Model may be defined as a set of conceptual tools for describing data, data relationships,
data semantics and consistency constraints. The data models are currently classified into three
categories. They are given below:
a. Object-Based Model
b. Record-Based Logical Model
c. Physical Data Model
a. Object-Based Database Model
The Object-based logical model provides fairly flexible structuring capabilities and allows data
constraints to be specified explicitly. The most often used object based models are Entity
Relationship model and Object-oriented model.

a.1 The Entity-Relationship model


This model consists of a collection of basic objects called entities and relationships among these
objects. The entity can be defined as an object with a set of attributes. The logical structure of a
database can be expressed graphically with the help of an Entity-Relationship diagram.

The Entity-relationship diagram consists of the following components for representing the entities
of a database. It consists of rectangles for representing entity sets, ellipses for representing
attributes, diamonds for representing the relationships among entity sets and lines for linking the
attributes to entity sets and entity sets to relationships.
The sample of an Entity Relationship diagram is shown below:

102
a.2 Object-Oriented Model
This model is based on a collection of objects. It consists of values called attributes and a set of
code that operate on object. These sets of code are called methods. One object can access the data
of another object by invoking the method of that object. This is called passing message to that
object.
b. Record-Based Logical Models
These models are used to describe a database in a fixed format of records of several types. That is,
each record type defines a fixed number of fields or attributes and each field is of fixed length.
Three important Record models are Relational, Network and Hierarchical models.
b.1 Relational Model
The Relational Model, currently the most widely used, represents the data and relationships among
data by a collection of tables. Each table has a set of columns and rows. The rows are called
records and the columns are called fields.

103
A database represented with the relational model is given below .

b.2 Network Model


In the Network Model the data collection and the relationships among data are represented by links
and can be viewed as a mesh or network of pointers.
c. Physical Data Model
The physical data model can be used to describe the data at the basic model. The Unifying model
and the Frame memory are the commonly used physical data models.
5. What is a three-tier application? Explain in detail?
Three-tier application can be defined as a modular way of dividing the processing of an application
for maximum modularity, ease of management, and flexibility.
The three Tiers are
a. Data services
Data services are used to manage data, join the records and maintain the integrity between them
b. Business services
These services are used to handle business transactions. They are used for applying the business
rules and logic.
c. Presentation services
These services are mainly used for handling the user interface. That is, they are used for handling
the user input and user transactions.
Exercise - Solution
1. Collect the information related to a real world application and do the following:
a. Data design
b. Table design and Normalization
c. Make relationships between the tables.
Solution
To solve this problem we can consider a student database. This database contains the details of
students in a school.
a. Data design
This involves arranging the collected information into logical groups of data. Then split the
individual pieces of information into smallest possible manageable parts of information. After that
organize the collected information into tables.
Here we can take the details of students, their batch and their mark details. The collected
information can be listed as given below:
1. Roll Number
2. Name of student
3. Batch Details
104
4. Marks got for Subject1
5. Marks got for Subject2
6. Total marks
Then arrange the collected information into separate groups.
Here we can arrange the data under the following groups.
Student details - This involves the details of the student. Such as his/her Name, Roll number,
batch details, etc.
Mark details - This involves details of marks obtained for each subject in the exam.
So we can arrange it into the two tables as student and marks.
b. Table design and Normalization
First Normal Form: This involves the moving up of data into separate tables and giving the primary key
to each table. After performing this we can arrange the student details into two tables as given below:
Student Table Marks Table
Roll Number Roll Number
Name Mark list Number
Batch code Subject 1
Batch name Subject2
Number of students in that Total
batch
Here we can see there are some data regarding the batch details as repeating. So by normalizing it,
we can eliminate the data redundancy.
Second Normal Form
Here we need to take out any data that depend on any other field of the same table. Here the batch
details and the Student table are dependent with each other. Also we can see that, for each student the
batch details are repeating. To avoid this we can split the entire data into three tables as shown below.
Student Table Marks Table Batch Table
Roll Number Roll Number Batch code
First Name Mark List Number Batch name
Last Name Subject 1 Number of students
Batch code Subject 2
Total

Third Normal Form


The data that does not depend only on the primary key is avoided in this step. If any field does not
depend on the primary key that fields will be separated into a new table. We can see that no such
fields exist in the second normal form.
Thus we get the final database design as:
Student Table Marks Table Batch Table
Roll Number Roll Number Batch code
First Name Mark List Number Batch name
Last Name Subject 1 No of students
Batch code Subject 2
Total
Then set the primary keys for each table as given below:
Table Name Primary Key
Student Roll Number
Marks Mark List Number

105
Batch Batch code

106
c. Making relationships between tables
Here we need to relate the student table, the Marks table and the Batch table. The batch table and
student can be related with the field batch_code. The student table and marks table can be related
using the field roll_number. The relationships are shown below:

107
CHAPTER 8
Component Architecture
Introduction to DAO
Data Access Object (DAO) is an application programming interface (API) that will help you to design
applications that are independent of any particular database management system.
The Microsoft Jet database engine is used to provide a set of Data Access Objects. DAO provides a
set of objects for connecting, manipulating and modifying a database. Performance of DAO can be
made better by using .MDB files, which can be created by Microsoft Access. DAO can also be used
to access ODBC databases with the help of Microsoft Jet Database engine.

The Jet database engine's object-oriented interface uses the Data Access Object Model.
Corresponding to the logical view of a relational database system, DAO has a hierarchy of classes.
The hierarchy consists of the database itself, the tables defined in it and their fields, indexes, and
so on. In a program, objects are created and programmatically manipulated using the classes of the
Data Access Objects.
DAO Architecture
The Data Access Object is a set of automation interfaces for the Jet Database Engine. DAO can
access Jet databases (Microsoft Access) directly, but to communicate with other databases, the
corresponding ODBC Driver is needed. The figure of the DAO Architecture is given below:

In the figure, the application program uses DAO to connect with the Jet Database Engine. Through
the DAO, a Microsoft Access Database can be connected. ODBC databases can also be connected
with Jet Database Engine through the ODBC drivers or interface programs.
Jet Database Engine
The Microsoft Jet Database Engine is used for access a Database. It is a powerful programming tool
for establishing connection with a database.
The DBEngine is the base or underlying class of DAO. It contains and controls all other classes in
the hierarchy. The DBEngine is not owned by any class. To connect to the Jet Database Engine an
instance of DBEngine class should be created within a program. The DBEngine class has the logic
within it to connect to the Jet Database Engine. The copy of the DBEngine class within a program
will in turn have several groups of objects. Each group of objects is known as a collection. The
objects within a collection will normally have a common nature. In order to work with a class in
Visual Basic, you need to create a copy of the class for use within a program or part of a program.
You create a copy of a class (an object) by declaring the object as a variable of type "class". This
can be done as follows,
Two types of ODBC support exist in the engine. They are,
Direct ODBC
In Direct ODBC, the program "calls" for accessing databases are passed through the Database
Engine and handled by the ODBC driver manager.
Indirect ODBC

108
Indirect requires the ODBC layer of the Jet Engine to process the request. Database independent
code can be developed with Jet Database Engine which translates database specific language and
subsequently handles Data manipulation.
The figure for the Jet database engine is given below:

Object Model in DAO


DAO is a hierarchy of classes which corresponds to the objects in a database such as tables, fields,
indexes, records and so on. Objects can be created from the classes by creating an instance of it in
your code. In the hierarchical model, classes belong to a collection. The DAO object model structure
is given below:

In DAO, the DBEngine object is the top level object. It contains workspaces and error objects.
The Workspace class has a number of Workspace objects. Each Workspace object have the
database, User and Group objects within it.
Each database class can have a number of database objects which in turn have Tabledef, Querydef,
Recordset, Container and Relation objects.
The Tabledef class has a number of TableDef objects which in turn have Field and Index classes.
109
Then the Index class has a number of Index objects which in turn have the Index Field class.
The QueryDef class have a number of QueryDef objects which in turn have Field class.
Field class has a number of Field objects which in turn have the Parameter class.
The RecordSet and Relation classes have a number of corresponding objects which in turn have
Field classes.

So some classes are member of a particular class. A member of a collection can be accessed
through the owner object.

110
Managing ODBC Connection
A database application can be written to provide access to different data sources. The Database
can be an ODBC Database, Microsoft Access, Microsoft SQL Server or ISAM Database such as
FoxPro, Paradox, dBASE or any database supported by the Jet database engine.
When data is accessed through DAO the connection management routines of the Jet Database are
invoked. After establishing a connection, the Jet, it will try to share an existing connection in order
to try to save resources. For each OpenDatabase call in a program, a Data Source Name should be
given. If the same DSN (data set name) is referenced by more than one OpenDatabase call, the
DAO reuses the connection, saving time and resources.
ODBC Data Sources can be accessed using DAO and the Jet Database Engine. The Data Source
Name (DSN) that points to the ODBC Data Source is specified in the OpenDatabase method. Jet
Database Engine contains Data Source Name(DSN), user name and password.
Next topic explains you how to use the data controls. The properties and methods of data controls
will be discussed.
Using Data Controls
The data control is the simplest data access method that can be used to connect your application
with a database. By setting a few properties of the Data Control, you can connect your application
to the database and access data from a table or SQL query without writing any additional code. The
Data Control can access various types of databases other than Microsoft Jet Database. The
important properties of the Data control are given below:
Important Properties Of Data Controls
Database Name
This property is used to hold the name and location of the database to which connection has to be
established.
Default Cursor
The DefaultCursorType property of the Data Control determines what type of cursor is to be used.
The DefaultCursorType has three values. If it is 0, then it allows the ODBC driver to determine what
type of cursor is to be used. If it is 1, then it use the ODBC cursor library. If it is 2, then it allows the
serversidecursor, which is specially used for network based applications. A cursor is a mechanism
for moving within a database.
DefaultType
The DefaultType property determines the type of the DataSource. If it is 1, (UseODBC) then it
indicates to use the ODBC direct data access method. If it is 2, then the Microsoft Jet Engine is used
for accessing data.
RecordSource
This property holds the tables available in the database. You can set this property to any table you
want to connect with the application. Alternatively, you can fill it with SQL statements which may
access multiple tables.
ReadOnly
This property is used to set the access to database as read-only.
RecordSet Type
This property defines the type of recordset to be created for data access. There are recordsets for
reading only, ones for dynamically modifying data etc.
Steps for establishing a Connection with an application
Step 1:
Select the Data control icon from toolbox and place it on the form.
Step 2:
Set its DatabaseName property with the name of the database to which connection is required.
Step 3:
Set the DefaultCursorType value as 0 (Default Cursor).
111
Step 4:
Set the DefaultType property as 2 (UseJet).
Step 5:
Set the value of Recordset Type property to 1 (Dynaset).
Step 6:
Select the Record Source value. So pull down the Combo in the properties window. Here you can
see the name of all the tables in the database. Select the table name that you want to use.
Recordset Property
A recordset object provides a logical representation of the records in a table, or in the results of a
query. There are three types of recordset objects.

Table
This type of recordset provides access to all of the records and fields in the specified table. The
sorting order of the retrieved records is set using recordset object's Index property. The contents of
records can be updated using the Table type, but only one table at a time can be referenced by this
type of recordset. Data access is faster, since it has a direct reference to the table.
Dynaset
The Dynaset type represents a selected (by SQL) set of records from one or more tables. The
records and fields contained in a dynaset type are specified by a query. The data can be modified in
the case of dynaset type recordset.
Snapshot
The Snapshot type recordset is similar to a dynaset type, but it is read-only. The data cannot be
updated. So you cannot use a snapshot type to modify records in a table. Snapshot type can be
used if you want only to view data or fill dropdowns from a table.
Data-Bound Controls
A data-Bound control is one where it "knows" about databases. Data-Bound controls can fill
themselves from fields in a database, and can update data directly to a database without any
programming.
Using Visual Basic, database applications can be created for the Windows environment quickly and
easily. If you want to access data from an existing database, then data controls can be used to
access the data and your can use data-bound controls to display them. With these controls, you can
create a wide variety of complex applications. Data bound controls are also called data-aware
controls. There are seven standard data-bound controls.
LabelBox - Used for displaying text and numeric data. The user cannot edit or modify data
displayed in the LabelBox. The user cannot enter data to the LabelBox.
TextBox - Used for displaying and entering text.
CheckBox - Used for displaying Boolean (Yes/No) data.
ComboBox - The ComboBox has two parts, one TextBox portion and other a ListBox portion. The
TextBox portion displays the data selected from the ListBox portion. It can also be used for data
entry.
ListBox - Similar to ComboBox. But it does not has an editing field.
PictureBox - Can display a bitmap, icon or metafile.
ImageBox - It is similar to a PictureBox with less capability. It uses fewer resources compared to
the PictureBox.

The above controls can be bound to databases by setting the following properties,
DataSource
Set this property with the name of the Data Control to which the control is to get it's data.

112
DataField
Set this property to the field available in the recordset of the data control to which the control is to
be bounded.
Methods of The Data Control
Data controls have many methods. Methods like MoveFirst, Move Last, MoveNext and MovePrevious
are used to move through the records.
MoveFirst - Will move the record pointer to the first record in the recordset.
MoveNext - Will move the record pointer to the next record in the recordset.
MovePrevious - Will move record pointer to the previous record in the recordset.
MoveLast - Will move record pointer to the last record in the recordset
A recordset has a pointer internally that points to the current record. At any time, the pointer can
point only one record. In a recordset, two special positions of record pointer are BOF and EOF. BOF
is the beginning of the file before the first record and EOF is the end of file after the last record. The
record pointer is set to the first record when BOF is reached and to the last record when EOF is
reached. This operation can be slightly modified depending on the value of BOFAction property and
EOFAction property.
The BOFAction property tells the Data Control what to do when the beginning of the file is
reached. This property has the following values:
0- Move First
This is the default setting and the record pointer is set to the first record using the MoveFirst
method and the BOF flag is set to false.
1- BOF
BOF flag is set to True.
The EOFAction property tells the Data Control what to do when the end of the file is reached. This
property has the following values.
0- Move Last
This is the default setting and the record pointer is set to the last record using the MoveLast
method and the EOF flag is set to false.
1- EOF
EOF flag is set to True.
2- AddNew
Automatically executes an AddNew method for adding a new record.
You can search for particular records in the recordset using the Find methods. The various Find
methods are:
FindFirst - Find the first occurrence of the required pattern.
FindLast - Find the last occurrence of the required pattern.
FindNext - Find the next occurrence of the required pattern.
FindPrevious - Find the previous occurrence of required pattern.
According to the required pattern, these methods can be used to locate records. The general syntax
is,
RecordSet.Findfirst String-Expression
String-Expression represents some condition for locating data in the recordset. How you write this
condition is the same as you would write the "where" part of an SQL statement. For example, from
a personal record, the details of the person with name, Simpson can be searched as follows,
datEmp.Recordset.FindFirst "Name=Simpson"
datEmp is the data control and Name is a field in the recordset. The above statement will locate the
first record with the Name field containing Simpson. The status of the search can be accessed using
the NoMatch property. If no record exist with the specified condition,
datEmp.recordset.NoMatch

113
will be true, otherwise false. After checking the NoMatch property further operation can be carried
out.
Example:
datEmp.Recordset.FindFirst "Name=Simpson"
' Checks result of the Find method
if datEmp.Recordset.NoMatch = True then
' Display message
MsgBox "No person exist with the name, Simpson"
else
MsgBox "Person exist with the name, Simpson"
EndIf
In this example the person having the name as Simpson is searched. The status after the execution
is checked with the NoMatch property. If the NoMatch is true then there is no such record.
Validation In Data Control
The data to be submitted to a database can be checked with the events and properties of data
control. Typically, inputs are validated before updating the database. This checking is done in the
validate event of the data control. The syntax is as follows,
Private Sub datEmp_Validate(Action as integer, Save as integer).
End Sub
The action argument is an integer value which contains a value to denote the operation that caused
the validate event to occur. For example, if the value is 1, the operation that triggered the Validate
event was a MoveFirst method. By setting the action to zero, the operation that triggered the
validate event can be cancelled. The save argument can be set to zero to prevent the changes due
to the operation and to 1 to save the changes due to the operation. Typically, you will check data
for errors and other conditions that you need to insure before allowing entry into the database.
Here is a good place to put the code if you are using data controls.
Methods Used To Access the Database
For accessing and updating the database, you will typically be writing code. Accessing and updating
records through code is more efficient than the no-code method. The No-code approach is to set
the EOFAction of the data control to Addnew, so that whenever the EOF is reached a new record will
be added. For updating records using code, the following methods can be used.
AddNew
For adding a new record to the database this method can be used. Addnew will create a blank
record at the last record of the database. Next you would manually set the value of each field in
that record with data from your form. Following this, you would use the Update method of the data
control to make the data be written into the database.
Example
datEmp.RecordSet.Addnew
datEmp("firstname")="Joe"
datEmp.Update
where datEmp is the name of the Data Control.
Update and Refresh
In order to edit data, you must first position the recordset on a particular record, and call the edit
method. After changing the fields you wish to change, you should then call the update method. If
you wish to cancel the edit, you merely need to cancel the edit by calling the refresh method.
Example:
datEmp.RecordSet.Edit
datEmp("firstname")="Mary"
datEmp.RecordSet.Update
Delete Method
114
Using the Delete method, the current record at which the record pointer points can be deleted.
Example:
datEmp.RecordSet.Delete
It will delete current record in the recordset.
Major Disadvantages of the Data control
The data control links the information in your database with any bound controls that you place on
the form for displaying information. Besides a lot of capabilities, data control has a few limitations
as follows,
1. Add or Delete functions are not available with the Data Control. The only way to provide these
functions is by using the Data Access Object method with the Data Control.
2. Implementation of transaction processing is more complex since EDIT and UPDATE operations
are automatic.
3. New Database or table cannot be created using Data Control. It can be used only for accessing
existing database.
Click here to go to a sample program using data control.
In the next topic, you can learn how to program with data access objects.
Employee Details Sample - Using Data Control

Description
This sample helps you to create an application for keeping the details of all the employees of a
company. This project is a simple database application, which includes creating a database, linking
with Visual Basic, performing operations such as Insertion, Updation and Deletion in the database.
In this application a user interface is designed to enter the details of the employees in a firm.
The interface of this application is an SDI form through which you can enter, update and delete
data in the database.
Creating the Database
In this application, the database is created in Microsoft Access, which is a native database of
Visual Basic.
Here you have to create an employee database, which is designed to store the information of
employees, like
 Employee Number
 Employee Name
 Department Number
 Employee’s Salary
 Age of Employees
To create a database in Microsoft Access, do the following steps:
Step 1:
From the Start menu, choose Programs.
Step 2:
Choose Microsoft Access and choose New Database.
Step 3:
In the window for creating new database give the name empdb and save.
Step 4:
Then choose table design. Enter the fields for the table like Empno, Empname, Deptno, Salary and
Age. Choose Empno as primary key.
Save the table with name emptab.
Designing The interface
After designing the database, the user interface has to be designed. First decide the controls you
want for your interface. The design of the interface can be done with the following steps:
Step 1:
Start Visual Basic and choose Standard EXE Project.
115
Step 2:
You have five fields in the table, emptab. So five TextBoxes are needed for displaying the data.
Place five TextBoxes of equal size on the form and arrange them.
Step 3:
Then for each TextBox you need Labels to display the field name. So place five Labels on the form.
Step 4:
Then you need nine Command buttons for various operations like insertion, updation, deletion,
saving and viewing through records. Place nine Command buttons and set their properties
according to the table given here.
Step 5:
Then click on Data Control on the ToolBox and place it on the form.
Step 6:
Set the DataBaseName property of the Data Control with the database name empdb.mdb with its
complete path.
Step 7:
Set the RecordSource property of the Data Control with the table, emptab, to which the Data
Control is to be connected and its RecordsetType property to 2 - Dynaset.
Step 8:
Select each control and make its DataSource property as name of the data control (Here
datEmp) and the select the datafield from the list.
The property settings of all the controls are given below:
Property Settings
Control Name Caption/Text
DataSource DataField
Name Property property

Form frmEmpdetails Employee Details (empty) (empty)

Data Control datEmp (empty) (empty) (empty)


Textbox1 txtEmpNo (empty) datEmp Empno
Textbox2 txtEmpName (empty) datEmp Empname
Textbox3 txtDeptNo (empty) datEmp Deptno
Textbox4 txtEmpSal (empty) datEmp Salary
Textbox5 txtEmpAge (empty) datEmp Age
Label1 lblEmpNo Employee No : (empty) (empty)
Label2 lblEmpName Employee Name : (empty) (empty)
Label3 lblDeptNo Department ID : (empty) (empty)
Label4 lblEmpSal Salary (empty) (empty)
Label5 lblEmpAge Age (empty) (empty)
Command
cmdAdd Add (empty) (empty)
Button1
Command
cmdUpdate Update (empty) (empty)
Button2
Command
cmdDelete Delete (empty) (empty)
Button3
Command
cmdSave Save (empty) (empty)
Button4

116
Command
cmdClose Close (empty) (empty)
Button5
Command
cmdFirst First (empty) (empty)
Button6
Command
cmdPrevious Previous (empty) (empty)
Button7
Command
cmdNext Next (empty) (empty)
Button8
Command
cmdLast Last (empty) (empty)
Button9
Coding
Place neccessary controls on the form. Set the properties of the controls as given above. Then go to
the Code Window. Declare the global variables in the General Declaration, as given below:
Option Explicit
' Declaring Global Variables
Dim varMode ' For setting the Mode
Dim varResp ' For receiving the user's response
Then you have to write user procedures.
To write user procedure, go to the tools menu and select Add Procedure. Then a dialog
box appears. Give a name for the procedure, select the procedure type as sub and click OK.
Then you will have the procedure body. You can write the required code there. The following user
procedures has to be written,
(a) Procedure for clearing the text boxes during addition of new records, the procedure named
Clear is written.
Public Sub Clear()
' Clear the TextBoxes
txtEmpNo = ""
txtEmpName = ""
txtEmpSal = ""
txtDeptNo = ""
txtEmpAge = ""
End Sub
(b) Procedure for searching a particular record in the table while updating or inserting, to
know whether the record with particular empno exists, another user procedure, Search is written.
Public Sub Search()
' Move record pointer to first record
datEmp.Recordset.MoveFirst
' Finds the record with same Employee Number
Do While Not Trim(datEmp.Recordset!Empno) = Trim(varResp)
datEmp.Recordset.MoveNext
If datEmp.Recordset.EOF Then
MsgBox "Employee with this ID does not exist"
Exit Sub
End If
Loop
End Sub
These procedures are called in other events when needed. Next, the event procedures have to be
written.

117
Insertion
First, the TextBoxes are to be cleared and the variable varMode should be set to “Add”. In the click
event of cmdAdd button code is written for these operations. The code for inserting with respect to
the varMode is written in the click event of cmdSave button.
Private Sub cmdAdd_Click()
'To add new record
datEmp.Recordset.AddNew
' Calls Clear function to clear TextBoxes
Call Clear
' To set the focus on txtEmpNo
txtEmpNo.SetFocus
' Sets varMode to "Add"
varMode = "Add"
End Sub
Updation
The Empno of the record to be updated is searched using the Search procedure, after getting the
value from the input box. Then the variable, varMode is set to “Update”. The code for updation
should be written in the click event of cmdSave button. The operation is done according to the
value of varMode.
Private Sub cmdUpdate_Click()
' Set the varMode variable to Update
varMode = "Update"
varResp = InputBox("Enter the empno", "Updation")
' Checks whether varResp has value or not
If varResp = Empty Then
' To exit from the procedure
Exit Sub
End If
' Calls the Search Procedure
Call Search
End Sub
Deletion
The Empno of the record to be deleted is searched using the Search procedure after getting the
value from the inputbox. Then the variable, varMode is set to “Delete”. The code for deletion is
written in the click event of cmdSave button. The operation is done according to the value of
varMode.
Private Sub cmdDelete_Click()
' Sets varMode to Delete
varMode = "Delete"
varResp = InputBox("Enter the empno", "Deletion")
' Checks whether varResp has value or not
If varResp = Empty Then
' To exit from the procedure
Exit Sub
End If
' Calls the user procedure, Search
Call Search
End Sub
Saving of Transactions

118
Different operations are saved using the code written in the click event of cmdSave button. The
value of the variable, varMode, is checked and the corresponding operation is saved. The code is as
given below:
Private Sub cmdSave_Click()
Dim varReply ' Variable for receiving the response from the message box
' Checks the varMode of operation is adding of records
If varMode = "Add" Then
MsgBox "Record saved"
' Checks the varMode of operation is adding of records
ElseIf varMode = "Update" Then
' Set the record for editing
datEmp.Recordset.Edit
' To update changes in the record
datEmp.Recordset.Update
MsgBox "Record Updated"
ElseIf varMode = "Delete" Then
varReply = MsgBox ("Are you sure to delete current record", vbYesNo + vbExclamation,
"Deletion")
If varReply = vbYes Then
' To delete the current record
datEmp.Recordset.Delete
MsgBox "Record deleted"
End If
End If
End Sub
Viewing Records
The records are viewed using the code in the click event of cmdFirst, cmdLast, cmdNext and
cmdPrevious. The codes are given below.
Private Sub cmdFirst_Click()
' Check whether any record exist
If datEmp.Recordset.EOF And datEmp.Recordset.BOF Then
MsgBox "No current Record"
Exit Sub
End If
' Move the record pointer to the First record
datEmp.Recordset.MoveFirst
End Sub

Private Sub cmLast_Click()


' Check whether any record exist
If datEmp.Recordset.EOF And datEmp.Recordset.BOF Then
MsgBox "No current Record"
Exit Sub
End If
' Move the record pointer to the Last record
datEmp.Recordset.MoveLast
End Sub

Private Sub cmdNext_Click()


' Check whether any record exist
119
If datEmp.Recordset.EOF And datEmp.Recordset.BOF Then
MsgBox "No current Record"
Exit Sub
End If
' Move the record pointer to the Next record
datEmp.Recordset.MoveNext
If datEmp.Recordset.EOF Then
MsgBox "Last Record"
datEmp.Recordset.MoveLast
End If
End Sub

120
Private Sub cmdPrevious_Click()
If datEmp.Recordset.EOF And datEmp.Recordset.BOF Then
MsgBox "No current Record"
Exit Sub
End If
' Move the record pointer to the previous record
datEmp.Recordset.MovePrevious
If datEmp.Recordset.BOF Then
MsgBox "First Record"
datEmp.Recordset.MoveFirst
End If
End Sub
Closing the Application
Private Sub cmdClose_Click()
' To terminate the program
End
End Sub
Sample Outputs
Main Window

Window for Updation


Type the employee number and click OK to locate the record for updation.

Window for Deletion


Type the employee number and click OK to locate the record for deletion.

121
Programming with DAO
Data Access Object is a collection of objects that can be used to program complete database
applications. They are used to access physical data stored in some type of database. DAO has more
flexibility than using the data control.
The basic objects of DAO are:
1. Workspace
A Workspace object defines a named session for a user. The default Workspace object is
Workspaces(0). For simple applications, the default workspace will be enough. The Workspace
object contains open databases and provides support for simultaneous transactions. The
Workspace object controls whether you are using the Microsoft Jet database engine or ODBCDirect
to access external data.
A new workspace can be created using the CreateWorkspace Method as,
Set Workspace = CreateWorkspace(name, user, password, type)
In this call:
name - uniquely identifies the Workspace object.
user - is the particular username for the Workspace
password - String that is password for the new Workspace.
type - denotes the type of Workspace used.
Two types of workspace are dbUseJet, which creates a Microsoft Jet workspace and dbUseODBC,
which creates an ODBCDirect workspace.

Example,
Set wspEmp=CreateWorkspace("Employee","admin","",dbUseJet)
Here the workspace with name Employee will be created.
2. Database
For accessing a database the Database object should be created. It can be created as follows using
CreateDatabase method of the workspace object,
Set database=workspace.CreateDatabase(name, locale, option)
Here,
name - identifies the database
locale - specifies the language to be used
option - denote the version of jet database engine used.
Example,
Set dbEmp=wspEmp.CreateDatabase("empdb",dbLanguageGeneral)
Here the database with name empdb will be created.
3. TableDef
The TableDef objects denote the tables in the database. A tabledef object can be created as
follows,
Set tabledef = database.CreateTableDef (name, attributes, source, connect)
Here,
name- uniquely identifies the object
attributes- defines the characteristics of the table
122
source- denotes the source table if an external database is used
connect-denotes the source of an open database
Here attributes, source, and connect properties are optional
Example,
Set tbdEmp=dbEmp.CreateTabledef("Employee")
Here table with name, Employee will be created.
4. QueryDef
The QueryDef object is used to define queries. Queries can be predefined using this object to a
variable and can be used later when the same query is to be used. A QueryDef object can be
created as follows,
Set querydef = object.CreateQueryDef (name, sqltext)
Here,
object- Denotes the object to which the QueryDef object belongs. It may be an open connection or
database.
name- Identifies the QueryDef object.
sqltext- Denote an SQL statement that defines the QueryDef object.
Example,
Set qryEmp=dbEmp.CreateQueryDef("EmpQuery", "Select * from Employee")
Here the QueryDef object will be created with the name EmpQuery. "Employee" is the name of the
source table.
5. Recordsets
The results of the queries are returned to the recordset. There are three types of recordsets as we
discussed in the topic, "Using Data Controls". The recordset can be opened with the following
statement,
Set recordset = object.OpenRecordset (source,type, options, lockedits)
Here,
source- Denotes the source of the recordset. It will be the name of a table or query, or an SQL
statement.
Type -Denotes the type of the recordset.
option-Denotes the characteristics of the recordset
lockedits- Determines the locking for the recordset
The type, option and lockedits properties are optional.
Example,
Set recEmp=dbEmp.OpenRecordset("emptab",dbOpenDynaset)
Here emptab is the source table and dbOpenDynaset is the type of the recordset.
Creating Database Using Code
In this section we will create a database using code. Let us consider a simple database of a school
with one table. Let the database name be School, table name be Student with fields Stud_ID,
Stud_Name, Class and Age.
1. For each object needed in a database an object variable should be created. The DBEngine and
default workspace objects already exist. So the database, tabledef and field objects have to be
created.
To create object variables for the Student.mdb database having the information of students, write
the following code in the general section.
Dim dbSchool As Database, wspSchool As Workspace
'Creating database,tabledef and field objects
Dim tbdStudent As TableDef
Dim fldStud_ID as Field
Dim fldStud_Name as Field

123
Dim fldClass as Field
Dim fldAge as Field
2. The CreateDatabase method of the Workspace object can be used for creating the new database.
'Setting the default workspace
Set wspSchool= DBEngine.Workspaces(0)
'Creates database with the file name school.mdb in C:\
Set dbStudent = wspSchool.CreateDatabase("C:\School.mdb", dbLangGeneral)
3. The Tabledef object can be created as,
'Create table with the name a student.
Set tbdStudent=dbSchool.CreateTableDef("Student")
4. For each field in the table a field object should be created, and properties of each field should be
set to define the field's size, data type, and other needed attributes.
The following code creates fields of the Student table in the School.mdb database.
' Create fields for the table
' Stud_ID is the first field with datatype dbLong
Set fldStud_ID = tbdStudent.CreateField("Stud_ID", dbLong)
' Stud_Name is created with datatype dbText and size 50
Set fldStud_Name = tbdStudent.CreateField("Stud_Name", dbText)
Set fldStud_Name.Size = 50
'Class and Age field is created with datatype dbLong
Set fldClass = tbdStudent.CreateField("Class", dbLong)
Set fldAge= tbdStudent.CreateField("Age", dbLong)
5. The created fields should be added to the table and the table should be added to the database.
To add the fields, the Append method can be used.
'The created tables are appended to the tabledef object tbdStudent
tbdStudent.Fields.Append fldStud_ID
tbdStudent.Fields.Append fldStud_Name
tbdStudent.Fields.Append fldClass
tbdStudent.Fields.Append fldAge
'Adds the created fields and table to the object
dbStudent.TableDefs.Append tbdStudent
Opening a Database
Any database that you want to use, should first be opened. A database can be opened using DAO
commands. When you open a database you are actually creating an instance of database object
that will be used by the other Data Access Objects. To access the DAO command set, you must
include a reference to the Microsoft DAO Object Library in your project. This library contains all the
DAO objects. While opening a database, you are using the Visual Basic database engine to process
the commands.
The database engine is represented in the application by the DBEngine object. A working database
section is defined by creating workspace objects within the DBEngine object.
Dim dbSchool As Database
Dim wspSchool As Workspace
Set wspSchool=DBEngine.Workspace( 0 )
Set dbSchool=wspSchool.OpenDatabase ( "C:\School.mdb")
Since the above code explicitly uses the default workspace, the DBEngine and Workspace can be
omitted as
Dim dbSchool as Database
Set dbSchool = wspSchool.Opendatabase ( " C:\School.mdb" )

124
Opening databases in separate workspaces control the operation of database transactions, or
controlled changes. Transaction processing operations in one Workspace will not affect the
operations in another.
Accessing Data
When using Data Access Objects, VB's controls are used to display the data. The data should be
assigned to the controls manually. When used in this manner the control are being used as
unbound controls. One advantage of using unbound controls is that you can use any control to
display data, not just the bound controls which are meant to be used with the Data Control.
You can access data within a recordset in several ways. For example, to retrieve the contents of a
field named Title in a recordset called recTitle, assign it into a Textbox named txtData as,
txtData = recTitle.Fields(0)
The Field's name can be specified to retrieve data as ,
txtData =recTitle.Fields("Title" )
Use the recordset collection's default to access the field as
txtData=recTitle("Title")
Click here to go to the example program using DAO.
Manipulating the Database
The data from the database can be accessed as we discussed earlier. The operations on the
database can be done using the Addnew, Update, Delete methods discussed in the previous
chapter, "Using Data Controls".
Other data bound controls like Data Bound List Control, Data Bound ComboBox control, Data Bound
Grid Control and Microsoft FlexGrid Control are discussed in the next topic.
Employee Details Sample - Using DAO

125
Description
We have already seen the Employee details sample using Data Control, now we can learn the data
accessing using DAO programming. This topic is almost similar in all respects with the topic,
accessing database using Data Controls
In this application a user interface is designed to enter the details of the employees in a firm. The
interface of this application is an SDI form through which you can enter, update and delete data in
the database.
Creating a Database

In this application, the database is created in Microsoft Access, which is a native database of Visual Basic.

Using Data Access Objects


DAO is a collection of objects with which we can access the database. Some of the objects are workspace, database, tabledef, querydef, fields, indexes and relations. To

use DAO you should include Microsoft DAO object Library. To include DAO in the Visual Basic IDE, do the following steps.

1. From the Project menu choose References.

2. Then a dialog box will appear. From that select Microsoft DAO Object Library.

The OpenDatabase method is used to open the database. Using the OpenRecordset method the
tables can be accessed.
Then you can design the database as we discussed in the Employee Details Sample Application -
Using Data Control.
Designing The interface

The designing is almost similar with the designing of Employee Details Sample Application using
Data Control, but the only difference is that here we are not using the Data Control.
 You have five fields in the table, emptab. So five TextBoxes are needed for displaying the
data. Place five textbooks of equal size on the form and arrange them.
 Then for each textbook you need Labels to display the field name. So place five Labels on
the form.
 Then you need nine Command buttons for various operations like insertion, updation,
deletion, saving and viewing through records.
Set the properties of the controls you have placed on the form, as given below.
Property Settings

Control Name Caption/Text


Name Property property
Form frmEmpdetails Employee Details
Textbox1 txtEmpNo (empty)
Textbox2 txtEmpName (empty)
Textbox3 txtDeptNo (empty)
Textbox4 txtEmpSal (empty)
Textbox5 txtEmpAge (empty)
Label1 lblEmpNo Employee ID
Label2 lblEmpName Employee Name
Label3 lblDeptNo Department ID
Label4 lblEmpSal Salary
Label5 lblEmpAge Age
Command
cmdAdd Add
Button1

126
Command
cmdUpdate Update
Button2
Command
cmdDelete Delete
Button3
Command
cmdSave Save
Button4
Command
cmdClose Close
Button5
Command
cmdFirst First
Button6
Command
cmdPrevious Previous
Button7
Command
cmdNext Next
Button8
Command
cmdLast Last
Button9
Coding

After setting the properties of various controls, you have to connect Visual Basic to the database.
For that you have OpenDatabase and OpenRecordset functions. You have to create an instance of
the objects, Database and Recordset. The declaration should be given in the general declaration
section as follows.
Option Explicit
‘ Declaring the variables.
Dim dbEmp As Database ' Variable for the database.
Dim wspEmp As Workspace ' Variable for the workspace
Dim recEmp As Recordset ' Variable for the recordset
Dim varMode ' Variable for the mode of operation
Dim varResp ' Variable for the Response
If insertion operation is to be done, varMode will be set to “Add”. Then the operation will take place
according to that. The varResp variable is used to accept the value returned from the inputbox.
Then we have to write the following code in the Form_Load Event to open the database and
initializing the TextBoxes with the data.
Private Sub Form_Load()
' Initialize the Workspace object
Set wspEmp = DBEngine.Workspaces(0)
‘ To open the database.
Set dbEmp = wspEmp.OpenDatabase("C:\Database\empdb.MDB")
‘ To assign the recordset with the table, emptab.
Set recEmp = dbEmp.OpenRecordset("emptab", dbOpenDynaset)
‘ To check whether there is any record already.
If recEmp.EOF And recEmp.BOF Then
MsgBox "No current Record"
Exit Sub
End If
‘ To call the procedure Recset to Ctrl to assign the controls with the recordset contents.
Call Recset_Ctrl
End Sub

127
Then we have to write user procedures.
To write user procedure, go to the tools menu, select Add Procedure. Then a dialog box appears.
Give a name for the procedure, select the procedure type as sub and click OK. Then you will have
the procedure body. You can write the required code there. The following user procedures should
be written,
(a) For shifting data from text boxes to database and from database to text boxes. For these
Recset_Ctrl and Ctrl_Recset functions are written.
' Procedure for moving data from the Recordset to the controls
Public Sub Recset_Ctrl()
‘ Assigns the TextBoxes with the value of recordset
txtEmpNo = recEmp!Empno
txtEmpName = recEmp!Empname
txtEmpSal = recEmp!Salary
txtDeptNo = recEmp!Deptno
txtEmpAge = recEmp!Age
End Sub
' Procedure for moving data from the controls to the recordsets
Public Sub Ctrl_Recset()
‘ Assign the recordset with the values in the TextBoxes
recEmp!Empno = txtEmpNo
recEmp!Empname = txtEmpName
recEmp!Salary = txtEmpSal
recEmp!Deptno = txtDeptNo
recEmp!Age = txtEmpAge
End Sub
(b) Then for clearing the text boxes during addition of new record, a procedure named clear is
written.
Public Sub Clear()
‘ To clear the TextBoxes.
txtEmpNo = ""
txtEmpName = ""
txtEmpSal = ""
txtDeptNo = ""
txtEmpAge = ""
End Sub
(c) For searching a particular record in the table, while updating or inserting, to know whether the
record with particular empno exist, another user procedure named Search is written.
Public Sub Search()
‘ To move the record pointer to the first record.
recEmp.MoveFirst
‘ Loop to check whether same empno exist in the table.
Do While Not Trim(recEmp!Empno) = Trim(varResp)
recEmp.MoveNext
If recEmp.EOF Then
MsgBox "Employee with this ID doesn't exist"
Exit Sub
End If
Loop
Call Recset_Ctrl
End Sub
128
These procedures are called in other events when required.
Next, the event procedures should be written.
Insertion

First, the TextBoxes are to be cleared and the variable varMode should be set to “Add”. In the click
event of cmdAdd button code is written for these operations. The code for inserting with respect to
the varMode is written in the click event of cmdSave button.
Private Sub cmdAdd_Click()
‘ To call the procedure, clear.
Call Clear
‘ To set the cursor in the TextBox, txtEmpid.
txtEmpNo.SetFocus
‘ To set the varMode of operation to ”Add”.
varMode = "Add"
End Sub
Updation
The Empno of the record to be updated is searched using the Search procedure after getting the
value from the inputbox. Then the variable, varMode is set to “Update”. The code for updation
should be written in the click event of cmdSave button. The operation is done according to the
value of varMode.
Private Sub cmdUpdate_Click()
‘ varResp assigned the value from the InputBox.
varResp = InputBox("Enter the empno", "Updation")
If varResp=empty then
Exit sub
End if
Call Search
varMode = "Update"
End Sub
Deletion The Empno of the record to be deleted is searched using the Search procedure after
getting the value from the inputbox. Then the variable, varMode is set to “Delete”. The code for
deletion is written in the click event of cmdDelete button. The operation is done according to the
value of varMode.
Private Sub cmdDelete_Click()
varResp = InputBox("Enter the Empno", "Deletion")
If varResp=Empty then
Exit sub
End If
Call Search procedure
‘ To set the varMode of operation to “Delete”
varMode = "Delete"
End Sub
Saving the Transactions
The different operations are saved using the code written in the click event of cmdSave button. The
value of the variable, varMode, is checked and the corresponding operation is saved. The code is as
given below:
Private Sub cmdSave_Click()
' Variable for receiving the message
Dim varAct
‘ Insertion saved in this part
If varMode = "Add" Then
129
‘ Adds a new empty record to table
recEmp.AddNew
Call Ctrl_Recset
On Error GoTo Errorh
‘ Updates the record with the data from the TextBox.
recEmp.Update
MsgBox "Record saved"
Errorh:
MsgBox "Record with same Employee ID exist"
Exit Sub
ElseIf varMode = "Update" Then
‘ Updation is saved here
recEmp.Edit
Call Ctrl_Recset
recEmp.Update
MsgBox "Record Updated"
‘ Deletion is saved is here
ElseIf varMode = "Delete" Then
varAct = MsgBox("Are you sure to delete current record", vbYesNo, vbExclamation)
If varAct = vbYes Then
‘ Delete the record which the record pointer points.
recEmp.Delete
MsgBox "Record deleted"
End If
End If
End Sub
Viewing Records
The records are viewed using the code in the click event of cmdFirst, cmdLast, cmdNext,
cmdPrevious.The code is as below:
' Code for moving into first record
Private Sub cmdFirst_Click()
‘ Checks whether any record exist.
If recEmp.EOF And recEmp.BOF Then
MsgBox "No current Record"
Exit Sub
End If
‘ Record pointer is moved to the first record.
recEmp.MoveFirst
Call Recset_Ctrl
End Sub
' Code for moving into last record
Private Sub cmdLast_Click()
‘ Checks whether any record exist
If recEmp.EOF And recEmp.BOF Then
MsgBox "No current Record"
Exit Sub
End If
‘ Record pointer is moved to the last record
recEmp.MoveLast

130
Call Recset_Ctrl
End Sub
' Code for moving into next record
Private Sub cmdNext_Click()
‘ Checks whether any record exist
If recEmp.EOF And recEmp.BOF Then
MsgBox "No current Record"
Exit Sub
End If
‘ Move the record pointer to the next record
recEmp.MoveNext
If recEmp.EOF Then
MsgBox "Last Record"
‘ Move the record pointer to the last record.
recEmp.MoveLast
End If
Call Recset_Ctrl
End Sub
' Code for moving into first record
Private Sub cmdPrevious_Click()
If recEmp.EOF And recEmp.BOF Then
MsgBox "No current Record"
Exit Sub
End If
‘ Move the record pointer to the previous record.
recEmp.MovePrevious
If recEmp.BOF Then
MsgBox "First Record"
recEmp.MoveFirst
End If
Call Recset_Ctrl
End Sub
Closing the Application
' Code for Terminating the application
Private Sub cmdClose_Click()
'To terminate the program
End
End Sub
Sample Outputs
Main Window

131
Window for Updation
Type the employee number and click OK to locate the record for updation.

Window for Deletion

Type the employee number and click OK to locate the record for deletion.

Working with Other Data Bound Controls


Apart from the standard bindable controls, there are other data bound controls which have more
functionality. Some of them are,
 Data Bound List Control
 Data Bound ComboBox control
 Data Bound Grid Control
 Microsoft FlexGrid Control
The Data Bound List control can hold the entire column of a recordset. The Data Bound Grid control
can hold the entire recordset. Each row of a recordset can be represented by a row in the Data
Bound Grid Control and each column of that recordset is represented by a column in it.
To add the above bound controls to your application do the following, do the following steps:
Step 1:
Right click on the ToolBox and select the Components option.
Step 2:
The Components dialog box will appear. Select Microsoft Data Bound Grid Control, Microsoft Data
Bound List Control and Microsoft FlexGrid Control by checking the respective check boxes.
Step 3:
Close the Component Dialog Box. The chosen controls will be available in the Toolbox.
132
The properties, methods and events are similar in the case of DBList and DBcombo controls.
Using Data Bound List Control
Columns from the recordset can be viewed using the Data Bound List control. The Data Bound List
Control has the following properties,
DataSource - Used to specify the name of the Data Control to which the database is connected.
DataField - Specifies the Field selected from the recordset.
RowSource - Specifies the name of the data control to use for the list.
ListField - Specifies the field to be listed in the Data Bound List control.
RowSource and ListField property decides how the controls are used. With these four properties the
Data Bound List Box can be connected to two Data Controls which are connected to two related
tables with a common field. By setting the RowSource property to the Data Control and ListField to
the particular field the Data Bound List Control will be loaded with the particular field of the
recordset.
Data Bound List Control have a property called BoundColumn. By setting the BoundColumn with
the data in the DataField property, a relation can be established between the Data Controls. As a
Data Control that has no direct connection with the Data Bound List Control is clicked, the field
corresponding to the current record appear in the Data Bound List Control as the selected field.
Data Bound ComboBox Control
The Data Bound ComboBox control is similar to Data Bound List Control. In addition, it has an edit
box. The Data Bound ComboBox has all the properties of the Data Bound List Control namely,
DateField, DataSource, RowSource and ListField.
Data Bound Grid Control
The Data Bound Grid Control is a powerful and flexible control. This control can completely display
all the data in a recordset. The data is displayed as rows and columns. Modification, Addition, and
Deletion are possible directly form this control. Each field will be represented as a cell. Each field
can be accessed and modified by the user. The modified data will be updated to the database
instantly. If we update the data by other means, it will be reflected in the Data Bound Grid Control.
The Data Bound Grid Control can be connected with a table or recordset by specifying the
DataSource property. The DataSource property can be set with the name of the Data Control. Then
the Database Grid will have all the records in the table to which the Data Control is connected. The
functionality of the Database Grid Control depends on the following properties,
1. AllowAddnew - This property can have two values, TRUE or FALSE. By setting this property to
TRUE the addition of new records is allowed.
2. AllowUpdate - This property allows us to modify the data directly within the control if it is set to
TRUE.
3. AllowDelete - When TRUE, this property allows us to delete the current record.
4. AllowArrow - If TRUE, this property provides an arrow indicating the current record.
Microsoft FlexGrid Control
The Microsoft FlexGrid is similar to Database Grid Control. Entire records in a recordset can be
viewed using the Microsoft FlexGrid Control. The user cannot edit the displayed elements.
Modification and addition of Data is not possible directly with Microsoft FlexGrid Control.
This control is an extremely useful tool for displaying data in tabular form. It consists of cells
arranged in rows and columns. The cells can contain text or images. Each cell has it's own size. As
in the case of the Data Bound Grid Control, the Microsoft FlexGrid can be connected to the
Database by setting the DataSource property to the Data Control which in turn is connected to a
table in the Database. The data in the table can be viewed in the cells, but cannot be updated. Two
fixed cells, fixed title row and fixed title column are available in this control.
Some Common properties are Row, Column, Text and TextMatrix.
The row and column properties gives the address of a cell. Row=0 and Column=0 denotes the fixed
title column. The cells can be addressed as,
133
msgDat.Row=1, msgDat.column=1
msgDat denoting the name of the Microsoft FlexGrid Control. The value of the cell with the address
can be retrieved as follows, cellval=msgDat.Text. Then the variable, cellval will have the value of
the cell. A cell can be set with the new value as
msgDat.Text=NewValue
Using the TextMatrix property a cell can be addressed and it's value can be accessed in a single
statement as,
cellval=msgDat.TextMatrix(Row,Column)
For example,
cellval=msgDat.TextMatrix(1,1)
Here the variable cellval will be assigned the value of the first cell.
Error handing with DAO is discussed in the next topic.
Error Handling with DAO
Whenever an operation is processed by DAO, errors may be generated. For example, an ODBC call
to the database may cause an error. Whenever an error occurs, an Error object will be placed in the
error collection of the DBEngine object. When a new error occurs the Error collection is cleared and
the new Error object will be placed in the Error collection. Some DAO operations will not generate
any errors and therefore will not affect the Error collection.
For describing an error, a group of Error objects in the error collection are used. The lowest level
error will be the first Error object. The next higher level error is the second Error object. Thus, if an
ODBC error occurs during an operation the first Error object, Errors(0) will be the lowest level ODBC
error. Then the subsequent errors will contain ODBC errors returned by the various layers of ODBC.
The ODBC driver manager returns separate Error objects. The last Error object will have the DAO
error which will be displayed to the user.
The cause and source of an error can be determined by verifying the particular error in the Error
collection. Then necessary steps can be taken to avoid the consequences. The details of the error
can be had by analyzing the properties of Error object. The properties can be used as given below.
 The Description property contains the error message which will be displayed on the screen.
 The Number property contains integer value of the error constant.
 The Source property identifies the object from which the error is generated. If there are
several Error objects in the Error collection, the Source property can be used to find the
source of error generation.
 The HelpFile and HelpContext properties indicates the appropriate Microsoft Windows
help topic for the error.
If the object which caused the error does not belong to the DBEngine object, then no Error object
will be created in the Error collection. The details of such an error can be referred in that particular
object to which the object that created the error belongs.
In remote server systems errors can occur due to invalid use of the database. The database system
contains procedures to generate messages on errors. Once DAO and the Jet database engine
receive any error, regardless of the cause, the query that triggered the error will be terminated.
The messages received from ODBC and the remote server can be trapped when using QueryDef
object. The error messages generated can be trapped by code. Message trapping can be enabled
by creating a property called "LogMessages" for a specific QueryDef object. For that, the
logMessages property should be set to true.
Errors sometimes will be generated when an SQL query is executed. These errors will be stored in
the Errors collection. The error will be accessible either during break mode or at run time. There will
be documentation for some messages. Additionally, ODBC operations will generate trappable error.
While entering data into a database, the Jet Engine checks whether the data meets the standards of
the database, and gives an error message if it does not support it. For example, a data entered to a
field is out of range, then an error message will occur. A runtime error message will occur whenever
134
the design standards of the database is violated. So to prevent the runtime error, an error event
should be generated. The error event can be declared as,
Private sub Error (data error as integer, response as integer)

End Sub
Data error will have the number of the error and response is an integer which can be set in order to
handle the error in the code itself. If it is 0, then the execution will be continued. If it is 1, an error
routine will be displayed.
Self Assessment
Select the correct answer.
(1). Which is the top level object of Data Access Object model
(a) Database
(b) DBEngine
(c) TableDef
(d) User
(e) QueryDef
(2) The property ListField stands for
(a) Specifies the field to be listed from a database.
(b) Specifies the field to be listed in the Data Bound List control.
(c) Specifies the field to be listed in a ListBox.
(d) Specifies the field to be listed in a ComboBox.
(3) Which is a read only recordset.
(a) Dynaset
(b) Table
(c) Snapshot
(d) None of the above
(4) Which is a DataBound control,
(a) CommandButton.
(b) Vertical ScrollBar.
(c) Timer.
(d) CheckBox.
(e) Shape.
(5) Which is not a property used to connect database using the DataControl
(a) DatabaseName.
(b) RecordSource.
(c) RecordSet.
(d) Negotiate.
(6) Which of the following is not a property of the Error object.
(a) Description
(b) Source
(c) LogMessages
(d) HelpFile
(e) HelpContent
Workshops
1. What are the important properties of the Data Control?
2. What are the objects of DAO? Explain each.
3. Explain the architecture of DAO.
4. What are the different RecordSet types?
5. Explain how a database can be created, opened and accessed using DAO.
Exercises
135
Write a database program for inserting, updating and deleting the records of two related tables,
each having a primary key?
Chapter – 8
Workshops - Solution
1. What are the important properties of the Data Control?
The important properties of the Data Control are given below:
Database Name
This property is used to hold the name and location of the database to which connection has to be
established.

Default Cursor
The DefaultCursorType property of the Data Control determines what type of cursor is to be used.
The DefaultCursorType has three values. If it is 0, then it allows the ODBC driver to determine what
type of cursor is to be used. If it is 1, then it use the ODBC cursor library. If it is 2, then it allows the
serversidecursor, which is specially used for network based applications. A cursor is a mechanism
for moving within a database.

Default Type
The DefaultType property determines the type of the DataSource. If it is 1, (Use ODBC) then it
indicates to use the ODBC direct data access method. If it is 2, then the Microsoft Jet Engine is used
for accessing data.

RecordSource
This property holds the tables available in the database. You can set this property to any table you
want to connect with the application. Alternatively, you can fill it with SQL statements, which may
access multiple tables.

ReadOnly
This property is used to set the access to database as read-only.
RecordSet Type
This property defines the type of recordset to be created for data access. There are recordsets for
reading only, ones for dynamically modifying data etc.
2. What are the objects of DAO? Explain each.
The important objects in the DAO are given below:
DBEngine object is the top-level object. It contains workspaces and error objects.
The Workspace class has a number of Workspace objects. Each Workspace object has the database,
User and Group objects within it.
Each database class can have a number of database objects, which in turn have Tabledef,
Querydef, Recordset, Container and Relation objects.
The Tabledef class has a number of TableDef objects, which in turn have Field and Index classes.
Then the Index class has a number of Index objects, which in turn have the Index Field class.
The QueryDef class has a number of QueryDef objects, which in turn have Field class.
Field class has a number of Field objects, which in turn have the Parameter class.
The RecordSet and Relation classes have a number of corresponding objects, which in turn have
Field classes.

3. Explain the architecture of DAO.


The DAO Architecture contains a set of automation interfaces for the Jet Database Engine. DAO can
access Jet databases (Microsoft Access) directly, but to communicate with other databases, the
corresponding ODBC Driver is needed. The figure of the DAO Architecture is given below:
136
In the figure, the application program uses DAO to connect with the Jet Database Engine. Through
the DAO, a Microsoft Access Database can be connected. ODBC databases can also be connected
with Jet Database Engine through the ODBC drivers or interface programs.

137
4. What are the different Recordset types?

A recordset object provides a logical representation of the records in a table, or in the results of a
query. There are three types of recordset objects.

Table
This type of recordset provides access to all of the records and fields in the specified table. The
sorting order of the retrieved records is set using recordset object's Index property. The contents of
records can be updated using the Table type, but this type of recordset can reference only one
table at a time. Data access is faster, since it has a direct reference to the table.

Dynaset
The Dynaset type represents a selected (by SQL) set of records from one or more tables. The
records and fields contained in a dynaset type are specified by a query. The data can be modified in
the case of dynaset type recordset.
Snapshot
The Snapshot type recordset is similar to a dynaset type, but it is read-only. The data cannot be
updated. So you cannot use a snapshot type to modify records in a table. Snapshot type can be
used if you want only to view data or fill dropdowns from a table.
Explain how a database can be created, opened and accessed using DAO.

Chapter – 8
Workshops - Solution

1. What are the important properties of the Data Control?


The important properties of the Data Control are given below:
Database Name
This property is used to hold the name and location of the database to which connection has to be
established.

Default Cursor
The DefaultCursorType property of the Data Control determines what type of cursor is to be used.
The DefaultCursorType has three values. If it is 0, then it allows the ODBC driver to determine what
type of cursor is to be used. If it is 1, then it use the ODBC cursor library. If it is 2, then it allows the
serversidecursor, which is specially used for network based applications. A cursor is a mechanism
for moving within a database.

Default Type
The DefaultType property determines the type of the DataSource. If it is 1, (Use ODBC) then it
indicates to use the ODBC direct data access method. If it is 2, then the Microsoft Jet Engine is used
for accessing data.

RecordSource
This property holds the tables available in the database. You can set this property to any table you
want to connect with the application. Alternatively, you can fill it with SQL statements, which may
access multiple tables.

ReadOnly
This property is used to set the access to database as read-only.
RecordSet Type

138
This property defines the type of recordset to be created for data access. There are recordsets for
reading only, ones for dynamically modifying data etc.
2. What are the objects of DAO? Explain each.
The important objects in the DAO are given below:
DBEngine object is the top-level object. It contains workspaces and error objects.
The Workspace class has a number of Workspace objects. Each Workspace object has the database,
User and Group objects within it.
Each database class can have a number of database objects, which in turn have Tabledef,
Querydef, Recordset, Container and Relation objects.
The Tabledef class has a number of TableDef objects, which in turn have Field and Index classes.
Then the Index class has a number of Index objects, which in turn have the Index Field class.
The QueryDef class has a number of QueryDef objects, which in turn have Field class.
Field class has a number of Field objects, which in turn have the Parameter class.
The RecordSet and Relation classes have a number of corresponding objects, which in turn have
Field classes.

3. Explain the architecture of DAO.


The DAO Architecture contains a set of automation interfaces for the Jet Database Engine. DAO can
access Jet databases (Microsoft Access) directly, but to communicate with other databases, the
corresponding ODBC Driver is needed. The figure of the DAO Architecture is given below:

In the figure, the application program uses DAO to connect with the Jet Database Engine. Through
the DAO, a Microsoft Access Database can be connected. ODBC databases can also be connected
with Jet Database Engine through the ODBC drivers or interface programs.
4. What are the different Recordset types?
A recordset object provides a logical representation of the records in a table, or in the results of a
query. There are three types of recordset objects.
Table
This type of recordset provides access to all of the records and fields in the specified table. The
sorting order of the retrieved records is set using recordset object's Index property. The contents of
records can be updated using the Table type, but this type of recordset can reference only one
table at a time. Data access is faster, since it has a direct reference to the table.
Dynaset
The Dynaset type represents a selected (by SQL) set of records from one or more tables. The
records and fields contained in a dynaset type are specified by a query. The data can be modified in
the case of dynaset type recordset.

Snapshot

139
The Snapshot type recordset is similar to a dynaset type, but it is read-only. The data cannot be
updated. So you cannot use a snapshot type to modify records in a table. Snapshot type can be
used if you want only to view data or fill dropdowns from a table.
Explain how a database can be created, opened and accessed using DAO.

140
Exercise - Solution

Write a database program for inserting, updating and deleting the records of two related tables,
each having a primary key?
Solution
Using the following steps we can solve this problem.
Step1:
Create a database with name Student and make the relationships as given in the Exercises of
chapter 7. This database contains three tables which are related to each other. The batch table has
the primary key batch_code and the student table has the roll_number as the primary key. These
tables can be related using the field, batch_code. In this relation the batch_code in the student
table refers the batch_code in the batch table.
Step 2:
Create a Standard EXE project.
Step 3:
In the project menu, select the references item, and in the references dialog box, check the
checkbox for the Microsoft DAO 3.6 Object Library.
Designing of the MDI Form:
Step1:
Add One MDI form into the project. Then add the menus and make settings as shown below:

Control Name Name Property Text/ Caption property


MDI From FrmMain School Details
Menu MnuDetails Details
Menu Item1 MnuStudent Student Details
Menu Item2 MnuMarks Marks Details
Menu Item3 MnuBatch BatchDetails
Menu MnuExit Exit

141
Step 2:
Then write the code for each menu item in order to show the corresponding forms:
Private Sub mnuStudent_Click()
frmStudent.Show
End Sub
Private Sub mnuBatch_Click()
frmBatch.Show
End Sub
Private Sub mnuMarks_Click()
frmMarks.Show
End Sub
Private Sub mnuExit_Click()
End
End Sub

Designing the Batch Form.


Step 1:
Add one form to the existing project then make the following settings:

Control Name Name Property Text/Caption property


Form frmBatch Batch Details
Combo Box cboBatchCode (empty)
Text1 txtBatchName (empty)
Text2 txtStudents (empty)
Label1 lblBatchCode Batch Code
Label2 lblBatchName Student Name
Label3 lblStudents Number of Students
Command Button1 cmdAdd &Add
Command Button2 cmdEdit &Edit
Command Button3 cmdDelete &Delete
Command Button4 cmdClose &Close

142
Step 2:
Write the following code in the general declaration section:
Option Explicit
Dim dbStudent As Database ‘Code for creating the Database Object
Dim recBatch As Recordset ‘Code for creating the Recordset Object

Step 3:
Write the following code in the Form load event.

Private Sub Form_Load()


On Error GoTo errd
Set dbStudent=OpenDatabase(“d:\studentdb”)
Set recBatch = dbStudent.OpenRecordset("batch", dbOpenDynaset)

cboBatchCode.Clear
recBatch.MoveFirst
Do While Not recBatch.EOF
cboBatchCode.AddItem recBatch!batch_code
recBatch.MoveNext
Loop
Exit Sub
errd:
MsgBox Err.Description
Unload Me
End Sub

Step 4:
Write the following code in the Click event of the Combo Box.
Private Sub cboBatchCode_Click()
recBatch.MoveFirst
Do While Not recBatch.EOF
If recBatch!batch_code = cboBatchCode Then
txtBatchCode = recBatch!batch_code
txtBatchName = recBatch!batch_name
txtStudents=recBatch!no_of_stud
Exit Sub
End If
recBatch.MoveNext
Loop
End Sub

Step 5:
Write the following code in the Click event of the cmdAdd button.
Private Sub cmdAdd_Click()
If cboBatchCode <> "" Then
On Error GoTo ErrHan
recBatch.AddNew
recBatch!batch_code = Trim(cboBatchCode)
recBatch!batch_name = Trim(txtBatchName)
recBatch!no_of_stud = Trim(txtStudents)
143
recBatch.Update
End If
ErrHan:
If Err.Number = "3022" Then
MsgBox "Record exist with same batch code", vbInformation
End If
End Sub

Step 6:
Write the following code in the Click event of the cmdDelete button.
Private Sub cmdDelete_Click()
recBatch.MoveFirst
Do While Not recBatch.EOF
If recBatch!batch_code = cboBatchCode Then
recBatch.Delete
Exit Sub
End If
recBatch.MoveNext
Loop
End Sub

Step 7:
Write the following code in the Click event of the cmdEdit button.
Private Sub cmdEdit_Click()
recBatch.MoveFirst
Do While Not recBatch.EOF
If recBatch!batch_code = cboBatchCode Then
recBatch.Edit
recBatch!batch_code = Trim(cboBatchCode)
recBatch!batch_name = Trim(txtBatchName)
recBatch!no_of_stud = Trim(txtStudents)
recBatch.Update
Exit Sub
End If
recBatch.MoveNext
Loop
End Sub

Step 8:
For closing the Student form write the following code in the Click event of cmdClose button.
Private Sub cmdClose_Click()
Unload Me
End Sub

144
Designing the Student Form

Step 1:
Add one form into the project then make the settings as shown below.

Control Name Name Property Text/Caption


property
Form FrmStudent Student Details
Combo Box cboRollNumber (empty)
Text1 txtStudName (empty)
Text2 txtBatchCode (empty)
Label1 lblRollNumber Roll Number
Label2 lblStudentName Student Name
Label3 lblBatchCode Batch Code
Command Button1 cmdAdd &Add
Command Button2 cmdEdit &Edit
Command Button3 cmdDelete &Delete
Command Button4 cmdClose &Close

Step 2:
Then write the following code in the declaration section.

Option Explicit
Dim dbStudent As Database ‘Code for creating the Database Object
Dim recStudent As Recordset ‘ Code for creating the Recordset object

Step 3:
Write the following code in the Form load event.

Private Sub Form_Load()


'On Error GoTo errd
Set dbStudent =OpenDatabase(“d:\studentdb.mdb”)
Set recStudent = dbStudent.OpenRecordset("student", dbOpenDynaset)
cboRollNumber.Clear
recStudent.MoveFirst
Do While Not recStudent.EOF
cboRollNumber.AddItem recStudent!roll_number
recStudent.MoveNext
Loop
Exit Sub
errd:
MsgBox Err.Description
Unload Me
End Sub

Step 4:
Write the following code in the Click event of the Combo Box.
Private Sub cboRollNumber_Click()
recStudent.MoveFirst
145
Do While Not recStudent.EOF
If recStudent!roll_number = cboRollNumber Then
txtBatchCode = recStudent!batch_code
txtStudName = recStudent!stud_name
Exit Sub
End If
recStudent.MoveNext
Loop
End Sub

Step 5:
Write the following code in the Click event of the cmdAdd button.
Private Sub cmdAdd_Click()
If cboRollNumber <> "" Then
On Error GoTo ErrHan
recStudent.AddNew
recStudent!roll_number = Trim(cboRollNumber)
recStudent!stud_name = Trim(txtStudName)
recStudent!batch_code= Trim(txtBatchCode)
recStudent.Update
Exit Sub
ErrHan:
MsgBox Err.Description
End If
End Sub

Step 6:
Code to be written in the Click event of cmdClick botton.
Private Sub cmdEdit_Click()
recStudent.MoveFirst
Do While Not recStudent.EOF
If recStudent!roll_number = cboRollNumber Then
recStudent.Edit
recStudent!roll_number = Trim(cboRollNumber)
recStudent!stud_name = Trim(txtStudName)
recStudent! batch_code = Trim(txtBatchCode)
recStudent.Update
Exit Sub
End If
recStudent.MoveNext
Loop
End Sub

146
Step 7:
Code to be written in the Click event of cmdDelete button.
Private Sub cmdDelete_Click()
recStudent.MoveFirst
Do While Not recStudent.EOF
If recStudent! roll_number = cboRollNumber Then
recStudent.Delete
Exit Sub
End If
recStudent.MoveNext
Loop
End Sub

Step 8:
Then write the code for closing the Form in the Click event of cmdClose button.

Private Sub cmdClose_Click()


Unload Me ‘ Code for unloading the form.
End Sub

147
Designing the Marks form:
Step 1:
Add one form to the existing project then make the following settings:

Control Name Name Property Text/Caption


property
Form FrmMarks Marks Details
Combo Box CboRollNumber (empty)
Text1 txtMarkListNumber (empty)
Text2 txtSubject1 (empty)
Text3 txtSubject2 (empty)
Text4 TxtTotal (empty)
Label1 LblRollNumber Roll Number
Label2 LblMarklistNo Mark List No:
Label3 lbl Subject1 Subject 1:
Label4 lbl Subject2 Subject 1:
Label5 lbl Total Total Marks:
Command Button1 CmdAdd &Add
Command Button2 CmdEdit &Edit
Command Button3 CmdDelete &Delete
Command Button4 CmdClose &Close

Step 2:
Then write the following code in the declaration section.

Option Explicit
Dim dbStudent As Database
Dim recMarks As Recordset

Step 3:
Write the following code in the Form load event.

Private Sub Form_Load()


'On Error GoTo errd
Set dbStudent=OpenDatabase(“d:\studentdb.mdb”)
Set recMarks = dbStudent.OpenRecordset("marks", dbOpenDynaset)
cboRollNumber.Clear
recMarks.MoveFirst
Do While Not recMarks.EOF
cboRollNumber.AddItem recMarks!roll_number
recMarks.MoveNext
Loop
Exit Sub
errd:
MsgBox Err.Description
Unload Me
148
End Sub

Step 4:
Write the following code in the Click event of the Combo Box.
Private sub cboRollNumber_Click()
recMarks.MoveFirst
Do While Not recMarks.EOF
If recMarks!roll_number = cboRollNumber Then
txtMarkListNumber = recMarks!marklist_no
txtSubject1 = recMarks!subject1
txtSubject2 = recMarks!subject1
txtTotal = recMarks!total_marks
Exit Sub
End If
recMarks.MoveNext
Loop
End sub

Step 5:
Write the following code in the Click event of the cmdAdd button.
Private Sub cmdAdd_Click()
If cboRollNumber <> "" Then
recMarks.AddNew
recMarks!roll_number = Trim(cboRollNumber)
recMarks!marklist_no = Trim(txtMarkListNumber)
recMarks!subject1= Trim(txtSubject1)
recMarks!subject2= Trim(txtSubject2)
recMarks! total_marks= Trim(txtTotal)
recMarks.Update
End If
End Sub
Step 6:
Write the following code in the Click event of the cmdDelete button.
Private Sub cmdDelete_Click()
recMarks.MoveFirst
Do While Not recMarks.EOF
If recMarks!batch_code = cboRollNumber Then
recMarks.Delete
Exit Sub
End If
recMarks.MoveNext
Loop
End Sub

Step 7:
Write the following code in the Click event of the cmdEdit button.
Private Sub cmdEdit_Click()
recMarks.MoveFirst
Do While Not recMarks.EOF
If recMarks!batch_code = cboRollNumber Then
149
recMarks.Edit
recMarks!roll_number = Trim(cboRollNumber)
recMarks!marklist_no = Trim(txtMarkListNumber)
recMarks!subject1= Trim(txtSubject1)
recMarks!subject2= Trim(txtSubject2)
recMarks! total_marks = Trim(txtTotal)
Exit Sub
End If
recMarks.MoveNext
Loop
End Sub

Step 8:
For closing the Student form write the following code in the Click event of cmdClose button.
Private Sub cmdClose_Click()
Unload Me
End Sub

Sample Outputs
MDI Form

150
Batch Details Form

Students Details Form

Marks Details Form

151
CHAPTER 9
ODBC Architecture
Open Database Connectivity (ODBC) is an interface that allows applications to access data in any
database having an ODBC driver. ODBC allows the application to be independent of the database
management system. ODBC gives an application access to any database which uses the ODBC
standard.
The ODBC architecture has four components. They are given below:
1. Application Component: This is the user's application which performs the processing and calls
ODBC functions for retrieving the results.
2. Driver Manager: This will load the corresponding driver for the application's use.
3. Driver: This is a piece of software that processes ODBC function calls from the application,
submits the commands to the specific database (data source) and returns the results to the
application.
4. Data source: This contains the data that the user wants to access.
The ODBC Architecture is shown below:

The application is the program through which the user interacts with a data source. The application
will call ODBC functions for performing its needs. An application can provide a variety of features
other than the ODBC interface, including mail, spreadsheet capabilities, online transaction
processing, report generation, and much more.
The main purpose of the Driver Manger is to load the ODBC Drivers which perform the functions for
initializing and working with the Data sources.
The Driver Component is used for establishing a connection and submitting requests to the data
source. It translates data to other formats and returns the results to the application.
The Data source contains the data that the user wants to access. The main functionality of the data
source is that it is capable of performing the Query requests from the user and returning the
values.
The ODBC is the most accepted data accessing technology and is used to access any type of
relational databases in the computer world.
In the next topic, you can learn how to program using ODBC.

152
Programming with ODBC
Before starting the detailed study of ODBC, you should know a little about ODBC Data Sources. A
data source is identification of a database. Each data source must be given a unique name when it
is registered. Through this name, the data is accessed by the application. If you want to use a
particular database in your application then you must register that database. For registering
database you can use the ODBC administrator.
The steps for registering a database is given below:
Step 1:
From the Control Panel select the ODBC icon. It will display a dialog named ODBC
administrator as shown below:

Step 2:
Click on the Add button in the dialog. Next, the Create New Data Source dialog will be displayed.
It is shown below.

153
Step 3:
Select the Driver for which you want to set up a data source. Then press the Finish Button.
Step 4:
Then it will show another dialog box for the corresponding Database Setup. Here you enter a
unique name for the database and the necessary information. Then press OK. The ODBC Microsoft
Access Setup dialog box is shown below.

Step 5:
Now you have created the DataSource for the corresponding database.
After registering the Database you want to create a front end for the application. For that just take
the Employee Details sample from the previous chapter and follow the steps given below to
implement connection using ODBC.
Step 1:
Register the Empdb in the ODBC driver using the select button.
Step 2:
Start the Visual Basic IDE and create a new Standard EXE Project.
Step 3:
Make an Interface and set the Properties the same as you did in the Employee Details Sample using
DAO. In this sample you will have an interface with five TextBoxes and nine Command Buttons.
Step 4:
A connection should be established with the database. For that we want to write code for making a
connection with a database. The first step in editing the code is to create an object for the
Recordset, Workspace, and Connection. For that, declare the variables in the corresponding
datatypes as shown below:
'Declaring the WorkSpace
Dim wspEmp As Workspace
'Declaring the Connection
Dim conEmp As Connection
'Declaring the Recordset
Dim recEmp As Recordset
'Variable for declaring the mode of operation
Dim varMode
'Variable for declaring the Response
Dim varResp
154
Here we are declaring the wspEmp as a Workspace object, conEmp as a Connection object, recEmp
as a Recordset object.
Step 5:
In the Form_Load event, the following code should be written:
'Setting the value of Workspace
Set wspEmp = CreateWorkspace("odbc", "admin", "", dbUseODBC)
'Setting the Value of Database
Set conEmp =
wspEmp.OpenConnection("new",dbDriverNoPrompt,False,"odbc;dsn=employee;uid= ;pwd=")
'Setting the value of Recordset
Set recEmp = conEmp.OpenRecordset("emptab", dbOpenDynaset)
The meaning of this code is given below:
The code, Set wspEmp = CreateWorkspace("odbc", "admin", "", dbUseODBC) is for creating a new
Workspace object and assigning its value to the wspEmp object.
The method CreateWorkspace is used for create a new workspace object and has the following
syntax.
Set workspace = CreateWorkspace(name, user, password, type)
Where
workspace is the variable that represents the Workspace object.
name is the object that uniquely names the Workspace object.
user is the name of the owner of the workspace and a string.
password is the password and is a string.
type is the constant that indicates the type of the workspace.
The code, Set conEmp =
wspEmp.OpenConnection("new",dbDriverNoPrompt,False,"odbc;dsn=employee;uid= ;pwd=") is for
opening a Connection to an ODBC DataSource.
The OpenConnection method has the following syntax:
Set connection = workspace.OpenConnection (name, options, readonly, connect)
Where
connection is the variable that represents the Connection object.
workspace is the variable that represents the Workspace object.
Name is a string expression that represents the Connection Name.
options is the name of a Variant that sets various options for the connection. Here we made that
option as dbDriverNoPrompt. This means that the ODBC Driver Manager uses the connection string
provided in dbName and connect to the database and there will be no need of entering the data at
runtime.
The code, Set recEmp = conEmp.OpenRecordset("emptab", dbOpenDynaset) is for creating a new
Recordset object.
Step 6:
If the Connection is OK then we can start connecting the database with each of the controls. For
that, we can use the following functions
Public Sub Recset_Ctrl()
'Function for Assigning values to each control from the Recordset.
txtEmpNo = recEmp!Empno
txtEmpname = recEmp!Empname
txtEmpSal = recEmp!Salary
txtDeptNo = recEmp!Deptno
txtEmpAge = recEmp!Age
End Sub

155
The above function is used for transferring the data from the Recordset to the Controls. The
following function is used for transferring data form the Controls to the Recordset.

Public Sub Ctrl_Recset()


'Function for transferring values from the Recordset to the Controls.
recEmp!Empno = txtEmpNo
recEmp!Empname = txtEmpName
recEmp!Salary = txtEmpSal
recEmp!Deptno = txtDeptNo
recEmp!Age = txtEmpAge
End Sub
Step 7:
Then for clearing the TextBoxes during addition of new record, a procedure named Clear is written.

Public Sub Clear()


‘ To clear the TextBoxes.
txtEmpNo = ""
txtEmpName = ""
txtEmpSal = ""
txtDeptNo = ""
txtEmpAge = ""
End Sub
Step 8:
For searching a particular record in the table, while updating or inserting, to know whether the
record with particular Empno exist, another user procedure named Search is written.
Public Sub Search()
‘ To move the record pointer to the first record.
recEmp.MoveFirst
‘ Loop to check whether same empno exist in the table.
Do While Not Trim(recEmp!Empno) = Trim(varResp)
recEmp.MoveNext
If recEmp.EOF Then
MsgBox "Employee with this ID doesn't exist"
Exit Sub
End If
Loop
Call Recset_Ctrl
End Sub
Step 9:
Now you can write the code for each command button for carrying out the operations for Addition,
Deletion, Updating, Saving and Moving to First, Last, Next and Previous records.
Addition
First you have to clear the TextBoxes. Then set the variable varMode to “Add”. In the click event of
cmdSave button, write the code for saving the data with respect to varMode.
Private Sub cmdAdd_Click()
‘ To call the procedure, clear.
Call Clear
‘ To set the cursor in the TextBox, txtEmpid.
txtEmpNo.SetFocus
‘ To set the varMode of operation to ”Add”.
156
varMode = "Add"
End Sub
Updating
The Empno of the record to be updated is searched using the Search procedure after getting the
value from the inputbox. Then the variable, varMode is set to “Update”. The code for updating
should be written in the click event of cmdUpdate button. The operation is done according to the
value of varMode.
Private Sub cmdUpdate_Click()
‘ varResp assigned the value from the InputBox.
varResp = InputBox("Enter the empno", "Updation")
If varResp=empty then
Exit sub
End if
Call Search
varMode = "Update"
End Sub
Deletion
The Empno of the record to be deleted is searched using the Search procedure after getting the
value from the inputbox. Then the variable, varMode is set to “Delete”. The code for deletion is
written in the click event of cmdDelete button. The operation is done according to the value of
varMode.

Private Sub cmdDelete_Click()


varResp = InputBox("Enter the Empno", "Updation")
If varResp=empty then
Exit sub
End If
Call Search procedure
‘ To set the varMode of operation to “Delete”
varMode = "Delete"
End Sub
Saving the Transactions
The different operations are saved using the code written in the click event of cmdSave button. The
value of the variable, varMode, is checked and the corresponding operation is saved. The code is as
given below:
Private Sub cmdSave_Click()
'Declare variable for accepting the return value of the MsgBox function
Dim varAct
‘ Insertion saved in this part
If varMode = "Add" Then
‘ Adds a new empty record to table
recEmp.AddNew
Call Ctrl_Recset
On Error GoTo Errorh
‘ updates the record with the data from the TextBox.
recEmp.Update
MsgBox "Record saved"
Errorh:
MsgBox "Record with same Employee ID exist"
Exit Sub
157
ElseIf varMode = "Update" Then
‘ Updation is saved here
recEmp.Edit
Call Ctrl_Recset
recEmp.Update
MsgBox "Record Updated"
‘ Deletion is saved is here
ElseIf varMode = "Delete" Then
varAct = MsgBox("Are you sure to delete current record", vbYesNo, vbExclamation)
If varAct = vbYes Then
‘ Delete the record which the record pointer points.
recEmp.Delete
MsgBox "Record deleted"
End If
End If
End Sub
Viewing Records
The records are viewed using the code in the click event of cmdFirst, cmdLast, cmdNext,
cmdPrevious. The code is as shown below:
' Code for moving into first record
Private Sub cmdFirst_Click()
‘ Checks whether any record exist.
If recEmp.EOF And recEmp.BOF Then
MsgBox "No current Record"
Exit Sub
End If
‘ Record pointer is moved to the first record.
recEmp.MoveFirst
Call Recset_Ctrl
End Sub
' Code for moving into last record
Private Sub cmdLast_Click()
‘ Checks whether any record exist
If recEmp.EOF And recEmp.BOF Then
MsgBox "No current Record"
Exit Sub
End If
‘ Record pointer is moved to the first record
recEmp.MoveLast
Call Recset_Ctrl
End Sub
' Code for moving into next record
Private Sub cmdNext_Click()
‘ Checks whether any record exist
If recEmp.EOF And recEmp.BOF Then
MsgBox "No current Record"
Exit Sub
End If
‘ Move the record pointer to the next record
recEmp.MoveNext
158
If recEmp.EOF Then
MsgBox "Last Record"
‘ Move the record pointer to the last record.
recEmp.MoveLast
End If
Call Recset_Ctrl
End Sub
' Code for moving into first record
Private Sub cmdPrevious_Click()
If recEmp.EOF And recEmp.BOF Then
MsgBox "No current Record"
Exit Sub
End If
‘ Move the record pointer to the previous record.
recEmp.MovePrevious
If recEmp.BOF Then
MsgBox "First Record"
recEmp.MoveFirst
End If
Call Recset_Ctrl
End Sub
Closing the Application
' Code for Terminating the application
Private Sub cmdClose_Click()
'To terminate the program
End
End Sub

159
Sample Outputs
Main Window

Window for Updation


Type the employee number and click OK to locate the record for updation.

Window for Deletion


Type the employee number and click OK to locate the record for deletion.

A comparison of ODBC and DAO is given in the next topic.

Comparing DAO and ODBC


It is very difficult to say which is best, DAO or ODBC. DAO provides more flexibility than ODBC and
the techniques of ODBC is yet hidden to most of the database programmers in the world.
For the Data Definition Language (DDL) and Data Manipulation Language (DML), programming with
DAO is more flexible than ODBC. DAO and ODBC can be compared as
1. The DAO and ODBC, both have the Database Manipulation Language (DML) support, but for
ODBC the Database Definition Language (DDL) support is possible only through direct ODBC
calls.
2. Both can access the ODBC data sources and Microsoft Access data sources.
3. ODBC is available in 16-bit and 32-bit but the DAO is not available in 16-bit.
4. ODBC is optimal for any data source which has a Driver and the DAO is optimal for the
Microsoft Access Database.
5. DAO is has Database Compaction capability but ODBC does not.
6. DAO has updatable joins but ODBC does not.
160
Both are widely accepted and each has its own advantages and disadvantages.
If you create a client-server application, you are actually using the ODBC. The Data Access Object
will also use the ODBC with enhanced functionality. The ODBC also is an industry standard. So
ODBC is the most popular database connecting technology.
Error handling with ODBC is discussed in the next topic.
Error Handling with ODBC
The Error handling in ODBC is an important topic. An error handler may be defined as a routine for
trapping and responding to errors in your application.
There are several aspects involved in error handling. They are,
1. Setting up the error handler
2. Determining the cause of the error
3. informing the user what happened
4. Trying to resolve the problem
Setting up the error handler involves writing an error-handling routine that responds to all possible
errors. Then add the handler to the procedure where the anticipated errors can occur.
In Visual Basic - ODBC Interface, there are four places where the actual error may occur. They are
a. In Visual Basic
b. ODBC driver Manager
c. ODBC driver
d. Data Source
There are 49 tradable errors detected between the Visual Basic and Data source through ODBC
connection. These errors are denoted with error numbers 600 to 648. You can write your own
routine in your application to divert the control when one of these occurs.
You can handle the errors by using the On Error statements. That is, you can make the code as On
Error...GoTo some error handling routines.
For example, you can write a code for moving the record pointer to the first position in an ODBC
based connection as:
Private Sub cmdMoveFirst_Click()
' If Error then go to error description
On Error GoTo Errh
recEmp.MoveFirst
Errh:
If Err = 3021 Then MsgBox (Err.Description)
End If
End Sub
This code means that when the recordset has been moved to the first position and if there is an
error (That is, there may not be any records in the database), then the control should move to the
error handling routine. In the error handling routine, it will check the Error object and if it is 3021,
then give a message box of the error description.
Self Assessment
Select the correct answer.
(1). Which of the following is a component of ODBC architecture?
(a) Application
(b) Driver Manager
(c) Driver
(d) Data Source
(e) All of these
(2) By clicking the ODBC icon
(a) Control panel will be displayed.
(b) ODBC Administrator will be displayed.
161
(c) Create New Data Source dialog will be displayed.
(d) ODBC Microsoft Access Setup dialog will be displayed.
(3) Which of the following is wrong?
(a) ODBC does not support Data Manipulation Language.
(b) Microsoft Access can be accessed using ODBC.
(c) ODBC does not have database Compaction.
(d) ODBC does not allow updatable joins.
(4) While using ODBC, an error may not occur in
(a) Visual Basic
(b) ODBC driver Manager
(c) ODBC driver
(d) Data Source
(e) None of these
Workshops
1. What are the components of ODBC architecture?
2. Explain the steps for registering a database.
3. Explain Error handling with ODBC.
Exercises
Create an application to analyze the details of students in a school, make the database connection
using ODBC.
Chapter - 9
Workshops - Solution

1. What are the components of ODBC architecture?


The ODBC architecture has four components. They are given below:
a. Application Component: This is the user's application which performs the processing and calls
ODBC functions for retrieving the results.
b. Driver Manager: This will load the corresponding driver for the application's use.
c. Driver: This is a piece of software that processes ODBC function calls from the application,
submits the commands to the specific database (data source) and returns the results to the
application.
d. Data source: This contains the data that the user wants to access.
The ODBC Architecture is shown below:

The application is the program through which the user interacts with a data source. The application
will call ODBC functions for performing its needs. An application can provide a variety of features
other than the ODBC interface, including mail, spreadsheet capabilities, online transaction
processing, report generation, amd much more.
The main purpose of the Driver Manger is to load the ODBC Drivers which perform the functions for
initializing and working with the Data sources.
The Driver Component is used for establishing a connection and submitting requests to the data
source. It translates data to other formats and returns the results to the application.

162
The Data source contains the data that the user wants to access. The main functionality of the data
source is that it is capable of performing the Query requests from the user and returning the
values.
2.
Explain the steps for registering a database.
The steps for registering a database is given below:
Step 1:
From the Control Panel select the ODBC icon. It will display a dialog named ODBC
administrator as shown below:

Step 2:
Click on the Add button in the dialog. Next, the Create New Data Source dialog will be displayed.
It is shown below.

Step 3:
Select the Driver for which you want to set up a data source. Then press the Finish Button.
Step 4:
Then it will show another dialog box for the corresponding Database Setup. Here you enter a
unique name for the database and the necessary information. Then press OK. The ODBC Microsoft
Access Setup dialog box is shown below.

163
Step 5:
Now you have created the DataSource for the corresponding database.
3. Explain Error handling with ODBC.
In Visual Basic - ODBC Interface, there are four places where the actual error may occur. They are
a. In Visual Basic
b. ODBC driver Manager
c. ODBC driver
d. Data Source
There are 49 tradable errors detected between the Visual Basic and Data source through ODBC
connection. These errors are denoted with error numbers 600 to 648.

164
Exercise - Solution
Create an application to analyze the details of students in a school, make the database connection
using ODBC.

Solution
Using the following steps we can solve this problem:

Step1:
Create a database Student and make the relationships as given in the chapter 7 Exercises.

Step 2:
Register the ODBC database and make the DSN. (For Registering the ODBC database please use
the steps in the section 9.2)

Step 3:
Create a Standard EXE project and make the of the Form1 as shown below.

Designing of the MDI Form:


Step1:
Add One MDI form into the project then add the menus and make settings as shown below:

Control Name Name Property Text/ Caption


property
MDI From FrmMain School Details
Menu MnuDetails Details
Menu Item1 MnuStudent Student Details
Menu Item2 MnuMarks Marks Details
Menu Item3 MnuBatch BatchDetails
Menu MnuExit Exit

Step 2:
Then write the code for each menu item in order to show the corresponding forms:
Private Sub mnuStudent_Click()
frmStudent.Show
End Sub
Private Sub mnuBatch_Click()
frmBatch.Show
End Sub

Private Sub mnuMarks_Click()


frmMarks.Show
End Sub

Private Sub mnuExit_Click()


End
End Sub

Designing the Student Form

165
Step 1:
Add one Form into the project then make the settings as shown below:

Control Name Name Property Text/Caption property


Form FrmStudent Student Details
Combo Box cboRollNumber (empty)
Text1 txtStudName (empty)
Text2 txtBatchCode (empty)
Label1 lblRollNumber Roll Number
Label2 lblStudentName Student Name
Label3 lblBatchCode Batch Code
Command Button1 cmdAdd &Add
Command Button2 cmdEdit &Edit
Command Button3 cmdDelete &Delete
Command Button4 cmdClose &Close

166
Step 2:
Then write the following code in the declaration section

Option Explicit
Dim wspStudent As Workspace ‘ Code for creating the workspaca
Dim conStudent As Connection ‘ Code for creating the Connection object
Dim recStudent As Recordset ‘ Code for creating the Recordset object

Step 3:
Write the following code in the Form load event

Private Sub Form_Load()


'On Error GoTo errd
Set wspStudent = CreateWorkspace("odbc", "", "", dbUseODBC)
Set conStudent = wspStudent.OpenConnection("Student", dbDriverNoPrompt, True,
"ODBC;database=studentdb;uid=;pwd=;dsn=Student")
Set recStudent = conStudent.OpenRecordset("student", dbOpenDynaset)
cboRollNumber.Clear
recStudent.MoveFirst
Do While Not recStudent.EOF
cboRollNumber.AddItem recStudent!roll_number
recStudent.MoveNext
Loop
Exit Sub
errd:
MsgBox Err.Description
Unload Me
End Sub

Step 4:
Write the following code in the Click event of the Combo Box.
Private Sub cboRollNumber_Click()
recStudent.MoveFirst
Do While Not recStudent.EOF
If recStudent!roll_number = cboRollNumber Then
txtBatchCode = recStudent!batch_code
txtStudName = recStudent!stud_name
Exit Sub
End If
recStudent.MoveNext
Loop
End Sub

Step 5:
Write the following code in the Click event of the cmdAdd button.
Private Sub cmdAdd_Click()
If cboRollNumber <> "" Then
recStudent.AddNew
recStudent!roll_number = Trim(cboRollNumber)
recStudent!stud_name = Trim(txtStudName)
167
recStudent!batch_code= Trim(txtBatchCode)
recStudent.Update
End If
End Sub
Step 6:
Write the following code in the Click event of the cmdEdit button
Private Sub cmdEdit_Click()
recStudent.MoveFirst
Do While Not recStudent.EOF
If recStudent!roll_number = cboRollNumber Then
recStudent.Edit
recStudent!roll_number = Trim(cboRollNumber)
recStudent!stud_name = Trim(txtStudName)
recStudent! batch_code = Trim(txtBatchCode)
recStudent.Update
Exit Sub
End If
recStudent.MoveNext
Loop
End Sub

Step 7:
Write the following code in the Click event of the cmdDelete
Private Sub cmdDelete_Click()
recStudent.MoveFirst
Do While Not recStudent.EOF
If recStudent! roll_number = cboRollNumber Then
recStudent.Delete
Exit Sub
End If
recStudent.MoveNext
Loop
End Sub

Step 8:
Then write the code for closing the Form in the Click event of cmdClose button.

Private Sub cmdClose_Click()


Unload Me ‘ Code for unloading the form.
End Sub
Designing the Batch Form:
Step 1:
Add one form to the existing project then make the following settings:

Control Name Name Property Text/Caption


property
Form frmBatch BatchDetails
Combo Box cboBatchCode (empty)
Text1 txtBatchName (empty)
Text2 txtStudents (empty)
168
Label1 lblBatchCode Batch Code
Label2 lblBatchName Student Name
Label3 lblStudents Number of Students
Command Button1 cmdAdd &Add
Command Button2 cmdEdit &Edit
Command Button3 cmdDelete &Delete
Command Button4 cmdClose &Close

Step 2:
Write the following code in the general declaration section:
Option Explicit

Dim wspStudent As Workspace


Dim conStudent As Connection
Dim recBatch As Recordset

Step 3:
Write the following code in the Form load event
Private Sub Form_Load()

'On Error GoTo errd


Set wspStudent = CreateWorkspace("odbc", "", "", dbUseODBC)
Set conStudent = wspStudent.OpenConnection("Student", dbDriverNoPrompt, True,
"ODBC;database=studentdb;uid=;pwd=;dsn=Student")
Set recBatch = conStudent.OpenRecordset("batch", dbOpenDynaset)
cboBatchCode.Clear
recBatch.MoveFirst
Do While Not recBatch.EOF
cboBatchCode.AddItem recBatch!batch_code
recBatch.MoveNext
Loop
Exit Sub
errd:
MsgBox Err.Description
Unload Me
End Sub

Step 4:
Write the following code in the Click event of the Combo Box.
Private Sub cboBatchCode_Click()
recBatch.MoveFirst
Do While Not recBatch.EOF
If recBatch!batch_code = cboBatchCode Then
txtBatchCode = recBatch!batch_code
txtBatchName = recBatch!batch_name
txtStudents=recBatch!no_of_stud
Exit Sub
End If
recBatch.MoveNext
Loop
169
End Sub

Step 5:
Write the following code in the Click event of the cmdAdd.
Private Sub cmdAdd_Click()
If cboBatchCode <> "" Then
recBatch.AddNew
recBatch!batch_code = Trim(cboBatchCode)
recBatch!batch_name = Trim(txtBatchName)
recBatch!no_of_stud = Trim(txtStudents)
recBatch.Update
End If
End Sub

Step 6:
Write the following code in the Click event of the cmdDelete button.
Private Sub cmdDelete_Click()
recBatch.MoveFirst
Do While Not recBatch.EOF
If recBatch!batch_code = cboBatchCode Then
recBatch.Delete
Exit Sub
End If
recBatch.MoveNext
Loop
End Sub

Step 7:
Write the following code in the Click event of the cmdEdit button.
Private Sub cmdEdit_Click()
recBatch.MoveFirst
Do While Not recBatch.EOF
If recBatch!batch_code = cboBatchCode Then
recBatch.Edit
recBatch!batch_code = Trim(cboBatchCode)
recBatch!batch_name = Trim(txtBatchName)
recBatch!no_of_stud = Trim(txtStudents)
recBatch.Update
Exit Sub
End If
recBatch.MoveNext
Loop
End Sub
Step 8:
For closing the Student form write the following code in the Click event of cmdClose button.
Private Sub cmdClose_Click()
Unload Me
End Sub
Designing the Marks form:
Step 1:
170
Add one form to the existing project then make the following settings:

Control Name Name Property Text/Caption property


Form frmMarks Marks Details
Combo Box cboRollNumber (empty)
Text1 txtMarkListNumber (empty)
Text2 txtSubject1 (empty)
Text3 txtSubject2 (empty)
Text4 txtTotal (empty)
Label1 lblRollNumber Roll Number:
Label2 lblMarklistNo Mark List No:
Label3 lblSubject1 Subject 1:
Label4 lblSubject2 Subject 1:
Label5 lblTotal Total Marks:
Command Button1 cmdAdd &Add
Command Button2 cmdEdit &Edit
Command Button3 cmdDelete &Delete
Command Button4 cmdClose &Close

Step 2:
Then write the following code in the declaration section

Option Explicit
Dim wspMarks As Workspace
Dim conMarks As Connection
Dim recMarks As Recordset

Step 3:
Write the following code in the Form load event.

Private Sub Form_Load()


'On Error GoTo errd
Set wspMarks = CreateWorkspace("odbc", "", "", dbUseODBC)
Set conMarks = wspMarks.OpenConnection("Student", dbDriverNoPrompt, True,
"ODBC;database=studentdb;uid=;pwd=;dsn=Student")
Set recMarks = conMarks.OpenRecordset("marks", dbOpenDynaset)

cboRollNumber.Clear
recMarks.MoveFirst
Do While Not recMarks.EOF
cboRollNumber.AddItem recMarks!roll_number
recMarks.MoveNext
Loop
Exit Sub
errd:
MsgBox Err.Description
Unload Me
End Sub

171
Step 4:
Write the following code in the Click event of the Combo Box.
recMarks.MoveFirst
Do While Not recMarks.EOF
If recMarks!roll_number = cboRollNumber Then
txtMarkListNumber = recMarks!marklist_no
txtSubject1 = recMarks!subject1
txtSubject2 = recMarks!subject1
txtTotal = recMarks!total_marks
Exit Sub
End If
recMarks.MoveNext
Loop

Step 5:
Write the following code in the Click event of the cmdAdd button.
Private Sub cmdAdd_Click()
If cboRollNumber <> "" Then
recMarks.AddNew
recMarks!roll_number = Trim(cboRollNumber)
recMarks!marklist_no = Trim(txtMarkListNumber)
recMarks!subject1= Trim(txtSubject1)
recMarks!subject2= Trim(txtSubject2)
recMarks! total_marks = Trim(txtTotal)
recMarks.Update
End If
End Sub

Step 6:
Write the following code in the Click event of the cmdDelete button.
Private Sub cmdDelete_Click()
recMarks.MoveFirst
Do While Not recMarks.EOF
If recMarks!batch_code = cboRollNumber Then
recMarks.Delete
Exit Sub
End If
recMarks.MoveNext
Loop
End Sub
Step 7:
Write the following code in the Click event of the cmdEdit button.
Private Sub cmdEdit_Click()
recMarks.MoveFirst
Do While Not recMarks.EOF
If recMarks!batch_code = cboRollNumber Then
recMarks.Edit
recMarks!roll_number = Trim(cboRollNumber)
recMarks!marklist_no = Trim(txtMarkListNumber)
recMarks!subject1= Trim(txtSubject1)
172
recMarks!subject2= Trim(txtSubject2)
recMarks! total_marks = Trim(txtTotal)
Exit Sub
End If
recMarks.MoveNext
Loop
End Sub

Step 8:
For closing the Student form write the following code in the Click event of cmdClose button.
Private Sub cmdClose_Click()
Unload Me
End Sub

Sample Outputs
MDI Form

173
Batch Details Form

Students Details Form

Marks Details Form

CHAPTER 10
Understanding RDO
The Remote Data Object (RDO) and Remote Data Control (RDC) are used for data access. With RDO
and the RemoteData control, ODBC data sources can be accessed directly. Using Remote Data
Objects is flexible, efficient and fast.
RDO have the following features:
1. Queries can be executed and can use any number of resultsets.

174
2. Stored procedures can be executed like queries. The result of execution can be returned to the
resultset.
3. Ability to use simple as well as complex resultsets. Resultsets can be created with or without
cursors.
4. Both data manipulation and data definition queries can be executed.
5. Ability to control the number of rows to be returned or processed in a particular processing
session.
6. The messages and errors produced by the remote record source can be processed without
affecting the execution of the query.
7. Ability to prevent the database operation from blocking the application, when lengthy queries are
executed.
RDO has the a hierarchical object model. There is one base object. All other objects belongs to that
object. Each object is a member object of a collection and each object contains a set of other
objects. The first object is not a member of any collection.
Figure of RDO Object Model

rdoEngine
This is the base object which is created automatically as RDO access the database.
rdoError
This is the object used to handle errors and messages that occur during data access.
rdoEnvironment
It defines the set of connections already opened and allocated, provides the mechanism for
simultaneous transactions and handles data manipulation operations. The default object,
rdoEnvironment will be automatically created.
rdoConnection
Used to make connection to a database in a remote data source.
rdoTable
Used to refer the Table in an already connected database.
rdoResultset
175
The result of an executed query is stored in this object. It consists of a set of rows of the result.
rdoColumn
Used to refer data in a specified column of a particular table.
rdoQuery
Used to define queries for manipulation of data. The queries may include one or more parameter.
rdoParameter
Defines the parameter used in the queries defined in the rdoQuery object.
With the exception of the rdoEngine object, each of these objects is maintained in an associated
collection. When RDO is initialized on first access, RDO automatically creates an instance of the
rdoEngine, the default rdoEnvironments(0).
A comparison of RDO with DAO and ADO is done in the next topic.
Comparing RDO with DAO and ADO
Comparing RDO with DAO
Remote Data Objects are similar to Data Access Objects which access the database through the jet
database engine. With RDO, queries can be executed, resultsets or cursors can be created and you
can process the results from the query.
Remote Data Controls can be used to design a database application in the same way you do with
the data control.
An application using DAO and Data Controls can be converted to use RDO and Remote Data Control
by doing some changes. RDO is developed mainly for relational Client-Server databases and
therefore depends on the data source to process the queries, create resultset and get the result of
the query. The data objects are created with the resultsets and cursors returned from the ODBC
driver.
For accessing an ODBC database, there is no need for converting the DAO based application to RDO
based. It is possible to access database directly using DAO with the ODBCDirect feature of the jet
database engine.
Remote Data Objects uses the terms rows and columns to refer to a Table instead of the terms
records and fields in DAO. The result of a query is returned in the form of resultsets which can have
zero or more records. RDO supports cursorless resultset, but DAO requires a cursor to access the
data.
In DAO, the index object and seek method are used for fast access and to locate a particular record.
RDO has no objects and methods of this kind, since it has different approach in managing the index
and search processes.
RDO does not have the ability to control referential integrity, security and schema modifications
because the database system itself has the utilities and tools for this purpose. DAO can manage the
referential integrity, security and modification of database with built-in methods and properties.
RDO uses complex stored procedures to manage and manipulate the database which is not
possible with DAO. By running native SQL statements like create table or execute action queries
RDO can manipulate the database.

Comparing RDO with ADO


ADO is not compatible with other database applications. To convert other data access application to
an ADO application, many statements will need to be changed to the ADO syntax. In some cases
you can convert with a few changes, while in other cases most of the code will need to be
converted to ADO syntax.
ADO is similar to RDO in it's functionality. ADO's object model is different from the object model
used by DAO and RDO. ADO has fewer objects, but more properties, methods, and events. ADO has
no objects such as rdoEngine and rdoEnvironment objects. ADO cannot access data through ODBC
data sources the same way as RDO. ADO can work with ODBC databases through the ODBC OLE DB
service provider.
176
DAO and RDO have objects which are derived from the base objects, thus forming a hierarchy of
objects. The functionality of RDO and DAO are concentrated in these objects. When comparing ADO
to RDO, the objects, properties, methods and events do not directly match up. Though ADO objects
are hierarchical, they are also created outside the scope of hierarchy. ADO doesn't support all the
functionality of the DAO. ADO has RDO style functionality and can interact with OLE DB data
source.
How to use remote data control is discussed in the next topic.
Using Remote Data Control
The Remote Data control is designed to connect data bound controls to the data source similar to
the Data control. The difference between the two controls is that the Remote Data control uses
RDO to connect to the ODBC driver manager and the Data control uses DAO to connect to the Jet
database engine, which can connect to native databases. The Data control can also connect
indirectly to RDO by using the ODBCDirect interface.
To use the Remote Data control, it should be added to Visual Basic Toolbox. To add the Remote
Data Control to the toolbox, click Components in the Project menu. In the Components dialog box
click the Controls tab and select the "Microsoft Remote Data Control 2.0" check box.
The data bound controls cannot access data from the database without Remote Data control, Data
control or its equivalent. Remote data access can be done with the Remote Data Control without
writing any code. The data access can be done by setting the properties of the RDC. However for
complex data access operations, Remote Data controls will not be enough. With more complex
applications, RDO code is normally used. RDO code gives you more flexible and efficient data
access. Those data access operations which cannot be done by setting the properties of the
Remote Data Control can be done by writing RDO code.
For accessing data, the data bound controls can be bound with the Remote Data Control. By setting
the required properties the controls can be connected to the RDC. The bounded controls can
display one or more columns or a set of rows. All operations can be performed by the control on the
current row.

By clicking the navigation buttons in the Remote Data control, the data in the bound controls
changes to the next record. The data in the table can be viewed using the navigation keys.
You can view the sample application using remote data control by clicking here.
In the next topic, you can learn how to program with remote data objects.
Employee Details Sample - Using Remote Data Control
The Employee Details sample using Data Control, discussed in Chapter 10, can be modified to use
Remote Data Control instead of Data Control. You can use the same database, empdb. The user
interface can be modified by placing Remote Data Control instead of the Data Control.

Remote Data Control can be placed on the Form by following the steps given below,
1.
From the Project menu choose Components.
2.
Then select the Controls tab in the Components dialog box that appears.
3.
Select the Microsoft Remote Data Control.
4.
Click OK.
Set the properties of the Remote Data Control as shown below.
Step 1:
Add the Remote Data Control on the form. Then select its properties. Then the properties page will
appear as shown below:

177
Step 2:
Set the DataSourceName property with your Data Source name. (Before setting this you should
create an ODBC driver as specified in the topic, Programming with ODBC.)
Step 3:
Set the SQL as,
"Select * from emptab"

Step 4:
Set the DataSourceName and the DataField name of each control.
Step 5:
You can see the property settings of the controls as shown below:
Property Settings
Arrange the controls with names as given below:
Control Name Caption/Text DataSour
DataField
Name Property Property ce
Employee
Form frmEmpdetails (empty) (empty)
Details
Remote
Data rdcEmp (empty) (empty) (empty)
Control
Textbox1 txtEmpNo (empty) rdcEmp Empno
Textbox2 txtEmpName (empty) rdcEmp Empname
Textbox3 txtDeptNo (empty) rdcEmp Depno
Textbox4 txtEmpSal (empty) rdcEmp Salary
Textbox5 txtEmpAge (empty) rdcEmp Age
Label1 lblEmpNo Employee ID (empty) (empty)
Employee
Label2 lblEmpName (empty) (empty)
Name
Label3 lblDeptNo Department ID (empty) (empty)
Label4 lblEmpSal Salary (empty) (empty)
178
Label5 lblEmpAge Age (empty) (empty)
Command
cmdAdd Add (empty) (empty)
Button1
Command
cmdUpdate Update (empty) (empty)
Button2
Command
cmdDelete Delete (empty) (empty)
Button3
Command
cmdSave Save (empty) (empty)
Button4
Command
cmdClose Close (empty) (empty)
Button5
Command
cmdFirst First (empty) (empty)
Button6
Command
cmdPrevious Previous (empty) (empty)
Button7
Command
cmdNext Next (empty) (empty)
Button8
Command
cmdLast Last (empty) (empty)
Button9
Coding
Place all the necessary controls in the form. Set the properties of the controls as discussed above.
Declare the global variables in the General Declaration.
Option Explicit
' Declaring Global Variables
Dim varMode
Dim varResp

Then we have to write user procedures.


To write user procedure, go to the tools menu, select Add Procedure. Then a dialog box appears.
Give a name for the procedure, select the procedure type as sub and click OK. Then write the
required code in the procedure body. The user procedures are given below,
User Procedures

(a) For clearing the text boxes during addition of new record a procedure named Clear have to be written.

Public Sub Clear()

' Clears the TextBoxes

txtEmpNo = ""

txtEmpName = ""

txtEmpSal = ""

txtDeptNo = ""

txtEmpAge = ""

End Sub

(b) For searching a particular record in the table while updating or inserting, to know whether the
record with particular empno exist, another user procedure, Search have to be written.
Public Sub Search()

' Move record pointer to first record

rdcEmp.Resultset.MoveFirst

179
' Finds the record with same Employee_id

Do While Not Trim(rdcEmp.Resultset!Empno) = Trim(varResp)

rdcEmp.Resultset.MoveNext

If rdcEmp.Resultset.EOF Then

MsgBox "Employ with this ID does not exist"

Exit Sub

End If

Loop

End Sub

These procedures are called in other events when required.


Next the event procedures should be written.
Event Procedures
Insertion operation

First, the TextBoxes are to be cleared and the variable varMode should be set to “Add”. In the click event of cmdAdd button code is written for these operations. The code

for inserting with respect to the varMode is written in the click event of cmdSave button.

Private Sub cmdAdd_Click()

' To add new record

rdcEmp.Resultset.AddNew

' Calls Clear function to clear TextBoxes

Call Clear

' To set the focus on txtEmpNo

txtEmpNo.SetFocus

' Sets varMode to "Add"

varMode = "Add"

End Sub

Updation Operation

The Empno of the record to be updated is searched using the Search procedure after getting the
value from the inputbox. Then the variable, varMode is set to “Update”. The code for updation is
written in the click event of cmdSave button. The operation is done according to the varMode set.
Private Sub cmdUpdate_Click()

' Set the varMode variable to Update

varMode = "Update"

varResp = InputBox("Enter the empno", "Updation")

If varResp = Empty Then

Exit Sub

End If

' Calls the Search Procedure

Call Search

End Sub

Deletion Operation
The empno of the record to be deleted is searched using the Search procedure after getting the value using the inputbox. Then the variable, varMode is set to “Delete”. The

code for deletion is written in the click event of cmdSave button. The operation is done according to the varMode set.

Private Sub cmdDelete_Click()

' Sets varMode to Delete

varMode = "Delete"

varResp = InputBox("Enter the empno", "Deletion")

' Checks whether varResp has value or not

If varResp = Empty Then

' To exit from the procedure

Exit Sub

180
End If

' Calls the user procedure, Search

Call Search

End Sub

Saving of Transactions

The different operations are saved using the code written in the click event of cmdSave button. The value of the variable, varMode, is checked and the corresponding

operation is saved. The code is as given below:

Private Sub cmdSave_Click()


Dim varAct
' Checks the varMode of operation is adding of records
If varMode = "Add" Then
MsgBox "record saved"
' Checks the varMode of operation is adding of records
ElseIf varMode = "Update" Then
' Set the record for editing
rdcEmp.Resultset.Edit
'To update changes in the record
rdcEmp.Resultset.Update
MsgBox "Record Updated"
ElseIf varMode = "Delete" Then
varAct = MsgBox("Are you sure to delete current record", vbYesNo+ vbExclamation,
"Deletion")
If varAct= vbYes Then
' To delete the current record
rdcEmp.Resultset.Delete
MsgBox "Record deleted"
End If
End If
End Sub
Viewing Records
The records are viewed using the code in the click event of cmdFirst, cmdLast, cmdNext, cmdPrevious. The code is as below:

Private Sub cmdFirst_Click()

' Check whether any record exist

If rdcEmp.Resultset.EOF And rdcEmp.Resultset.BOF Then

MsgBox "No current Record"

Exit Sub

End If

' Move the record pointer to the First record

rdcEmp.Resultset.MoveFirst

End Sub

Private Sub cmdLast_Click()

' Check whether any record exist

If rdcEmp.Resultset.EOF And rdcEmp.Resultset.BOF Then

MsgBox "No current Record"

Exit Sub

End If

' Move the record pointer to the Last record

rdcEmp.Resultset.MoveLast

End Sub

181
Private Sub cmdNext_Click()

' Check whether any record exist

If rdcEmp.Resultset.EOF And rdcEmp.Resultset.BOF Then

MsgBox "No current Record"

Exit Sub

End If

' Move the record pointer to the Next record

rdcEmp.Resultset.MoveNext

If rdcEmp.Resultset.EOF Then

MsgBox "Last Record"

rdcEmp.Resultset.MoveLast

End If

End Sub

Private Sub cmdPrevious_Click()


If rdcEmp.Resultset.EOF And rdcEmp.Resultset.BOF Then
MsgBox "No current Record"
Exit Sub
End If
' Move the record pointer to the Previous record
rdcEmp.Resultset.MovePrevious
If rdcEmp.Resultset.BOF Then
MsgBox "First Record"
rdcEmp.Resultset.MoveFirst
End If
End Sub
Closing the Application
Private Sub cmdClose_Click()

' To terminate the program

End

End Sub

Save and run the application.


Sample Outputs
Main Window

Window for Updation


Type the employee number and click OK to locate the record for updation.

182
Window for Deletion
Type the employee number and click OK to locate the record for deletion.

Programming with Remote Data Objects


RDO collections consist of objects which can be used for creating and manipulating components of
a database system. A collection includes a number of objects. RDO consists of Objects and
Collections having properties that describe the characteristics of database components and
methods that you use to manipulate them. Relationships can be created among objects and
collections.
The rdoEngine Object
The remote data source is represented by the rdoEngine object. When a reference is made to an
RDO object the rdoEngine will be created. It is the top level object in the hierarchy of RDO objects
and contains all the other objects remaining in the hierarchy. Once it is created, there is no need to
create rdoEngine object again. Since it is not a member of any collection, it is not owned by any
other objects. Data source parameters can be set and rdoEnvironment objects can be created using
rdoEngine object.
The RDOEngine can be shared among applications that are using it. The default properties are not
shared among the applications. Each application has it's own default properties which does not
affect other applications that use RDO.
Creating an rdoEnvironment Object
The default rdoEnvironment object is rdoEnvironments(0). For most applications, the default
environment is enough. But for applications which have complex functions and scope and need a
separate username and password facility, more rdoEnvironment objects should be created. The
rdoCreateEnviroinment method can be used to create additional rdoEnvironments. So an
rdoEnvironment can be created which accepts a unique user name and password. If you try to
create another with the same user name, an error will occur.
The default rdoEnvironments(0), which will be created at the time when RDO is referenced, will
have name property set to "Default_Environment" and the username and password will be zero
length strings.
Any new rdoEnvironment will be appended to the rdoEnvironment collection automatically when
they are created if a unique name is given. If the name property is set to a zero length string, the
new rdoEnvironment will not be appended to the rdoEnvironment collection.
A connection object can be created with the user name Admin, and password hello as follows,
Dim En As rdoEnvironment

Set En = rdoCreateEnvironment("", "Admin", "hello")

183
In the OpenConnection method the username and password should be specified in the connect
argument to make connection. If the username and password are not specified in the connect
argument they are taken from the rdoEnvironment.
Connecting to a Remote Database
To access the data in a database, a connection to the Data Source should be established. The RDO
can be connected to any remote database such as Oracle or SQL Server or any other database
having an ODBC driver.
RDO can be connected to the database in many ways. As in the case of DAO, you will use RDO to
manage the connection operations for your application. But RDO doesn't actually manage the
connection. RDO will internally pass the parameter to the SQLDriverConnect function and then call
the SQLDisconnect function to close the collection.
A database can be connected using any of the following methods according to your needs.
By setting the properties of the Remote Data Control, a connection can be established. Then the
rdoConnection object can be created by setting it's connection property.
For example,
Dim rdoCon as new rdoConnection
rdoCon.Connect = "UID=;PWD=;Database=Employee;" _ & "Server=SEQUEL; Driver={SQL
Server}" _ & "DSN=`';"
Where, UID is the user Id and PWD is the password of the user. DSN represents the data source
name.
Declare the rdoConnection object. Make the connection Using OpenConnection method of the
rdoEnvironment object.

Use the Dim statement and create rdoConnection object, set its properties, and use the
EstablishConnection method.
The methods defined are for different purposes. According to your requirement, any of the methods
can be used.
The above methods are used to make a link to a data source as Oracle and SQL server. But to
establish a connection, you must provide a network location of the data source, the driver type and
number of optional parameters used.

Once you have established a connection, you can


 Execute a query using the OpenResultset method, which returns one or more resultsets.
 Execute an action query by using the execute method .
 Create an rdoQuery object. Using this object a parameter query or stored procedure can be
executed.
 Show stored procedures as methods of the rdoConnection object by defining a query.
 Set the ActiveConnection property to associate the rdoConnection object with a specific
rdoResultset object.
 Add the rdoConnection object to a particular rdoConnection using the Add method.
 Remove an rdoConnection object from the RDO connections collection using the Remove
method.
Updating RDO Data
All rdoResultsets are not updatable. There may be rdoResultsets that can't be updated using a
cursor but can be updated using an action query. A cursor can be used to update a table if the
conditions below are met:
 The table must have a unique index to use as a unique row identifier for a cursor. If the table
does not have a unique key, it becomes one of the returned errors for the table being not
updated.
 The remote database system must have direct update permission to tables.
184
 If the result set is a complex multitable join, it is possible to update a join. But updating all
joins is not possible and depends upon the complexity of the join.
 Not all cursors allow updating.
 The data can be updated if the user has permission to update it.
 Even when the updatable property of the rdoResultset and rdoColumn objects are set to
true, the resultset or a specific column may not be updatable.
Updating Data Using Stored Procedures
Though the cursor is created for easily updating a table, some administrators will not allow this
update method because of security problems. Referential Integrity and business rules can be taken
care in the database itself. In a database, triggers or other mechanisms can be used to validate the
data and do the operations automatically. This way, the application would not have to take care of
the complexities in validation and confirmation of referential integrity.
Updating a base table and other operations using RDO cursors will use independent update
operations. This is a relatively complex approach for database work since in each application, this
process will need to be repeated. If you choose to do your database work this way, when the
business rules or constraints on the data changes, each application would then need to be rebuild
and recompiled. This approach is less productive on developers time.
The overhead of each application doing the database integrity work can be avoided by writing
stored database procedures and triggers for updating the data. If database procedures are written
for updating data, the part regarding the referential integrity and business rules, need to be
changed in the database procedure only. There is no need to change each application that shares
the database. This will be an advantage for large database systems which have a large number of
users. The need for security will be higher since the changes are actually done in the database
server itself.
Updating through the WillUpdateRows Event
While using a cursor, RDO also permits executing a stored procedure to update the database.
Stored procedures can be written according to the user requirements. A stored procedure can be
written for the WillUpdateRows event to perform the update.
If the resultset is not been set to batch mode, the WillUpdateRows event will be fired for each call
to the update method. If the resultset is in batch mode, the WillUpdateRows will be fired by the
RDO only when the BatchUpdate method is executed.
The success or failure of WillUpdateRows can be denoted by setting the ReturnCode argument of
the event. The ReturnCode argument can be set with the following values.

ReturnCode Denotes

Update operation was successful. Columns are


rdUpdateSuccessful
marked as updated.

Update operation was successful, but with some


rdUpdateWithCollisions
collisions

rdUpdateFailed Update operation was not successful.

RDO notifies if other handlers exist and updates the


rdUpdateNotHandled
data if none are present.

Updating Data Sources Using Cursors


If the database does not support any referential integrity or rules, the RdoResultset cursor can be
used to update the data in a database. Care should be taken to deal with row and page lock
conflicts, the loss of a connection, update conflicts, etc.
185
Data can be changed in the rdoResultset as given below,
1. Position the row which should be updated.

2. Activate the row to be modified using Edit method. The data in the row is transferred to the temporary row buffer.

3. Assign new values to the columns that you need to be modified. Address the temporary row buffer by addressing the rdoResultset.

4. After changing all columns use update method to save the row buffer to the data source. The new column values replace the current row in the database. The

LastModified property will have the bookmark to the modified row.

Cancelling an Edit

The changes made can be canceled before the update takes place. The changes will be committed
only if the update command is used. The changes can be discarded as shown below,
 Shift the row pointer to the next row.
 Refresh the current row by using the Move method with argument 0.
 In the WillUpdate event, set the Cancel argument to True.
 Undo the transaction using the RollBack method.
After the edit, the current row pointer is positioned to the row modified — which might be located
at the end of the rdoResultset. To revisit the row that was just changed, use the bookmark provided
in the LastModified property.
Performing Addition and Deletion of rows in rdoResultset

New rows can be added to the rdoResultset and hence can add row to a base table. There should be access permission to add rows to the table.

New row can be added to the Resultset as follows,


1. Create a temporary row to add as new row. Give the values in the columns of the newly created row.

2. Save the row using the Update method.

After adding new record, the record pointer will be moved to the row before the just created row. To
move the current pointer to the newly created row use the last modified Bookmark.
The deleting of rows is also possible from the resultsets if the permission for deletion exists in the
database.
To delete row from the rdoResultset do the following steps,
1. Position to the row to be deleted using any method.

2. Delete the row from cursor and database using the delete method.

After deleting a row the current position pointer should be repositioned to another record. Once a
row is deleted, the current row is no longer valid, so you must reposition the pointer to a valid row
in the rdoResultset.
Modifying with RDO Action Queries
Using the Execute method, the Edit, Update, AddNew, Delete and Update operation can be done.
SQL statements such as UPDATE, INSERT or DELETE can be used to modify the database without
using RDO. If the data source has the ability to support multistatement operations, more complex
SQL statements can be used. The Execute method cannot be used to execute queries that return
rows.
You can see the sample application using remote data object by clicking here.
In the next topic, you can learn how to build rdoResultsets.
Employee Details Sample - Using RDO
The Employee Details sample using DAO, discussed in Chapter 8, can be modified to use Remote
Data Objects instead of DAO. You can use the same database, empdb. The user interface can be
modified by placing Remote Data Object instead of the Data Control. Then add the "Microsoft
Remote Data Objects 2.0" in the new project by following the steps below,
1. In the Project Menu, Choose References.
2. Check the "Microsoft Remote Data Objects 2.0" CheckBox in the reference Dialog box which
will be displayed.
3. Click OK.
After designing the User Interface and Database, the code can be designed. The properties of the
controls can be set, as done in the DAO sample.
186
The variables that have to be used in the entire program can be declared in the General Declaration
Section as follows,
' Declaring the connection object
Dim conEmp As rdoConnection
' Declaring the resultset
Dim resEmp As rdoResultset
' Declaring string for assigning SQL Query

Dim varSqlStat As String

Dim varMode

Dim varResp

The varMode variable is declared to use as a variable mode for separate operations. If insertion
operation is to be done, varMode will be set to “Add”. The varResp variable is used to accept the
value returned from the InputBox.
The object variables can be set with values to connect to the database. The code can be written in
the Form_Load event. Before that an ODBC driver should be created with the DataSourceName
"Employee". ODBC driver can be created as specified in ODBC Programming.
Private Sub Form_Load()
Set conEmp=rdoEnvironments(0).OpenConnection("Employee", rdDriverNoPrompt)
varSqlStat="Select * From emptab"
Set resEmp=conEmp.OpenResultSet(varSqlStat, rdOpenKeySet, rdConcurValues)
' To check whether any record exist
If resEmp.EOF And resEmp.BOF Then
MsgBox "No current Record"
Exit Sub
End If
Call Resset_Ctrl
End Sub
Here the rdDriverNoPrompt parameter is given in the OpenConnection method to avoid prompting
the user to give the DataSourceName in run time. The rdOpenKeySet is given in the OpenResultSet
method for allowing both forward and backward access of records in the Resultset. The
rdConcurValues parameter is given in the OpenResultSet method for allowing operations on the
Resultset.
Then you have to write user procedures.
User Procedures
To write user procedure, go to the tools menu, select Add Procedure. Then a dialog box appears.
Give a name for the procedure, select the procedure type as sub and click OK. Then you will have
the procedure body. You can write the required code there. The following user procedures should
be written,
(a) For shifting data from text boxes to database and from database to text boxes the Resset_Ctrl
and Ctrl_Resset functions are written.
Public Sub Resset_Ctrl()
‘ To assign the values of the record to the display controls.
txtEmpNo = resEmp!Empno
txtEmpname = resEmp!Empname
txtEmpsal = resEmp!Salary
txtDeptNo = resEmp!Deptno
txtEmpage = resEmp!Age
End Sub
Public Sub Ctrl_Resset()
‘ To assign the values of the TextBoxes
187
resEmp!Empno = txtEmpNo
resEmp!Empname = txtEmpName
resEmp!Salary = txtEmpSal
resEmp!Deptno = txtDeptNo
resEmp!Age = txtEmpAge
End Sub
(b) Then for clearing the text boxes during addition of new record a procedure named clear is
written.
Public Sub Clear()
‘ To clear the TextBoxes.
txtEmpNo = ""
txtEmpname = ""
txtEmpSal = ""
txtDeptNo = ""
txtEmpAge = ""
End Sub
(c) For searching a particular record in the table while updating or inserting to know whether the
record with particular empid exist another user procedure ,Search is written.
Public Sub Search()
‘ To move the record pointer to the first record.
resEmp.MoveFirst
‘ Loop to check whether same empno exist in the table.
Do While Not Trim(resEmp!empno) = Trim(varResp)
resEmp.MoveNext
If resEmp.EOF Then
MsgBox "Employ with this ID doesn't exist"
Exit Sub
End If
Loop
Call Resset_Ctrl
End Sub
These procedures are called in other events when required.
Next the event procedures should be written.
Event Procedures
Insert Operation
First, the TextBoxes are to be cleared and the variable varMode should be set to “Add”. In the click
event of cmdAdd button code is written for these operations. The code for inserting with respect to
the varMode is written in the click event of cmdSave button.
Private Sub cmdAdd_Click()
‘ To call the procedure, clear.
Call Clear
‘ To set the cursor in the TextBox, txtEmpNo.
txtEmpNo.SetFocus
‘ To set the varMode of operation to ”Add”.
varMode = "Add"
End Sub
Update Operation
The empid of the record to be updated is searched using the Search procedure after getting the
value using the inputbox. Then the variable, varMode is set to “Update”. The code for updation is
written in the click event of cmdSave button. The operation is done according to the varMode set.
188
Private Sub cmdUpdate_Click()
‘ varResp is assigned the value from the InputBox.
varResp = InputBox("Enter the empno", "Updation")
If varResp=empty then
Exit sub
End if
Call search
varMode = "Update"
End Sub

189
Delete Operation.
The empno of the record to be deleted is searched using the Search procedure after getting the
value using the inputbox. Then the variable, varMode is set to “Delete”. The code for deletion is
written in the click event of cmdSave button. The operation is done according to the varMode set.
Private Sub cmdDelete_Click()
' Set the varMode as "Delete"
varResp = InputBox("Enter the empno", "Deletion")
If varResp=Empty then
Exit sub
End If
Call Search
‘ To set the varMode of operation to “Delete”
varMode = "Delete"
End Sub
Saving the Transactions
The different operations are saved using the code written in the click event of cmdSave button. The
value of the variable, varMode, is checked and the corresponding operation is saved. The code is as
given below:
Private Sub cmdSave_Click()
Dim varAct
‘ Inserted data is saved in this part
If varMode = "Add" Then
‘ Adds a new empty record to table
resEmp.AddNew
Call Ctrl_Resset
On Error GoTo Errhan
‘ Updates the record with the data from the TextBox.
resEmp.Update
MsgBox "record saved"
Exit Sub
Errhan:
MsgBox "Record with same Employee ID exist"
Exit Sub
ElseIf varMode = "Update" Then
‘ Updated data is saved here
resEmp.Edit
Call Ctrl_Resset
resEmp.Update
MsgBox "Record Updated"
‘ Deletion is saved is here
ElseIf varMode = "Delete" Then
varAct = MsgBox ("Are you sure to delete current record", vbYesNo, vbExclamation)
If varAct = vbYes Then
‘ Delete the record which the record pointer points.
resEmp.Delete
MsgBox "Record deleted"
End If
End If
End Sub

190
Viewing Records
The records are viewed using the code in the click event of cmdFirst, cmdLast, cmdNext,
cmdPrevious. The code is as below:
Private Sub cmdFirst_Click()
‘ Checks whether any record exist.
If resEmp.EOF And resEmp.BOF Then
MsgBox "No current Record"
Exit Sub
End If
‘ Record pointer is moved to the first record.
resEmp.MoveFirst
Call Resset_Ctrl
End Sub

Private Sub cmdLast_Click()


‘ Checks whether any record exist
If resEmp.EOF And resEmp.BOF Then
MsgBox "No current Record"
Exit Sub
End If
‘ Record pointer is moved to the Last record
resEmp.MoveLast
Call Resset_Ctrl
End Sub

Private Sub cmdNext_Click()


‘Checks whether any record exist
If resEmp.EOF And resEmp.BOF Then
MsgBox "No current Record"
Exit Sub
End If
‘ Move the record pointer to the next record
resEmp.MoveNext
If resEmp.EOF Then
MsgBox "Last Record"
‘ Move the record pointer to the last record.
resEmp.MoveLast
End If
Call Resset_Ctrl
End Sub
Private Sub cmdPrevious_Click()
If resEmp.EOF And resEmp.BOF Then
MsgBox "No current Record"
Exit Sub
End If
‘ Move the record pointer to the previous record.
resEmp.MovePrevious
If resEmp.BOF Then
MsgBox "First Record"
‘ Move the record pointer to the first record.
191
resEmp.MoveFirst
End If
Call Resset_Ctrl
End Sub
Closing the Application
Private Sub cmdClose_Click()
' To terminate the program
End
End Sub
Save and run the application.
Sample Outputs
Main Window

Window for Updation


Type the employee number and click OK to locate the record for updation.

Window for Deletion


Type the employee number and click OK to locate the record for deletion.

Building rdoResultsets
The RDO resultset object can be created independent of the Remote Data Control using code. It is
possible to access the columns of the resultset using bound controls by assigning the newly created
resultset object to the Remote Data Control's resultset property. The resultset property of the
Remote Data Control is available only at run time which can be set using code. Then using the
Refresh method any existing result of the Remote Data Control is discarded.
192
In procedures, the properties and methods of the rdoConnection and rdoResultset objects can be
used. Remote Data Control can create resultset objects using the properties Environment,
Connection and RowsetSize which are expressed.
For example, to move the rdoResultset to the next row the MoveNext method of an rdoResultset
object can be used. To invoke the method of the rdoResultset created by a Remote Data Control,
code can be written as,
Remote Data Control name.resultset.MoveNext
RdoResultset should be created based on rdoQuery, if you need to execute a parameter query
using the RemoteData control. The RemoteData control's Resultset property should be set to the
newly created rdoResultset. Another rdoEnvironment can be accessed using this method.
Using RDO Resultsets
After creating the rdoResultset, data can be accessed from it and manipulated. The resultset is
created in many ways. So while using the resultset it should be created in a way that it serves the
purpose. So while using the resultsets the following things should be noted,
 The resultset should be populated as soon as created as a cursor, because the rows fetched
might be locked by the remote database engine. A resultset will be populated only after you
have positioned to its last row.
 Create the resultset according to the requirement. A cursor-less resultset will be more
efficient. RdoResultset objects that enable more features than required will not be created.
For example, you should not create an updatable resultset if any updation is not required
using the cursor.
 Use action queries with cursor-less resultsets to perform updates.
 To prevent application lockups use asynchronous operations and event procedures
whenever possible.
 For complex processing also, it is good to create a small resultset since the processing with
small resultsets is faster compared to the large one. The small resultset manages the
system resources better.
 It is always good to generate resultsets from stored procedures whenever possible, because
efficiency on the server is increased and thus making application development easier.
RDO Cursor Limits
The MaxRows property of the rdoQuery newly created, is used to set the limit for the number of
rows returned by a query. When the MaxRows property is returned by the query processor the
query execution is stopped. By this method the number of rows returned from queries can be
managed.
Data modification queries are also affected by the MaxRows property. If MaxRows is set to 10 and if
you execute a DELETE statement only 10 records will be deleted.
Determining Number of Return Rows
The RowCount property is used to determine the number of rows that can be returned in the
resultset. When this property is used, the resultset is fully populated by the RDO using the
MoveLast method. The application can be blocked when the query is completed, since the
operation is not asynchronous. If RowCount is not supported in the database it will have return
value, -1.
RDO QueryTimeout Events
Query Timeout property determines the time the query processor should work on a query. It can be
set on the rdoConnection or rdoQuery. When the Query Timeout period exceeds, the Query Timeout
event is fired. As the QueryTimeout time is reached the event is fired regardless of rdAsyncEnable
option value.
The asynchronous query operation can be continued or canceled using Event Handler. By passing
false to the cancel parameter, work can be continued and another Query Timeout period is awaited.
QueryTimeout property can be changed while another query is started.
193
When no code is written in the Query Timeout event procedure the query will be canceled by
setting StillExecuting property to false and the control returns to the application.
Error handling with RDO is discussed in the next topic.
Error Handling with RDO and Remote data Controls
Error Handling with The RDO
rdoError Object
The Remote Access Object architecture consists of the rdoEngine, rdoQuery and rdoError.
Operations using remote data access objects will generate errors and messages. Whenever an error
occurs rdoError objects will be placed in the rdoError collection of the rdoEngine object. As a new
error is generated, the existing rdoError collection will be cleared and the new rdoError object will
be placed in the rdoError collection. Some RDO operations will not generate any errors. Those
operations will not affect the rdoError object, but instead will generate trappable errors in Visual
Basic. The rdoErrors collection can be checked to find if any error has occurred and the related
cause of the error.
There will be some warning messages generated by ODBC. These messages will not create any
problem. If any informational errors are generated, the rdoEngine InfoMessage event will be
triggered. The rdoError collection can be checked inside this event.
The properties, rdoDefaultErrorThreshold or ErrorThreshold will have an error threshold value. If the
error number is below the error threshold specified in any of the above properties, then a trappable
error will be generated. Otherwise, a new rdoError object will be added to the rdoError collection.
Using rdoError object, the type and cause of the Error can be determined. The following properties
can be used for this purpose,
The Description property can be used to display the message describing the error.
The Number property can be used to determine the native data source error number.
The Source property can be used to determine the source of the error.
The SQLRetCode and SQLState properties can be used to determine the ODBC return
code and status of SQLState flags.
The Clear method can be used to remove rdoError objects from the rdoErrors collection.
Usually there will not be any need to clear the rdoError collection, since it will be get cleared
whenever a new error occurs.
The general errors are appended always at the end of the collection and the detailed errors are
placed at the top of the collection. The root cause of the error can be found out by verifying
rdoErrors(0). For describing an error, a set of rdoError objects in the rdoError collection will be
needed. The first object will represent the lowest level error and the next will represent the next
highest level error. The set of rdoError objects in the rdoErrors collection describes one error. The
first rdoError object is the lowest level error, the second is the next higher level, and so forth.
If a trappable error occurred, it can be handled by the On Error statement. Errors generated by the
ODBC middleware or by the remote server are placed in the rdoErrors collection. Whenever an
ODBC error occurs Visual Basic indicates it by using a trappable error.
Even if the error is not related to an ODBC operation, Visual Basic generates a trappable error. The
Err and Error properties can be verified using On Error handler.
Once you examine the rdoErrors collection, you can clear its contents by using the Clear method.
preventing the confusion that can occur if you subsequently check the rdoErrors collection for
errors, only to discover residual messages from an earlier operation that could have no bearing on
the current problem.
Whenever a Query is executed the Query Complete event fires regardless of whether the Query is
executed successfully or not. Then the ErrorOccured Boolean flag can be checked indicating the
success of the query. Similarly each operation will have an event, in which the ErrorOccured
Boolean flag can be used to check the success of the query.

194
The messages are handled by rdoErrors collection. For example, messages generated by a PRINT
statement are returned as rdoError objects in rdoError collection. Whenever a message is
processed an InfoMessage event is fired.
Error Handling with the Remote Data Control
While accessing a database using Remote Data Control there may arise certain situations which
cause loss of data. Some problems can arise while including empty resultsets, adding new rows,
editing and updating existing rows and handling some types of errors. Remote Data Control cannot
trap all the error conditions. These error conditions should be trapped. In big applications, some
error trapping methods should be finalized. The accessing of remote sever can have problems like
no access permission or can't execute the query load. In such cases a trappable error occurs. Then
the RDC's Error event will be created.
The RDO objects can be created and used by the Remote Data control. By setting the appropriate
properties of Remote Data Control, it can create an rdoResultset that can be manipulated in code
like any other rdoResultset. You can also create an rdoResultset in code and set the Remote Data
control’s Resultset property to point to this object.
Self Assessment
Select the correct answer.
(1) Which is the base object, created automatically as RDO accesses the database?
(a) rdoConnection
(b) rdoError
(c) rdoEngine
(d) rdoEnvironment
(e) rdoTable
(2) The object which is created as the result of the running of an execute query:
(a) rdoParameter
(b) rdoQuery
(c) rdoConnection
(d) rdoResultset
(3) Which of the following is true:
(a) The RDC connects to the Microsoft Jet Engine.
(b) The RDC uses the ODBC Direct Technology
(c) The RDC connects to the ODBC driver manager.
(d) All the above
(4) Which is the default environment object:
(a) rdoEngine
(b) rdoEnvironment
(c) rdoConnection
(d) rdoEnvironment(0)
(e) None of the above
(5) In RDO the error handling is done by the object:
(a) Error Object
(b) rdoError Object
(c) rdoEngine
(d) All the above
Workshops
1. What are the components of the RDO architecture?
2. Compare RDO with DAO and ADO.
3. Explain Error handling with RDO.
Exercises

195
Create an application of a supermarket that uses the RDO for database access. Speculate the steps
needed to convert it into an Internet based application.
Chapter – 10
Workshops - Solution
1. What are the components of the RDO architecture?
The components of the RDO architecture are given below.
rdoEngine
This is the base object, which is created automatically as RDO access the database.
rdoError
This is the object used to handle errors and messages that occur during data access.
rdoEnvironment
It defines the set of connections already opened and allocated, provides the mechanism for
simultaneous transactions and handles data manipulation operations. The default object,
rdoEnvironment will be automatically created.
rdoConnection
Used to make connection to a database in a remote data source.
rdoTable
Used to refer the Table in an already connected database.
rdoResultset
The result of an executed query is stored in this object. It consists of a set of rows of the result.
rdoColumn
Used to refer data in a specified column of a particular table.
rdoQuery
Used to define queries for manipulation of data. The queries may include one or more parameter.

196
rdoParameter
Defines the parameter used in the queries defined in the rdoQuery object.
With the exception of the rdoEngine object, each of these objects is maintained in an associated
collection. When RDO is initialized on first access, RDO automatically creates an instance of the
rdoEngine, the default rdoEnvironments(0).
2. Compare RDO with DAO and ADO.
The comparison between RDO and DAO are given below:
Remote Data Objects are similar to Data Access Objects, which access the database through the jet
database engine. With RDO, queries can be executed, resultsets or cursors can be created and you
can process the results from the query.
Remote Data Controls can be used to design a database application in the same way you do with
the data control.
An application using DAO and Data Controls can be converted to use RDO and Remote Data Control
by doing some changes. RDO is developed mainly for relational Client-Server databases and
therefore depends on the data source to process the queries, create resultset and get the result of
the query. The data objects are created with the resultsets and cursors returned from the ODBC
driver.
For accessing an ODBC database, there is no need for converting the DAO based application to RDO
based. It is possible to access database directly using DAO with the ODBCDirect feature of the jet
database engine.
Remote Data Objects uses the terms rows and columns to refer to a Table instead of the terms
records and fields in DAO. The result of a query is returned in the form of resultsets, which can have
zero or more records. RDO supports cursorless resultset, but DAO requires a cursor to access the
data.
In DAO, the index object and seek method are used for fast access and to locate a particular record.
RDO has no objects and methods of this kind, since it has different approach in managing the index
and search processes.
RDO does not have the ability to control referential integrity, security and schema modifications
because the database system itself has the utilities and tools for this purpose. DAO can manage the
referential integrity, security and modification of database with built-in methods and properties.
RDO uses complex stored procedures to manage and manipulate the database, which is not
possible with DAO. By running native SQL statements like create table or execute action queries
RDO can manipulate the database.
Comparison between RDO and ADO are given below:
ADO is not compatible with other database applications. To convert other data access application to
an ADO application, many statements will need to be changed to the ADO syntax. In some cases
you can convert with a few changes, while in other cases most of the code will need to be
converted to ADO syntax.
ADO is similar to RDO in it's functionality. ADO's object model is different from the object model
used by DAO and RDO. ADO has fewer objects, but more properties, methods, and events. ADO has
no objects such as rdoEngine and rdoEnvironment objects. ADO cannot access data through ODBC
data sources the same way as RDO. ADO can work with ODBC databases through the ODBC OLE DB
service provider.
DAO and RDO have objects that are derived from the base objects, thus forming a hierarchy of
objects. The functionality of RDO and DAO are concentrated in these objects. When comparing ADO
to RDO, the objects, properties, methods and events do not directly match up. Though ADO objects
are hierarchical, they are also created outside the scope of hierarchy. ADO doesn't support all the
functionality of the DAO. ADO has RDO style functionality and can interact with OLE DB data
source.
3. Explain Error handling with RDO.
197
The Remote Access Object architecture consists of the rdoEngine, rdoQuery and rdoError.
Operations using remote data access objects will generate errors and messages. Whenever an error
occurs rdoError objects will be placed in the rdoError collection of the rdoEngine object. As a new
error is generated, the existing rdoError collection will be cleared and the new rdoError object will
be placed in the rdoError collection. Some RDO operations will not generate any errors. Those
operations will not affect the rdoError object, but instead will generate trappable errors in Visual
Basic. The rdoErrors collection can be checked to find if any error has occurred and the related
cause of the error.
There will be some warning messages generated by ODBC. These messages will not create any
problem. If any informational errors are generated, the rdoEngine InfoMessage event will be
triggered. The rdoError collection can be checked inside this event.
The properties, rdoDefaultErrorThreshold or ErrorThreshold will have an error threshold value. If the
error number is below the error threshold specified in any of the above properties, then a trappable
error will be generated. Otherwise, a new rdoError object will be added to the rdoError collection.

198
Exercise - Solution
Create an application of a supermarket that uses the RDO for database access. Speculate the steps
needed to convert it into an Internet based application.
Solution
We want to create an application for a Super Market that uses RDO for the database access.
For this we can create a very simple application with the following operations.
a. Product Entry: This involves entering the new products to the stock. Details of the
products can be viewed by selecting the product code. The updating of the existing data is
also possible.
b. Sales: Here the Sales operation is handled. When a product is sold the corresponding
details has to be entered here so as to reduce the stock of the corresponding item. The
details of the issued bills can be viewed by selecting the bill number.
Data Design
Here we need to keep the details of the products in the stock and the details of the products sold.
So we can design the database with three tables.
Product Table:
Field Name Data Type
prod_code Text
prod_desc Text
prod_ price Currency

prod_tax Number

Sales_Master Table:
Field Name Data Type
sales_bill_no Number
sales_bill_date Date/Time
sales_amount Currency
Sales_Details Table:
Field Name Data Type
salesdet_bill_no Number

salesdet_prod_code Text

salesdet_prod_name Text
salesdet_price Currency

salesdet_qty Number
salesdet_tax Number
salesdet_rate Currency

There is a relation between the Sales_Master and the Sales_Details tables in which
Sales_Details.salesdet_bill_no refers Sales_Master .sales_bill_no
The salesdet_prod_code of Sales_Details table refers prod_code of Products table.
GUI Designing:
Here we need three Interfaces. They are:
a. Super Market Main Form: This is MDI form that is controlling all the process of the application.
For that add one MDI form to the project, add three menus and set the properties as shown below:

199
Name of Control Name Property Caption/Text
property
Form MDIFrmSuper Super Market
Menu1 mnuProducts &Products
Menu2 mnuSales &Sales
Menu3 mnuExit E&xit

b. Products Entry Form: This form handles all the operations for the product entry. Place the
controls and set the properties as shown below

Name of Control Name Property Text/Caption


property
Form frmProducts Products Entry
Label1 lblName Products Entry
Label2 lblProdCode Product Code
Label3 lblProdName Product Name
Label4 lblPrice Price
Label5 lblTax Tax
Label6 lblStock Stock
Combo1 cboProdCode (empty)
Text1 txtProdName (empty)
Text2 txtPrice (empty)
Text3 txtTax (empty)
Text4 txtStock (empty)
Command Button1 cmdAdd &Add
Command Button2 cmdUpdate &Update
Command Button3 cmdClear &Clear
Command Button4 cmdDelete &Delete
Command Button5 cmdClose Clos&e

c. Sales Form: This form handles all the operations for the Sales process. Place the controls and
set the properties as given below:
Name of Control Name Property Text/Caption
property
Form frmSales Sales
Label1 lblName Sales Details
Label2 lblBillNumber Bill Number
Label3 lblBillDate Bill Date
Label4 lblProdCode Product Code
Label5 lblProdName Product Name
Label6 lblPrice Price
Label7 lblQty Quantity
Label8 lblTax Tax
Label9 lblRate Rate
Label10 lblTotal Total
Combo1 cboBillNo (empty)
Combo2 cboProdCode (empty)

200
Text1 txtBillDate (empty)
Text2 txtProdName (empty)
Text3 txtPrice (empty)
Text4 txtQty (empty)
Text5 txttax (empty)
Text6 txtRate (empty)
Text7 txtTotal (empty)
Comm8and Button1 cmdAdd &Add / &New
Command Button2 cmdupdate &Update
Command Button3 cmdNext Nex&t
Command Button4 cmdClear &Clear
Command Button5 cmdClose Clos&e

Coding
Add the following code to MDIfrmSuper code editor window:
Private Sub mnuExit_Click()
'code for endding the application
End
End Sub

Private Sub mnuProducts_Click()


' for displaying the frmProducts form
frmProducts.Show
End Sub

Private Sub mnuSales_Click()


' for displaying the frmSales form
frmSales.Show
End Sub

201
Add the following code to the frmProducts form.
‘ Declare the following in the General Declarations section
Dim conSuper As rdoConnection
Dim recProducts As rdoResultset
Dim varSqlStat1 As String
Write the code in the click event of the cboProdCode.
Private Sub cboProdCode_Click()
recProducts.MoveFirst
Do While Not recProducts.EOF
If Trim(UCase(recProducts!prod_code)) = Trim(UCase(cboProdCode)) Then
cboProdCode = recProducts!prod_code
txtProdName = recProducts!prod_desc
txtPrice = recProducts!prod_price
txtTax = recProducts!prod_tax
txtStock = recProducts!prod_stock
Exit Sub
Else
recProducts.MoveNext
End If
Loop
End Sub
Write the following code in the click event of the cmdAdd command button.
Private Sub cmdAdd_Click()
'Adding new records
On Error GoTo ErrHan
recProducts.AddNew
recProducts!prod_code = cboProdCode
recProducts!prod_desc = txtProdName
recProducts!prod_price = txtPrice
recProducts!prod_tax = txtTax
recProducts!prod_stock = txtStock
recProducts.Update
cboProdCode.AddItem cboProdCode
Exit Sub
ErrHan:
If Err.Number = 3022 Then
MsgBox "Same Product Code is already given for a product" & vbCrLf & "Give another
code", vbInformation
cboProdCode.SetFocus
End If
End Sub

Code for clearing the fields.


Private Sub cmdClear_Click()
cboProdCode = ""
txtProdName = ""
txtPrice = ""
txtTax = ""
txtStock = ""
cboProdCode.SetFocus
202
End Sub

Code for closing the application


Private Sub cmdClose_Click()
Unload Me
End Sub
Code for Deleting the Record.
Private Sub cmdDelete_Click()
Dim varRes
If cboProdCode = "" Then
MsgBox "Select the record to edit", vbInformation
Exit Sub
End If
' Deleting the particular record
varRes = MsgBox("Are you sure to delete the product record", vbQuestion + vbYesNo)
If varRes = 6 Then
recProducts.Delete
cboProdCode.Clear
recProducts.MoveFirst
Do While Not recProducts.EOF
cboProdCode.AddItem recProducts!prod_code
recProducts.MoveNext
Loop
Call cmdClear_Click
End If
End Sub
Add the code for Updating the records.
Private Sub cmdUpdate_Click()
'Updating the records
recProducts.MoveFirst
Do While Not recProducts.EOF
If Trim(UCase(recProducts!prod_code)) = Trim(UCase(cboProdCode)) Then
recProducts.Edit
recProducts!prod_code = cboProdCode
recProducts!prod_desc = txtProdName
recProducts!prod_price = txtPrice
recProducts!prod_tax = txtTax
recProducts!prod_stock = recProducts!prod_stock + Val(txtStock)
recProducts.Update
Exit Do
Else
recProducts.MoveNext
End If
Loop
End Sub
Write the code in the Form Load event.
Private Sub Form_Load()
Set conSuper = rdoEnvironments(0).OpenConnection("Super", rdDriverNoPrompt)
varSqlStat1 = "Select * From products"
'Setting the recordset
203
Set recProducts = conSuper.OpenResultset(varSqlStat1, rdOpenKeyset, rdConcurValues)
'Loading the combo with Products code
On Error GoTo ErrHan
recProducts.MoveFirst
Do While Not recProducts.EOF
cboProdCode.AddItem recProducts!prod_code
recProducts.MoveNext
Loop
Exit Sub
ErrHan:
If Err.Number = 3021 Then
MsgBox "No items in the stock"
End If
End Sub
Add the following code to the frmSales form.
Declare the following in the general declaration section.
Dim conSuper As rdoConnection
' Declaring the resultset
Dim recSalesDetails As rdoResultset
Dim recSalesMaster As rdoResultset
Dim recProducts As rdoResultset
Dim conEmp As rdoConnection
' Declaring string for assigning SQL Query
Dim varSqlStat1 As String
Dim varSqlStat2 As String
Dim varSqlStat3 As String
Write the following code in the click event of the combo box, cboBillNo.
Private Sub cboBillNo_Click()
If cmdAdd.Caption = "&New" Then
recSalesMaster.MoveFirst
Do While Not recSalesMaster.EOF
If Trim(UCase(recSalesMaster!sales_bill_no)) = Trim(UCase(cboBillNo)) Then
recSalesDetails.MoveFirst
Do While Not recSalesDetails.EOF
If Trim(UCase(recSalesDetails!salesdet_bill_no)) = Trim(cboBillNo) Then
cboBillNo = recSalesMaster!sales_bill_no
txtBillDate = recSalesMaster!sales_bill_date
txtTotal = recSalesMaster!sales_amount
cboProdCode = recSalesDetails!salesdet_prod_code
txtProdName = recSalesDetails!salesdet_prod_name
txtQty = recSalesDetails!salesdet_qty
txtPrice = recSalesDetails!salesdet_price
txtTax = recSalesDetails!salesdet_tax
txtRate = recSalesDetails!salesdet_rate
recSalesDetails.MoveFirst
cboProdCode.Clear
Do While Not recSalesDetails.EOF
If recSalesDetails!salesdet_bill_no = cboBillNo Then
cboProdCode.AddItem recSalesDetails!salesdet_prod_code
End If
204
recSalesDetails.MoveNext
Loop
Exit Sub
Else
recSalesDetails.MoveNext
End If
Loop
Else
recSalesMaster.MoveNext
If recSalesMaster.EOF Then
MsgBox "No Bill Issued with this Bill Number", vbInformation
End If
End If
Loop
End If
End Sub

205
Add the following code in the clicking event of the combo box.
Private Sub cboProdCode_Click()
If cmdAdd.Caption = "&New" Then
recSalesDetails.MoveFirst
Do While Not recSalesDetails.EOF
If Trim(UCase(recSalesDetails!salesdet_bill_no)) = Trim(cboBillNo) And
Trim(UCase(recSalesDetails!salesdet_prod_code)) = Trim(UCase(cboProdCode)) Then
cboProdCode = recSalesDetails!salesdet_prod_code
txtProdName = recSalesDetails!salesdet_prod_name
txtQty = recSalesDetails!salesdet_qty
txtPrice = recSalesDetails!salesdet_price
txtTax = recSalesDetails!salesdet_tax
txtRate = recSalesDetails!salesdet_rate
Exit Do
Else
recSalesDetails.MoveNext
End If
Loop
Else
recProducts.MoveFirst
Do While Not recProducts.EOF
If Trim(UCase(recProducts!prod_code)) = Trim(UCase(cboProdCode)) Then
txtProdName = recProducts!prod_desc
txtPrice = recProducts!prod_price
txtTax = recProducts!prod_tax
txtQty.SetFocus
Exit Do
Else
recProducts.MoveNext
End If
Loop
End If
End Sub
Add the code in the clicking event of the cmdAdd button
Private Sub cmdAdd_Click()
If cmdAdd.Caption = "&New" Then
cboProdCode.Clear
recProducts.MoveFirst
Do While Not recProducts.EOF
cboProdCode.AddItem recProducts!prod_code
recProducts.MoveNext
Loop
cmdAdd.Caption = "&Add"
cboBillNo.SetFocus
Else
recSalesMaster.MoveFirst
Do While Not recSalesMaster.EOF
If Trim(UCase(recSalesMaster!sales_bill_no)) = Trim(UCase(cboBillNo)) Then
recSalesMaster.Edit
recSalesMaster!sales_bill_no = Trim(cboBillNo)
206
recSalesMaster!sales_bill_date = Trim(txtBillDate)
recSalesMaster!sales_amount = recSalesMaster!sales_amount + Trim(txtRate)
recSalesMaster.Update
Else
recSalesMaster.MoveNext
If recSalesMaster.EOF Then
recSalesMaster.AddNew
recSalesMaster!sales_bill_no = Trim(cboBillNo)
recSalesMaster!sales_bill_date = Trim(txtBillDate)
recSalesMaster!sales_amount = recSalesMaster!sales_amount + Trim(txtRate)
txtTotal = recSalesMaster!sales_amount
recSalesMaster.Update
End If
End If
Loop
recSalesDetails.AddNew
recSalesDetails!salesdet_bill_no = Trim(cboBillNo)
recSalesDetails!salesdet_prod_code = Trim(cboProdCode)
recSalesDetails!salesdet_prod_name = Trim(txtProdName)
recSalesDetails!salesdet_price = Trim(txtPrice)
recSalesDetails!salesdet_rate = Trim(txtRate)
recSalesDetails!salesdet_tax = Trim(txtTax)
recSalesDetails!salesdet_qty = Trim(txtQty)
recSalesDetails.Update
recProducts.MoveFirst
Do While Not recProducts.EOF
If Trim(UCase(recProducts!prod_code)) = Trim(UCase(prodcode)) Then
recProducts.Edit
recProducts!prod_stock = recProducts!prod_stock - Val(txtQty)
recProducts.Update
Exit Sub
Else
recProducts.MoveNext
End If
Loop
End If
End Sub
Write the following code in the click event of the cmdClick command button.
Private Sub cmdClear_Click()
cmdAdd.Caption = "&New"
cboBillNo = ""
cboProdCode = ""
txtProdName = ""
txtTax = ""
txtRate = ""
txtPrice = ""
txtRate = ""
txtTotal = ""
txtBillDate = ""
txtQty = ""
207
cboProdCode.Clear
recProducts.MoveFirst
Do While Not recProducts.EOF
cboProdCode.AddItem recProducts!prod_code
recProducts.MoveNext
Loop
End Sub
Code for unloading the sales form.
Private Sub cmdClose_Click()
Unload Me
End Sub
Add the following code in the cmdNext button.
Private Sub cmdNext_Click()
If cmdAdd.Caption = "&New" Then
recSalesDetails.MoveFirst
Do While Not recSalesDetails.EOF
If Trim(UCase(recSalesDetails!salesdet_bill_no)) = Trim(cboBillNo) And
Trim(UCase(recSalesDetails!salesdet_prod_code)) = Trim(UCase(cboProdCode)) Then
cboProdCode = recSalesDetails!salesdet_prod_code
txtProdName = recSalesDetails!salesdet_prod_name
txtQty = recSalesDetails!salesdet_qty
txtPrice = recSalesDetails!salesdet_price
txtTax = recSalesDetails!salesdet_tax
txtRate = recSalesDetails!salesdet_rate
Exit Do
Else
recSalesDetails.MoveNext
End If
Loop
Else
cboProdCode = ""
txtProdName = ""
txtQty = ""
txtPrice = ""
txtTax = ""
txtRate = ""
cboProdCode.SetFocus
End If
End Sub
Write the following code in the click event of the cmdUpdate button.
Private Sub cmdUpdate_Click()
If cmdAdd.Caption = "&New" Then
recSalesMaster.Edit
recSalesMaster!sales_bill_no = Trim(cboBillNo)
recSalesMaster!sales_bill_date = Trim(txtBillDate)
recSalesMaster!sales_amount = Trim(txtTotal)
recSalesMaster.Update
recSalesDetails.Edit
recSalesDetails!salesdet_bill_no = Trim(cboBillNo)
recSalesDetails!salesdet_prod_code = Trim(cboProdCode)
208
recSalesDetails!salesdet_prod_name = Trim(txtProdName)
recSalesDetails!salesdet_price = Trim(txtPrice)
recSalesDetails!salesdet_rate = Trim(txtRate)
recSalesDetails!salesdet_tax = Trim(txtTax)
recProducts.MoveFirst
Do While Not recProducts.EOF
If Trim(UCase(recProducts!prod_code)) = Trim(UCase(cboProdCode)) Then
recProducts.Edit
recProducts!prod_stock = recProducts!prod_stock + recSalesDetails!salesdet_qty -
Val(txtQty)
recProducts.Update
Exit Do
Else
recProducts.MoveNext
End If
Loop
recSalesDetails!salesdet_qty = Trim(txtQty)
recSalesDetails.Update
End If
End Sub
Write the code in the Form Load event.
Private Sub Form_Load()
Set conSuper = rdoEnvironments(0).OpenConnection("Super", rdDriverNoPrompt)
varSqlStat1 = "Select * From products"
varSqlStat2 = "Select * from Sales_master"
varSqlStat3 = "Select * from sales_details"
' Set resEmp = conEmp.OpenResultset(varSqlStat, rdOpenKeyset, rdConcurValues)
' Set dbSuper = OpenDatabase("d:\supermarket")
Set recSalesMaster = conSuper.OpenResultset(varSqlStat2, rdOpenKeyset, rdConcurValues)
Set recSalesDetails = conSuper.OpenResultset(varSqlStat3, rdOpenKeyset, rdConcurValues)
Set recProducts = conSuper.OpenResultset(varSqlStat1, rdOpenKeyset, rdConcurValues)
On Error GoTo ErrHan
recProducts.MoveFirst
Do While Not recProducts.EOF
cboProdCode.AddItem recProducts!prod_code
recProducts.MoveNext
Loop
recSalesMaster.MoveFirst
Do While Not recSalesMaster.EOF
cboBillNo.AddItem recSalesMaster!sales_bill_no
recSalesMaster.MoveNext
Loop
Exit Sub
ErrHan:
MsgBox "No Records Exist"
End Sub
Add the code in the Lost Focus event of the txtQty
Private Sub txtQty_LostFocus()
If cmdAdd.Caption = "&Add" Then
txtRate = Val(txtPrice) * Val(txtQty) * (1 + Val(txtTax) / 100)
209
txtTotal.SetFocus
End If
End Sub
Steps for converting this application into Internet based
We can convert this application into Internet based, by converting it into an ActiveX Document.
For that, do the following steps.
Step 1:
From Add-Ins select ActiveX Doc Migration Wizard.
Step 2:
Open the ActiveX Migration wizard and select the forms that you need to convert into the Internet
application. Then press Next button.
Step 3:
Follow the instructions in each window and at last press the Finish button.
Step 4:
Save and run the application. You can view a dialog box asking where to run the application as
default. Select Internet Explorer and click OK. Then you can view the application running in the
Internet Explorer.
Sample Outputs
MDI Form

210
Products Entry Form

Sales Entry Form

211
CHAPTER 11
Introduction to OLE DB and ADO
ActiveX Data Objects (ADO) may be defined as a high speed, high performance interface which
allows client applications to access and manipulate data in a database server and other databases
through any mechanism that supports the OLE DB. The OLE DB providers are actually software that
communicates with the database.
The OLE DB is a low-level interface designed for the universal data access. OLE DB is theoretically
capable of dealing with any type of data source. The data source is not restricted in terms of its
format or storage method. It may be a small database system or a large Relational database.
There are many ways to connect to databases, each with their own strengths and weaknesses. The
VBSQL is a high speed and lightweight tool for accessing databases in Microsoft SQL Server and
Sybase SQL Server. The main disadvantage of VBSQL is that it connects only to Sybase and SQL
Server. After VBSQL, the DB Library technology evolved. After that, DAO (Data Access Object) .DAO
is the first object-based interface capable of accessing native Jet databases, popular ISAM
databases and other common Relational databases. Next the Remote Data Object evolved. Finally
the most advanced connection developed: OLE DB.
The OLE DB was introduced by Microsoft Corporation and is a new database client technology. ADO
is an interface which is build on top of OLE DB. The ADO Objects can be created and used
independently. This means that ADO has mainly three independent objects. One for Connection,
one for Recordset and the other for Command. The Connection object is for making an open
connection with a datasource. The Recordset object is a group of data from a database The
Command object is for defining a Command that you want to execute in a data source. Each object
is a stand-alone object and you can create any number of objects or can work with each object as a
stand-alone application. Other important advantages are, it will support stored procedures having
different cursor types, support for multiple recordsets and free-threaded objects for Network based
applications.
Concept of OLE DB and ADO are discussed in the next topic.
Understanding OLE DB and ADO
Concept of OLE DB

OLE DB is introduced for implementing the concept of Universal Data Access. It was designed for
providing an open standard for accessing all kinds of data sources. OLE DB interfaces provide
uniform access to the data stored in diverse data sources that are distributed in diverse systems
such as desktop, midrange, mainframe and Internet. OLE DB is a developing industry standard for
data access to, and manipulation of both SQL and non-SQL data sources or Relational and Non-
Relational data sources. The term Universal data access means the ability to access data regardless
of the data source. The data source may be Relational database systems, COM Components, Email
systems, File Systems, Spread sheets or any type of information source.

212
OLE DB is a specification which is designed to provide an open standard for accessing all kinds of
data. The OLE DB consists of mainly three components: , Data providers, Data consumers and
Service components. The Data providers are those which expose their data. They are the
component that responds to the commands and queries and provides the data in a usable form.
The Data consumers are those which use data and is a component that uses the OLE DB
Technology to access a data source in any usable form. The Service Components are those which
process and transport data. These Components are designed to help the users to make high quality
applications that can access any data base, anywhere and can be created and used independently
There are two types of OLE DB applications: consumer and providers. An OLE DB consumer can be
defined as any application that consumes data provided by the OLE DB interfaces. For example a
Windows based application that uses the OLE DB interface to connect with a database is an OLE DB
Consumer. An OLE DB provider is any application that allows consumers to access data from any
information source.
The OLE DB Connection object represents an Open connection to a data source. When a user wants
a connection, they want to create a Connection object and the Connection object handles all the
necessary parameters for establishing a connection with a database. The connection object calls
the OLE DB provider and it will invoke the corresponding APIs for establishing a connection.
Concept of ADO
The term ADO stands for ActiveX Data Object. The ADO is an Object Based interface to OLE DB. It
enables you to create applications that can access and manipulate data in a data source regardless
of its type or location. The data source may be a relational or a simple DBMS, a text file, native Jet
databases, popular ISAM databases, and other common Relational databases and can be
distributed in a mainframe, mini computer, or on other network sources.
The peculiarity of ADO is that it has independent objects for creating and manipulating the
database. The three main independent objects are the Connection object, the Recordset object, and
the Command object. The Connection Object is used for creating and maintaining a connection with
a data source. You will learn the ADO Connection object concept in detail in the following chapters.
You can even create and can set the properties before the connection is opened.
The Recordset Object is used for collecting the data from a database. It contains several rows and
columns of data where each row is a record. The user can access one record at a time and
manipulate it as they see fit. ADO has some other peculiarities. You can create your own recordset
without establishing a connection or you can manipulate an existing recordset after closing the
connection.
The another important object is the Command object. This object defines a command or query that
you want to execute in a database. This is most useful for manipulating the Database.
All these concepts are made clear in the following sections.
In the next topic, you can learn how to use ADO control
Using The ADO Control
The ADO Data Control is used for accessing data using Microsoft's ActiveX Technology. It is used for
establishing a connection between data-bound controls and a data source. A Data-bound control is
any control that has the datasource property.
The ADO Control is almost like a data control and it also has some other properties for making an
Object Based interface with a data source. It is mainly used to create front-end applications,
establishing the database connection and modifying the records in that data source.
Developing an application using ADO control is discussed below,
Step 1:
In the first step we need to create a Standard EXE project.
Step 2
In the next step place an ADO control on the Form. For that the ADO Data control should be
included in the project from the Components Dialog box. This is done by right clicking on the Tool
213
Box and select the Components. Then Select the Microsoft ADO Data Control 6.0 (OLE DB).
Then set the Properties of the ADO Data Control by selecting the ADODC Properties from the
Pop-up menu. Then a property page will appear.
Then in the General Tab of the Properties Page (Figure shown below)

Select the Option Use Connection String and press the Build button.
Step 3:
It will display a Dialog as shown in the figure.

214
In the Provider tab of the dialog, select the OLE DB provider name (here select Microsoft Jet 3.51
OLE DB Provider) then press Next.
Step 4:
It will display the Connection tab as shown in the figure.

Here you can enter the Database name such as empdb (specify the path). Then enter the User
Name and Password. To test your connection, select the Test Connection Command Button. Thus
you can create and test a Connection string before you begin to use it.

215
Step 5:
Next, select the Authentication tab of the properties page, where you can set the UserName and
Password.

Step 6:
Then, select the Record Source tab as shown in the figure.

In this Tab there is one ComboBox for selecting the Command Type, another Combo Box for
Table or Stored Procedure Name, other for Command Text (SQL). Here select adCmdTable
as the command type, then select the Table name emptab from the second Combo Box.
Step 7:
Then Place Five Text Boxes, Five Labels, and Nine Command Buttons in the Form and set the Properties as below:

Name Caption/Text DataSour


Control Name DataField
Property property ce
frmEmpdetai Employee
Form (empty) (empty)
ls Details

216
ADO Data Control adoEmp Details (empty) (empty)
Textbox1 txtEmpNo (empty) adoEmp Empno
Textbox2 txtEmpName (empty) adoEmp Empname
Textbox3 txtDeptNo (empty) adoEmp Deptno
Textbox4 txtEmpSal (empty) adoEmp Salary
Textbox5 txtEmpAge (empty) adoEmp Age
Label1 lblEmpNo Employee No (empty) (empty)
Employee
Label2 lblEmpName (empty) (empty)
Name
Label3 lblDeptNo Dept No (empty) (empty)
Label4 lblEmpSal Salary (empty) (empty)
Label5 lblEmpAge Age (empty) (empty)
Command
cmdAdd (empty) (empty) (empty)
Button1
Command
cmdDelete (empty) (empty) (empty)
Button2
Command
cmdUpdate (empty) (empty) (empty)
Button3
Command
cmdSave (empty) (empty) (empty)
Button4
Command
cmdClose (empty) (empty) (empty)
Button5
Command
cmdFirst (empty) (empty) (empty)
Button6
Command
cmdPrevious (empty) (empty) (empty)
Button7
Command
cmdNext (empty) (empty) (empty)
Button8
Command
cmdLast (empty) (empty) (empty)
Button9
Step 8:
The next step is to write the necessary code for the appropriate event of each control. The Code is
similar to the Data Control programming. First step is to declare the global variables in the General
Declarations section of your project. Here we want to declare the variables for setting the mode
and for collecting the response. Declare it as shown below:
Option Explicit
' Declaring Global Variables
Dim varmode ' Variable for setting mode of operation.
Dim varRes ' Variable for collecting the Response
Next write the procedures, Recset_Ctrl and Ctrl_Rectset functions for transferring data from text
boxes to the database and from the database to TextBoxes.
Public Sub Recset_Ctrl()
' Assign the values from the Recordset to the TextBoxes
txtEmpNo = adoEmp.Recordset!Empno
217
txtEmpName= adoEmp.Recordset!Empname
txtEmpSal = adoEmp.Recordset!Salary
txtDeptNo = adoEmp.Recordset!Deptno
txtEmpAge = adoEmp.Recordset!Age
End Sub
Public Sub Ctrl_Recset()
' Assign the values from the TextBoxes to the Recordset
adoEmp.Recordset!Empno = txtEmpNo
adoEmp.Recordset!Empname = txtEmpName
adoEmp.Recordset!Salary = txtEmpSal
adoEmp.Recordset!DeptNo = txtDepNo
adoEmp.Recordset!Age = txtEmpAge
End Sub
Next, for clearing the text boxes during addition of new record, a procedure named Clear should be
written.
Public Sub Clear()
' Clears the TextBoxes
txtEmpNo = ""
txtEmpName = ""
txtEmpSal = ""
txtDepNo = ""
txtEmpAge = ""
End Sub
( In order to search for a particular record in the table while updating or inserting to know whether the
record with a particular Empno exist, another user procedure called Search is written.
Public Sub Search()
' Move record pointer to first record
adoEmp.Recordset.MoveFirst
' Finds the record with same Employee_id
Do While Not Trim (adoEmp.Recordset!Empno) = Trim(varRes)
adoEmp.Recordset.MoveNext
If adoEmp.Recordset.EOF Then
MsgBox "an Employee with this ID does not exist"
Exit Sub
End If
Loop
Call Recset_Ctrl()
End Sub
After completing this, write the following code in the Click event of the cmdAdd Command Button.
Private Sub cmdAdd_Click()
' To add a new record
adoEmp.Recordset.AddNew
' Calls Clear function to clear the TextBoxes
Call Clear ()
' To set the focus on txtEmpNo
txtEmpNo.SetFocus
' Sets mode to "Add"
varMode = "Add"
End Sub
Now, write the following code in the Click event of the cmdUpdate Command Button.
218
Private Sub cmdUpdate_Click()
' Set the mode variable to Update
varMode = "Update"
varRes = InputBox("Enter the Empno:", "Updation")
If varRes = Empty Then
Exit Sub
End If
' Calls the Search Procedure
Call Search
End Sub
After this we can write the code for the Delete operation.
Private Sub cmdDelete_Click()
' Sets mode to Delete
varMode = "Delete"
varRes = InputBox("Enter the Empno", "delete")
' Checks whether varRes has a value or not
If varRes = Empty Then
' To exit from the procedure
Exit Sub
End If
' Calls the user procedure, Search
Call Search()
End Sub
Until now, we have done the operations for Inserting, Deleting, and Updating. Now we want to write
the code for saving all the above operations. For that, write the following code for cmdSave
Command Button.
Private Sub cmdSave_Click()
' For storing the Response
Dim varAct
' Verifies that the mode of operation is set for adding of records
If varMode = "Add" Then
MsgBox "Record saved"
' Checks the mode of operation is set for updating of records
ElseIf varMode = "Update" Then
' Set the record for editing
adoEmp.Recordset.Edit
Call Ctrl_Recset()
' To update changes in the record
adoEmp.Recordset.Update
' To update the recordset
adoEmp.Recordset.Requery
MsgBox "Record Updated"
ElseIf varMode = "Delete" Then
varResp = MsgBox("Are you sure to delete the current record", vbYesNo + vbExclamation,
"Deletion")
If res = vbYes Then
' To delete the current record
adoEmp.Recordset.Delete
MsgBox "Record deleted"
Call Clear()
219
End If
End If
End Sub
Now we have completed all the operations for working with the Database. If you want to be able to
move the data pointer to First position, Next position, Last position, or Previous position then we
can write the following code :
In the click event of the cmdFirst Command Button.
Private Sub cmdFirst_Click()
' Check whether any record exist
If adoEmp.Recordset.EOF And adoEmp.Recordset.BOF Then
MsgBox "No current Record"
Exit Sub
End If
' Move the record pointer to the First record
adoEmp.Recordset.MoveFirst
' Calls Recset_Ctrl to assign recordset values to control
Call Recset_Ctrl()
End Sub
In the click event of the cmdLast Button.
Private Sub cmLast_Click()
' Check whether any record exist
If adoEmp.Recordset.EOF And adoEmp.Recordset.BOF Then
MsgBox "No current Record"
Exit Sub
End If
' Move the record pointer to the Last record
adoEmp.Recordset.MoveLast
' Calls Recset_Ctrl to assign recordset values to control
Call Recset_Ctrl()
End Sub
In the click event of the cmdNext Command Button.
Private Sub cmdNext_Click()
' Check whether any record exist
If adoEmp.Recordset.EOF And adoEmp.Recordset.BOF Then
MsgBox "No current Record"
Exit Sub
End If
' Move the record pointer to the Last record
adoEmp.Recordset.MoveNext
If adoEmp.Recordset.EOF Then
MsgBox "Last Record"
adoEmp.Recordset.MoveLast
End If
Call Recset_Ctrl()
End Sub
In the click event of the cmdPrevious Command Button.
Private Sub cmdPrevious_Click()
If adoEmp.Recordset.EOF And adoEmp.Recordset.BOF Then
MsgBox "No current Record"
Exit Sub
220
End If
' Move the record pointer to the previous record
adoEmp.Recordset.MovePrevious
If adoEmp.Recordset.BOF Then
MsgBox "First Record"
adoEmp.Recordset.MoveFirst
End If
Call Recset_Ctrl()
End Sub
Step 9:
Finally, run the application by Pressing F5 or click on the Start menu item in the Run menu.
Sample Outputs
Main Window

Window for Updation


Type the employee number and click OK to locate the record for updation.

Window for Deletion


Type the employee number and click OK to locate the record for deletion.

In the next topic you will learn how to program using ADO.
Programming with ADO
OLE DB is an API that enables an application to gain access to and modify any type of data source.
The data source may be a text file, a relational or non-relational database located in any type of

221
system. ADO is a programming model that has the capability to access any type of Data source. It
is an Object Model that has it's own methods, properties, and events.
The important Objects of ADO are given below:
1. Connection Object

The Connection Object is used for making a connection with a database and it enables an
application to exchange data with the data source. The connection object allows the user to set all
parameters that are necessary for setting up a connection. It is also a container for transactions. A
transaction is a series of data access operations across a connection treated as one operation.
The important properties are given below:
The Provider property is the name of OLE DB provider, otherwise known as the connection. Each
database has its own corresponding OLE DB provider. There is a default MSDASQL ("Kagera")
provider which is the OLE DB provider for ODBC Drivers allowing an application to connect to any
relational database that supports the ODBC driver.
The another important property related with the Connection is the ConnectionString property in
which you can set the Provider name, Server name, UserID, Password and Data Source Name
(DSN). The Provider property and the Connection String property are not used simultaneously.
The mode property is used to set the available permissions for a user for modifying the Database.
For example we can set the database as readonly by setting the mode property to adModeRead.
If you want to create a Cursor then you can use the CursorLocation property through which you can
determine where to create a Cursor. The client-side cursors can be created by setting the
CursorLocation property to adUseServer and the server-side cursor by setting the CursorLocation
property to adUseServer.
You can modify the DefaultDatabase property to set the default database for the connection object.
The level of isolation for the Connection object can be set by using the isolationlevel property.
The Attributes property is used for managing Transactions. It will be set to adXactCommitRetaining
after setting every CommitTrans method and it will be set to adXactAbort after every RollbackTrans
method.
The CommandTimeout method indicates how long should wait while executing a command before
terminating the attempt and generating an Error message.
The ConnectionTimeout method indicates how long it should wait for establishing a connection
before terminating the attempt and generating an Error message.
The State property is used for representing the state of the object and will indicate closed or open.
Important methods of the Connection Object is given below:
The Open method is used for establishing a connection. It has the following syntax:
Open [ConnectionString], [UserID], [Password], [Options]
The BeginTrans, CommitTrans, and RollbackTrans methods are used for controlling transactions.
The method BeginTrans will begin a new Transaction, CommitTrans saves the changes in the
Transactions and RollbackTrans cancels the changes made during the current transaction.
The Execute method is used for performing a Query Operation in a Connection. The syntax for the
Execute method is:
Execute CommandText, [RecordsAffected], [Options]
Where the CommandText is a string that represents the SQL statement, stored procedure etc.,
RecordsAffected represents the number of records that the operation has affected and Options
represents how the provider should evaluate the CommandText property.
2. Recordset Object
The Recordset object contains a group of data from a database. It contains a set of columns or
rows of data. Each row is known as Record and each column is known as Field. Using the Recordset
you can access each row and can manipulate the current record. The ADO, Recordset is more
advanced than the DAO and ODBC. Here you can create a Recordset object without being

222
connected to the database and can retrieve and modify the data without being connected to the
database.
The important properties are given below:
The Source property is for holding the name of the table or query used to populate the Recordset.
The ActiveConnection property represents which Recordset is currently working with the database.
The current record position is determined by the BOF and EOF functions. BOF indicates the current
record is before the first record in the Recordset object and EOF represents the current position is
after the last record in a Recordset object.
The MaxRecords property sets the maximum number of records returned during the connection.
The Recordset object also has the CursorLocation property which is almost same as that of the
Connection object.
The CursorType property tells which type of cursor is to be created.
The CacheSize property will give the number of records when working with ADO cursors.
The LockType property is for managing concurrency in the database.
The RecordCount property returns the number of records in the Recordset.
The AbsolutePosition property returns the ordinal position of the current record in the Recordset.
The Sort property is used to sort the records in a Recordset.
The MarshalOption property tells how to send back rows to the server. If it is adMarshalAll, then
ADO will send all the records to the server. If this property is adMarshalModifiedOnly then it will
return only all the modified records to the server.
The important methods of the Recordset object is given below:
The first method for a Recordset is the Open method. If you want to manipulate data in a
Recordset, it should be opened first. The syntax for the Open method is:
Open [Source], [ActiveConnection], [CursorType], [LockType], [Options]
Where Source is the name of the Table or a stored procedure, ActiveConnection is the name of the
currently active connection object, CursorType tells which type of cursor you want to create and
LockType is the type of locking you want to enforce and the Options represents the type of data
source. For example if the Options value is adCmdTable then it is a database table.
The Cancel method is used to cancel an asynchronous operation at any time.
The Close method is used for closing an existing Recordset.
The Clone method is used for creating a copy of an existing Recordset. For example if rs1 is a
Recordset and if we want to create the same type of recordset having the Locktype ReadOnly then
we can do it as follows:
Dim rs2 As ADODB.Recordset
Set rs2=rs1.Clone(adLockReadOnly)
The GetRows method is used for retrieving the data form a database. The syntax is as follows:
varArray = rs.GetRows([Rows], [Start], [Fields])
where Rows is the number of records you want to read; Start is a bookmark that indicates the first
record to be read; Fields is an optional array of field names that serves to restrict the fields of data
to transfer. Getrows returns a two dimensional array where each column corresponds to a record in
the Records and each row correspond to the field in the Records.
The MoveFirst, MoveNext, MovePrevious, and MoveNext methods are used for navigating within a
Recordset.
The method MoveFirst is used to move the record pointer to the first record in the recordset.
The method MoveLast is used to move the record pointer to the last record in the recordset.
MoveNext is used to move to the next record and MovePrevious is used to move to the Previous
record.
The Find method is used for finding a record. The syntax for Find method is as follows:
Find Criteria,[Skip Records], [SearchDirection], [Start]

223
where the Criteria is a string that contains the search condition; SkipRecord represents how many
records should be skipped before starting the search; SearchDirection indicates the direction the
search will proceed, Start is an optional bookmark that specifies the record from which the Search
should begin.
In ADO you can save the Recordset object to a disk file and can reopen it when necessary. This can
be done by using the Save method. It has the following syntax:
Save [FileName], [PersistFormat]
Where Filename represents the name of the file in which the Recordset will be saved and the
PersistFormat represents the format in which the recordset will be saved.
3. Command Object
The execution of a specific query or a command that you want to execute in a database is carried
out through the Command object. It is very useful when you want to reuse commands or invoke
parameterized queries.
The important properties of the Command object are given below:
The CommandText property contains the SQL command or the name of the query that you want to
execute for a database provider. It is used to instruct the Command object what to do to the data
source.
The property ActiveConnection represents the definition of the Connection object that is currently
working with the database.
The CommandType property represents what the CommandText string contains. For example if it is
set to adCmdStoredProc, then it is a stored procedure.
The Prepared property is used to tell whether the compiled procedure is to be saved or not. If this
property is true, the provider creates a prepared (saved) version of a query passed in the
CommandText property and then uses it to run the query each time when the command is re-
executed.
The CommandTimeout property is same as that of the Connection object. It is the time interval in
seconds, that indicates how much time it should wait while executing a command before
terminating the attempt and generating an error message.
The State property represents the current state of the database at any time.
The important methods of the Command object are given below:
The Execute method is used to run the query or a command stored in the CommandText property.
The syntax for the Execute method is given below:
Execute([RecordsAffected], [Parameters], [Options]) As Recordset
Where the argument RecordsAffected represents the number of records that the operation affects;
Parameter is the array of parameter values passed in the SQL statement and Options represents
the value that tells how the provider should evaluate the CommandText property of the Command
object.
The Cancel method is used to cancel the execution of the Command object's asynchronous
operation.
The CreateParameter method is used to create a new parameter object. The syntax for
CreateParameter is given below:
CreateParameter([Name], [Type], [Direction], [Size], [Value]) As Parameter
Where the Name argument is a string that representing the name of the parameter object; Type is
a string that represents the datatype of the parameter object; The Direction argument tells the
value that represents the type of the parameter object and Size represents the maximum length of
a parameter in bytes.
4. Field Object
The Field object represents one column in a Data source of the same datatype.
The important properties of the Field Object is given below:
The Name property is the name of the database column from which the Field object takes the data.
224
The Type property represents the constant that defines the kind of values which is stored in a field.
The DefinedSize property represents the maximum capacity that was defined when the field was
created.
The Attributes property is used to represent the value that returns the information about the field.
The Value property is used to set the contents of the field.
The ActualSize property defines the number of bytes taken by the current value in the field.
The OriginalValue property represents the value that was in the field before any changes were
made.
The important methods for the Field Object is given below:
The AppendChunk method appends a chunk of data to a large text or binary field.
The GetChunk method is used to take back the data stored in a Field that contains a large text or
binary field.
5. Parameter Object
The Parameter object defines a parameter in a command or a stored procedure on which the
command object is based.
The important properties of the Parameter object are given below:
The characteristics of a parameter object is represented by the Attributes property.
The Direction property represents whether the Parameter object represents an input parameter, an
output parameter, or the return value from a stored procedure.
The Size property represents the maximum size value of a parameter object.
The parameter object also has the properties such as Name, Type, Precision and NumericScale
property which are same as that of the Field object.
The Parameter object has only the AppendChunk method, which is similar to that of the Field
object.
6. Property Object
The Property object defines the characteristics of an ADO object. The ADO Object model has two
types of properties: built-in and dynamic.
The Built-in properties are those properties which are available to any new object.
The Dynamic properties are those which are defined by the corresponding data provider and
appear in the properties collection of the ADO object.
In the next topic you can learn how to work with ADO events.

225
Working with ADO Events
The term Events represents the notifications to the objects that some operation has occurred or is
about to occur. Events allow you to take complete control of what's happening behind the scenes.
The connection object enables the events when it establishes a connection. The important events of
the Connection object are described below.
Two important events when establishing a connection are the WillConnect event and
ConnectComplete event. The WillConnect event will fire immediately before a connection is
established and the ConnectComplete event will fire after the connection is established.
The events which are related to the Execution of a command are the WillExecute and
ExecuteComplete events. The WillExecute event occurs before a command is executed on the
connection and the event ExecuteComplete fires immediately after it has completed.
The event which is related to transactions is known as the BeginTransComplete event. The
BeginTransComplete event occurs when a BeginTrans method has completed execution.
The InfoMessage event occurs when the database engine sends a message or warning.
After the connection has been established, the Recordset formation can begin. The events which
are related with the Recordset are given below.
The FetchProgress event occurs while a lengthy operation is taking place. For example you can use
this to show a progressbar that indicates the percentage of records retrieved.
The Navigation operations will trigger the WillMove and MoveComplete events. The WillMove event
occurs each time the current record begins to change and the MoveComplete event fires as soon as
the Movement completes.
The WillChangeField event occurs when you begin the process of modifying one or more fields in a
Recordset and the FieldChangeComplete event occurs when the Update operation is completed.
The WillChangeRecordset event occurs whenever the ADO is going to change the contents of the
Recordset as a whole. The RecordsetChangeComplete event occurs immediately after a change
occurs in the Recordset.
These are the important events which take place in the ADO object.
Self Assessment
Select the correct answer.
(1) The term ADO stands for:
(a) Active Data Object
(b) ActiveX Data Object
(c) ActiveX Data Access Object
(d) All the above
(2) The Interface for the universal data access:
(a) OLE DB
(b) ODBC
(c) DAO
(d) VB SQL
(3) Which is not a component of OLE DB:
(a) Data providers
(b) Data consumers
(c) Service components
(d) Data connection
(4) Which is not an event of ADO.
(a) SetFocus
(b) WillConnect
(c) WillExecute
(d) InfoMessage
(e) FetchProgress
226
Workshops
1. Explain the concept of Universal Data Access ?
2. What are the important types of objects in the OLE DB ? Explain the important properties and
methods of each object ?
3. Explain the important events in the OLE DB?
Exercise
Create a database application which can access a database using DAO, ADO and ODBC. Compare
the differences?
Chapter - 11
Workshops - Solution
1. Explain the concept of Universal Data Access?
The concept of Universal Data Access means the ability to access data regardless of the data
source. The data source may be relational database systems, COM Components, Email systems,
File Systems, Spread sheets or any type of information source. OLE DB is introduced for
implementing this concept. It was designed for providing an open standard for accessing all kinds of
data sources. OLE DB interfaces provide uniform access to the data stored in diverse data sources
that are distributed in diverse systems such as desktop, mid-range, mainframe and Internet. OLE
DB is a developing industry standard for data access to, and manipulation of either SQL and non-
SQL data sources or Relational and Non-Relational data sources.
2. What are the important types of objects in the OLE DB? Explain the important properties and
methods of each object?
1. Connection Object
The Connection Object is used for making a connection with a database and it enables an
application to exchange data with the data source. The connection object allows the user to set all
parameters that are necessary for setting up a connection. It is also a container for transactions. A
transaction is a series of data access operations across a connection treated as one operation.
The important properties are given below:
The Provider property is the name of OLE DB provider, otherwise known as the connection. Each
database has its own corresponding OLE DB provider. There is default MSDASQL ("Kagera")
provider which is the OLE DB provider for ODBC Drivers allowing an application to connect to any
relational database that supports the ODBC driver.
The another important property related with the Connection is the ConnectionString property in
which you can set the Provider name, Server name, UserID, Password and Data Source Name
(DSN). The Provider property and the Connection String property are not used simultaneously.
The mode property is used to set the available permissions for a user for modifying the Database.
For example we can set the database as readonly by setting the mode property to adModeRead.
If you want to create a Cursor then you can use the CursorLocation property through which you can
determine where to create a Cursor. The client-side cursors can be created by setting the
CursorLocation property to adUseServer and the server-side cursor by setting the CursorLocation
property to adUseServer.
You can modify the DefaultDatabase property to set the default database for the connection object.
The level of isolation for the Connection object can be set by using the isolationlevel property.
The Attributes property is used for managing Transactions. It will be set to adXactCommitRetaining
after setting every CommitTrans method and it will be set to adXactAbort after every RollbackTrans
method.
The CommadTimeout method indicates how long should wait while executing a command before
terminating the attempt and generating an Error message.
The ConnectionTimeout method indicates how long it should wait for establishing a connection
before terminating the attempt and generating an Error message.
The State property is used for representing the state of the object and will indicate closed or open.
227
Important methods of the Connection Object are given below:
The Open method is used for establishing a connection. It has the following syntax:
Open [ConnectionString], [UserID], [Password], [Options]
The BeginTrans, CommitTrans, and RollbackTrans methods are used for controlling transactions.
The method BeginTrans will begin a new Transaction, CommitTrans saves the changes in the
Transactions and RollbackTrans cancels the changes made during the current transaction.
The Execute method is used for performing a Query Operation in a Connection. The syntax for the
Execute method is:
Execute CommandText, [RecordsAffected], [Options]
Where the CommandText is a string that represents the SQL statement, stored procedure etc,
RecordsAffected represents the number of records that the operation has affected and Options
represents how the provider should evaluate the CommandText property.
2. Recordset Object
The Recordset object contains a group of data from a database. It contains a set of columns or
rows of data. Each row is known as Record and each column is known as Field. Using the Recordset
you can access each row and can manipulate the current record. The ADO, Recordset is more
advanced than the DAO and ODBC. Here you can create a Recordset object without being
connected to the database and can retrieve and modify the data without being connected to the
database.
The important properties are given below:
The Source property is for holding the name of the table or query used to populate the Recordset.
The ActiveConnection property represents which Recordset is currently working with the database.
The current record position is determined by the BOF and EOF functions. BOF indicates that the
current record is before the first record, in the Recordset object and EOF represents the current
position is after the last record in a Recordset object.
The MaxRecords property sets the maximum number of records returned during the connection.
The Recordset object also has the CursorLocation property which is almost same as that of the
Connection object.
The CursorType property tells which type of cursor is to be created.
The CacheSize property will give the number of records when working with ADO cursors.
The LockType property is for managing concurrency in the database.
The RecordCount property returns the number of records in the Recordset.
The AbsolutePosition property returns the ordinal position of the current record in the Recordset.
The Sort property is used to sort the records in a Recordset.
The MarshalOption property tells how to send back rows to the server. If it is adMarshalAll, then
ADO will send all the records to the server. If this property is adMarshalModifiedOnly then it will
return only all the modified records to the server.
The important methods of the Recordset object is given below:
The first method for a Recordset is the Open method. If you want to manipulate data in a
Recordset, it should be opened first. The syntax for the Open method is:
Open [Source], [ActiveConnection], [CursorType], [LockType], [Options]
Here,
Source is the name of the table or a stored procedure. ActiveConnection is the name of the
currently active connection object. CursorType tells which type of cursor you want to create and
LockType is the type of locking you want to enforce and the Options represents the type of data
source. For example, if the Options value is adCmdTable then it is a database table.
The Cancel method is used to cancel an asynchronous operation at any time.
The Close method is used for closing an existing Recordset.

228
The Clone method is used for creating a copy of an existing Recordset. For example if rs1 is a
Recordset and if we want to create the same type of recordset having the Locktype ReadOnly then
we can do it as follows:
Dim rs2 As ADODB.Recordset
Set rs2=rs1.Clone(adLockReadOnly)
The GetRows method is used for retrieving the data form a database. The syntax is as follows:
varArray = rs.GetRows([Rows], [Start], [Fields])
where Rows is the number of records you want to read; Start is a bookmark that indicates the first
record to be read; Fields is an optional array of field names that serves to restrict the fields of data
to transfer. GetRows returns a two dimensional array where each column corresponds to a record in
the Records and each row correspond to the field in the Records.
The MoveFirst, MoveNext, MovePrevious, and MoveNext methods are used for navigating within a
Recordset.
The method MoveFirst is used to move the record pointer to the first record in the recordset.
The method MoveLast is used to move the record pointer to the last record in the recordset.
MoveNext is used to move to the next record and MovePrevious is used to move to the Previous
record.
The Find method is used for finding a record. The syntax for Find method is as follows:
Find Criteria,[Skip Records], [SearchDirection], [Start]
where the Criteria is a string that contains the search condition; SkipRecord represents how many
records should be skipped before starting the search; SearchDirection indicates the direction the
search will proceed, Start is an optional bookmark that specifies the record from which the Search
should begin.
In ADO you can save the Recordset object to a disk file and can reopen it when necessary. This can
be done by using the Save method. It has the following syntax:
Save [FileName], [PersistFormat]
Where FileName represents the name of the file in which the Recordset will be saved and the
PersistFormat represents the format in which the recordset will be saved.
3. Command Object
The execution of a specific query or a command that you want to execute in a database is carried
out through the Command object. It is very useful when you want to reuse commands or invoke
parameterized queries.

The important properties of the Command object are given below:


The CommandText property contains the SQL command or the name of the query that you want to
execute for a database provider. It is used to instruct the Command object what to do to the data
source.
The property ActiveConnection represents the definition of the Connection object that is currently
working with the database.
The CommandType property represents what the CommandText string contains. For example if it is
set to adCmdStoredProc, then it is a stored procedure.
The Prepared property is used to tell whether the compiled procedure is to be saved or not. If this
property is true, the provider creates a prepared (saved) version of a query passed in the
CommandText property and then uses it to run the query each time when the command is
reexecuted.
The CommandTimeout property is same as that of the Connection object. It is the time interval in
seconds, that indicates how much time it should wait while executing a command before
terminating the attempt and generating an error message.
The State property represents the current state of the database at any time.
The important methods of the Command object are given below:
229
The Execute method is used to run the query or a command stored in the CommandText property.
The syntax for the Execute method is given below:
Execute([RecordsAffected], [Parameters], [Options]) As Recordset
Where the argument RecordsAffected represents the number of records that the operation affects;
Parameter is the array of parameter values passed in the SQL statement and Options represents
the value that tells how the provider should evaluate the CommandText property of the Command
object.
The Cancel method is used to cancel the execution of the Command object's asynchronous
operation.
The CreateParameter method is used to create a new parameter object. The syntax for
CreateParameter is given below:
CreateParameter([Name], [Type], [Direction], [Size], [Value]) As Parameter
Where,
Name argument is a string that representing the name of the parameter object, Type is a string
that represents the datatype of the parameter object, The Direction argument tells the value that
represents the type of the parameter object and Size represents the maximum length of a
parameter in bytes.
4. Field Object
The Field object represents one column in a Data source of the same datatype.
The important properties of the Field Object are given below:
The Name property is the name of the database column from which the Field object takes the data.
The Type property represents the constant that defines the kind of values which is stored in a field.
The DefinedSize property represents the maximum capacity that was defined when the field was
created.
The Attributes property is used to represent the value that returns the information about the field.
The Value property is used to set the contents of the field.
The ActualSize property defines the number of bytes taken by the current value in the field.
The OriginalValue property represents the value that was in the field before any changes were
made.
The important methods for the Field Object are given below:
The AppendChunk method appends a chunk of data to a large text or binary field.
The GetChunk method is used to take back the data stored in a Field that contains a large text or
binary field.
5. Parameter Object
The Parameter object defines a parameter in a command or a stored procedure on which the
command object is based.
The important properties of the Parameter object are given below:
The characteristics of a parameter object are represented by the Attributes property.
The Direction property represents whether the Parameter object represents an input parameter, an
output parameter, or the return value from a stored procedure.
The Size property represents the maximum size value of a parameter object.
The parameter object also has the properties such as Name, Type, Precision and NumericScale
property which are same as that of the Field object.
The Parameter object has only the AppendChunk method, which is similar to that of the Field
object.
6. Property Object
The Property object defines the characteristics of an ADO object. The ADO Object model has two
types of properties: built-in and dynamic.
The Built-in properties are those properties, which are available to any new object.

230
The Dynamic properties are those which are defined by the corresponding data provider and
appear in the properties collection of the ADO object.
In the next topic you can learn how to work with ADO events.
3. Explain the important events in the OLE DB?
The important events of the OLE DB are given below:
Two important events when establishing a connection are the WillConnect event and
ConnectComplete event. The WillConnect event will fire immediately before a connection is
established and the ConnectComplete event will fire after the connection is established.
The events that are related to the Execution of a command are the WillExecute and
ExecuteComplete events. The WillExecute event occurs before a command is executed on the
connection and the event ExecuteComplete fires immediately after it has completed.
The event that is related to transactions is known as the BeginTransComplete event. The
BeginTransComplete event occurs when a BeginTrans method has completed execution.
The InfoMessage event occurs when the database engine sends a message or warning.
After the connection has been established, the Recordset formation can begin. The events that are
related with the Recordset are given below.
The FetchProgress event occurs while a lengthy operation is taking place. For example you can use
this to show a progress bar that indicates the percentage of records retrieved.
The Navigation operations will trigger the WillMove and MoveComplete events. The WillMove event
occurs each time the current record begins to change and the MoveComplete event fires as soon as
the Movement completes.
The WillChangeField event occurs when you begin the process of modifying one or more fields in a
Recordset and the FieldChangeComplete event occurs when the Update operation is completed.
The WillChangeRecordset event occurs whenever the ADO is going to change the contents of the
Recordset as a whole. The RecordsetChangeComplete event occurs immediately after a change
occurs in the Recordset.
Exercise - Solution
Create a database application, which can access a database using DAO, ADO and ODBC. Compare
the differences?
Solution
In this sample we can use the employee database. You can refer sample project given in chapter 8
for database connection using DAO, sample project in chapter 9 for database connection using
ODBC and sample project in chapter 11 for database connection using ADO.
Comparison between DAO, ODBC and ADO
The DAO and ODBC both have the Database Manipulation Language (DML) support, but for ODBC
the Database Definition Language (DDL) support is possible only through direct ODBC calls. Both
can access the ODBC data sources and Microsoft Access data sources. ODBC is available in 16-bit
and 32-bit but the DAO is not available in 16-bit. ODBC is optimal for any data source, which has a
Driver and the DAO is optimal for the Microsoft Access Database. DAO is has Database Compaction
capability but ODBC does not. DAO has updatable joins but ODBC does not have.
The peculiarity of ADO is that it has independent objects for creating and manipulating the
database. The three main independent objects are the Connection object, the Recordset object, and
the Command object. The Connection Object is used for creating and maintaining a connection with
a data source. You will learn the ADO Connection object concept in detail in the following chapters.
You can even create and can set the properties before the connection is opened.

231
CHAPTER 12
Introduction to The Data Environment Designer
An interactive and design time environment for creating programmatic run-time data access is
provided by the Data Environment Designer. A Data Environment Designer can be easily added to a
Visual Basic project. It provides a means to access data easily. The Data Environment Objects can
be dragged to forms or reports to create data-bound controls. The Data Environment Designer
helps you to create Connection objects. It also helps you to create Command objects and
hierarchies of commands and to create code for Connection and Recordset objects.
Advantages of Data Environment Designer
The Data Environment Objects can be used to create ADO objects at design time instead of using
the ActiveX UserConnection to create Remote Data Objects (RDO). It has all the capabilities of the
UserConnection Designer plus:
 Multiple Connection objects.
 Connection and Command objects.
 OLE DB and ODBC data sources.
 Drag-and-drop support that allows you to drag Data Environment designer objects onto a
form or report creating data-bound controls.
 Execution of commands in the Data Environment as programmatic runtime methods.
 Programmatic access to a Data Environment that is bound to controls on a form without a
variable reference.
 The ability to group Command objects to create a grouped hierarchy.
 The Data Environment extensibility object model, which allows you to create add-ins.
In the next topic, you can learn about Data Environment objects.
Data Environment Objects
A Data Environment Object can be created at design time using the Data Environment Designer. It
can include Connection and Command objects, relationships between Command objects and
groups. You should determine your run-time objectives before designing the Data Environment
objects. Also you should determine what information you want to present and from which database
the information should be taken.
The Data Environment can be referenced in Visual Basic by selecting Microsoft Data Environment
from the References dialog box on the Project menu. For that do the following steps:
Step 1:
Select the References menu item from the Project menu.
Step 2:
The Reference Dialog will appear as shown below.

232
Step 3:
Select the Microsoft Data Environment 1.0 as shown in the figure.
Step 4:
Select More ActiveX Designers... then Data Environment from the Project menu.
The Data Environment designer window will appear as shown below.

After adding the Data Environment designer, a connection can be created and Commands can be
added to it.
Connection Objects
A Connection object represents a connection to a remote database. This database will be used as a
data source. At least one Connection object should be created in a Data Environment. When a Data
233
Environment is added to the Visual Basic project, a new Connection will be automatically created.
The Connection will be opened at design time and the Data Environment will retrieve metadata
from this Connection.
To create a Connection object:
Step 1:
Click Add Connection on the Data Environment designer toolbar or select Add Connection from the
shortcut menu opened by right-clicking the Data Environment designer.
A Connection will be created with the name "Connection" followed by a number.
Step 2:
Modify the Properties by selecting Properties from the menu opened by right-clicking the
Connection object. The Data Link Properties dialog is shown below.

Step 3:
The default name can be changed in the Properties window. Specify the connection information on
the Provider and Connection tabs in the Data Link Properties dialog box.
If the database accessed with Connection object requires any authentication information, then
logon information should be supplied. You can specify the user identification and password in the
Visual Basic Properties window. The logon information specified in the Visual basic Properties
window overrides that specified in the Data Link Properties dialog box. Advanced options like
Connection and Command timeouts and network settings can also be set in the Data Link
Properties dialog box.
Command Objects
Details about what information should be retrieved from a database connection is given by the
Command object. They can be based on either a database object or a SQL query. Relationships
between Command objects can be created to retrieve a set of related data. A Command object
should always be associated with a Connection object.
A Command object can be said to be "recordset returning" if it returns data and "non-recordset
returning" if it does not return data. The data returned can be accessed using a Recordset object
available from the DataEnvironment object. The Data Environment Designer automatically
identifies whether the Command is recordset returning or not.
Step 1:
A Command object can be added by right-clicking the Connection object. Then a Command1
properties dialog box will appear. The Command1 Properties dialog box is shown below.

234
Step 2:
In the General Tab of the Command1 Properties dialog box insert the command1 name and select
the appropriate connection. Next, select the Database Object Name. It may be a Stored
Procedure or a Table or a View etc. Then select the Object Name. This is the procedure for
establishing a connection with a database.
Commands objects can be automatically created by dragging from the Data View window to the
Data Environment designer. If the Connection associated with the Command object being dropped
does exists, it will be automatically created.
Using the Insert Procedure dialog box, multiple Command objects can be created. To create
multiple Command objects , first you have to insert multiple stored procedures. For that open Insert
Stored Procedures dialog box from the Data Environment designer toolbar. In the dialog box, move
the required procedures from the Available list to the Add list and click Insert to add them to the
Data Environment. A new Command object will be created for each stored procedure.
Mapping Fields
The Data Environment allows you to drag fields from it to a form or report. Based on the data type
of the field , you can specify what control is created when a field is dropped. In the design time
three levels of controls can be specified - Field object, Ado data type, and field type categories.
In the Field object level, a control can be directly associated with a field object in a Command
object. Here the control is specified as a property of the field. The Data Environment moves to the
next level if no control is specified. Here a control is associated with a specific ADO data type and it
will be created when a field of its type is dropped on the form. The Data Environment will move to
the next level if no control is associated with the specific Ado object type. A set of field type
categories are defined because there exists a large number of ADO data types that store similar
data. The control associated with the Field type that contains the ADO data type will be used if no
control is associated with the specific ADO data type. The system defaults to an intrinsic TextBox
control if no control is associated with the Field Type category.
Next topic describes how to work with Data Environment Designer.
Working with The Data Environment Designer
How to view objects within the Data Environment designer, modify and delete objects, refresh
Command and Connection objects, and set Data Environment designer options, are discussed in
this topic.

235
Views of the Data Environment Designer
The outline view of the Data Environment designer window shows the defined Connection and
Command objects. It can be arranged either by object type or by connection and to display or hide
the field objects of each Command object.
View By Connection
Here the objects are connected grouped by connection. In this view, the association of Command
objects with Connection objects can be easily seen. Click the Arrange by Connection button in the
Data Environment designer toolbar to view objects by connection.
View By Object
Here the objects of the same type are grouped together. This helps to focus on objects of a specific
type. Click the Arrange by Objects button in the Data environment designer toolbar to view by
objects.
Hide Field Objects
The Field objects of each Command object will be displayed in the outline view of the Data
Environment designer. The relationships between Command objects can be clearly viewed by
hiding all Field objects from the outline view. To hide them right-click on the Data Environment
object and clear the selection "Show Fields" from the shortcut menu.
Modifying an Object
Any existing Command or Connection object in the Data Environment can be modified by accessing
either its Properties dialog box or the Visual Basic Properties window. Common modifications
include renaming an object, changing a Command object's connection source and adjusting the
logon information of a Connection object. Right-click the object that you want to modify the
properties, and choose Properties menu. Make necessary changes in the Properties dialog box.
Deleting an Object
Objects like Data Environment Connection or Command can be removed from the Data
Environment designer. An object can be deleted with or without other objects that are dependent
on it. When a Command object is deleted, any other Command objects associated with it become
invalid. To delete an object, select it and press Delete.
Refreshing an Object
The functioning of the refresh function is different in Connection and Command objects. In the case
of a Connection object, the connection will be closed and the internal cache will be cleared of the
metadata, when a refresh is performed. This does not automatically refresh the Command objects
associated with the Connection object. In the case of Command objects all the metadata stored
with the object will be rebuilt when a refresh is performed. To refresh a Command or Connection
object, select the object and click Refresh in the Data Environment designer toolbar. They are also
refreshed whenever their respective source properties are modified.
Using the Data Environment with an Application
The Data Environment creates ADO Command and Connection objects for each Command and
Connection object defined in the Data Environment designer at run time. An ADO Recordset object
will be created if the Command object is marked as Recordset Returning. Data Environment can be
used as a direct data source for data binding to controls on a form. At run time it can be used to
programmatically create an instance of the Data Environment and execute its Command objects.
The run-time Data Environment contains Commands, Connections, and Recordsets collections.
When the Command method corresponding to a Recordset object executes, the Recordset object
will open. A Recordset object can be directly opened using the ADO Open method.
Next topic gives an introduction to the Data Report designer.
Data Report Designer
The Data Report Designer is a tool used for generating reports including hierarchical reports.
Reports from several relational databases can be created using Data Report Designer. Reports can

236
be exported in HTML format, so that they can be distributed on the Internet. The Data Environment
Designer can be used as a data source for generating reports.
Some of the features of Data Report Designer are:
1.
Drag-and-Drop Functionality—Fields and Command object can be dragged from the Data
Environment designer to the Data Report designer while creating the report. During this
process, a text box control will be automatically created on the data report. The
DataMember and DataField properties for text box control will be set with appropriate
values.
2.
Toolbox Controls—Controls will be created in a new toolbox when the Data Report
designer is added to a project. These controls will be identical to those in Visual Basic in
their function.
3.
Preview and Print Reports—Using the Show method, a preview of the report can be seen.
Using the PrintReport method, the report can be printed programmatically. The report can
also be printed in the preview mode by clicking the Printer icon in the toolbar
4.
Export Files and Templates—Using the ExportReport method, the data report information
can be exported in HTML or text format. A collection of file templates can be created and
used with the ExportReport method, so that a variety of formats can be exported.
5.
Asynchronous Operation—The state of asynchronous operations like PrintReport and
ExportReport methods can be monitored using the ProcessingTimeout event.
The following objects are present in Data Report designer
1.
DataReport object — It has a visual designer where the layout of the report can be
created and a code module where code can be written to format controls or sections.
2.
Section object — The Section object represents each section of the Data Report designer.
They can be used to dynamically reconfigure a report before it is built.
3.
Data Report Controls — These are special controls placed on the tab DataReport in Visual
Basic.
The sections in Data Report designer are:
1.
Report Header— contains the report title, author name, or database name.
2.
Page Header—contains information that is to be displayed at the top of every page.
3.
Group Header/Footer—contains a repeating section.
4.
Details—contains the innermost repeating part.
5.
Page Footer—contains the information that is to be displayed at the bottom of every page.
6.
Report Footer—contains the summary information, or contact address.
In the Data Report Designer, you can clearly view these sections. The figure of Data Report control
is given below.

237
The Controls in Data Report Designer are:
1.
Label Control (RptLabel)—used to place labels on the report to identify fields or sections.
2.
TextBox Control (RptTextBox)—used to format text.
3.
Image Control (RptImage)—helps to place graphics on the report.
4.
Line Control (RptLine)—used to draw rules on the report, so that sections can be
distinguished.
5.
Shape Control (RptShape)—used to place rectangles, triangles and circles on a report.
6.
Function Control (RptFunction)—used to calculate values when a report is generated.
Some key events of Data Report are given below.
1.
Initialize-invoked when a query has completed and controls are on the form.
2.
Resize-invoked when the window state of an object is changed.
3.
Activate/Deactivate-invoked when the Data Report designer becomes the active/inactive
window.
4.
ProcessingTimeout-invoked every second after the query has completed and until all
processing has finished.
5.
QueryClose-invoked before the designer is terminated.
6.
Terminate-invoked when all references to the designer becomes 0.
Next topic describes how to create a Data Report.
Creating a Data Report
An idea of how to create a Data Report using Data Environment designer as the data source is
given in this topic. You can create the Data Report using a few fields in the Data Environment
Designer. First you can create a Data Environment designer. Follow the steps given below to create
a Data Environment designer.
1.
Start a new Standard EXE project.
2.
Click Add Data Environment on the Project Menu. If Project Menu does not contain the
designer, then go to Components/Designers tab and click Data Environment.
3.
Give the name of OLE DB provider on the Data Link Properties dialog box.
4. Go to Connection tab. Select Access Database and give the name of the database file from
which you want to get data.

238
5. Give the properties like Command name, Connection, Database object and object name in
the Command dialog box. The Command dialog box can be opened by right clicking the
Connection icon and then clicking the Add Command.
6.
If you want to create a child Command object, right click the parent object and click on Add
Child Command. A dialog box will be opened where you can set the properties of child
Command object. Check the Relate to a Parent Command Object check box in the
Relation tab. Do not create more than one child Command for a Command object, because
Data Report can display only the first of the child Commands.
7. Add the relation to the Command object by clicking the Add button and then close the dialog
box. Now the Data Environment Designer displays the commands in a hierarchy.
8. Save the project after giving the Data Environment name and Project name.
To create the Data Report, follow the steps given below,
1.
Click Add Data Report on the Project Menu. If Project Menu does not contain the designer,
then go to Components/Designers tab and click Data Report. Then a Data Report control will
appear on the from. It is shown below.

2. After adding the Data Report set the properties of objects, like name, caption, DataSource
and DataMember. Before setting the DataSource property, open the Data Environment
Designer.
3.
Right-click the Data Report designer. Then click Retrieve Structure. An appropriate
number of Group headers and footers will be created after retrieving the structure. Each
header/footer pair will be assigned a name that corresponds to a Command object.
4. Drag the fields of the Command object from the Data Environment designer to the Group
Header section. Each group header section will have a one-to-one relation to a Command
object and also a matching group footer section.
5. Drag the TextBox controls from the section where they are created onto a different section
of the Data Report designer.

239
6.
Check the Drag and Drop Fields Caption option on the Field Mapping tab of the Data
Environment designer's Options dialog box to include a Label control with a TextBox
control. Otherwise uncheck this option.
7. Drag the fields of the child Command to the Details section which corresponds to the lowest
Command object in the Data Environment hierarchy ( i.e. the Command objects should be
dragged to the corresponding section of the Data Report designer).
8. Add necessary function controls.
9. Save the project.
Next topic describes how to preview and print a Data Report.
Previewing and Printing a Data Report
Previewing a Data Report
The Data Report which you have created can be viewed at runtime by writing code for a Command
Button in the Visual Basic project. Follow the steps given below for previewing the report.
1.
To display the Form designer, double-click the frmShowReport icon on the Project
Explorer window.
2.
Next, click the General tab on Toolbox, so that you can use standard Visual Basic Controls.
3.
Place a Command Button on the form.
4. Set the name and caption properties of the CommandButton.
5. In the Click event of CommandButton,write the following code:
rptABC.Show 'where rptABC is the name of the report.
6. Save the project.
7. Run the project and click the button to display the report in print preview mode.
Exporting a Data Report
The ExportReport method in Data Report Designer helps you to reuse a report as part of a large
document or for distribution on a network. The report can be exported either as text file or as an
HTML file. Images and graphics cannot be exported using ExportReport method. ExportFormat
objects can be used to modify the content and appearance of an exported file. Each ExportFormat
describes a separate format for the report. The Four default ExportFormats are HTML, unicode
HTML, text and unicode text. These default formats can be specified using their Key property.
Printing a Data Report
A data report can be printed either by clicking the Print button that appears on the data report in
Print Preview mode (using the Show method), or by using the PrintReport method in the program.
If you are printing the report programmatically, then you can display a Print dialog box with the
help of a CommandButton. For that place a CommandButton on the form and in the Click event of
the button, write the following code,
rptABC.PrintReport True
You can print without displaying the Print dialog box by writing the following statement in the Click
event of the CommandButton,
rptABC.PrintReport False
In the next topic a brief description of Data View window is given.
Data View Window
The Data View is a tool that is capable of editing the attached databases without breaking the
connection. It provides a graphical means for organizing the database objects.
You can open the Data View window by clicking Data View on the view menu or click the Data View
button on the standard toolbar. The following screen will appear.

240
The Data View window can be used for creating new database connections. This can be done by the
following procedure. Right-click on the node Data Link and choose the option Add Data Link. Then
the following screen will be seen.

Click on the Connection tab to display the following screen.

241
Choose the appropriate DataSource name and enter the user name and password.
The Data View window can be used for manipulating the tables in a database.
You can also manipulate the attached tables. Select and open the table folder in the data source.
Then right click the folder and select New Table from the table. Thus you can add, delete or modify
tables in the database.
Sample Application - The Data Environment Designer
This application is for understanding the workings of the Data Environment Designer. Here the
Biblio database is used which is provided with Microsoft Visual Studio.
Step 1:
Start a Standard EXE project.
Step 2:
Select the Microsoft Data Environment 1.0 from the Reference Dialog.
Step 3:
Select the Data Environment from the More ActiveX Designers menu item of the Project.
Step 4:
The Data Environment window will appear. In the Data Environment window, select the properties
of Connection1. Then the Data Link properties dialog box will appear.
Step 5:
In the Data Link properties dialog, set the database provider to Microsoft Jet 3.51 OLE DB
Provider. Then press the Next button.
The figure of Data Link properties dialog is shown below.

242
Step 7:
Then in the connection tab select the database name. You can browse also. Here set the database
name as "C:\Program Files\Microsoft Visual Studio\VB98\Biblio.mdb" and you can also set the user
name and password.
Step 8:
Now the connection is established. You can test connection by pressing the Test Connection
button. If the connection is OK, you will see a displayed message "Test connection succeeded".
Step 9:
The next step is to create the Command object. For that select the Add Command by right clicking
the Connection object.
Step 10:
In the properties page of the Command1 object, set the Database Object as Table and set the
Object name as "Authors" as shown below.

243
Now the Command object is created for your application.
Step 11:
The next step is designing the front end . For that create three Text Boxes and three Label Controls
and set their properties as below:
Control Name Data
Caption/ Text Data Source Data Member
Name Property Field
TextBox1 txtAu_id (empty) Data Environment Command1 Au_ID
TextBox2 txtAuthor (empty) Data Environment Command1 Author
TextBox3 txtYearborn (empty) Data Environment Command1 Year Born
Label1 lblAu_id Author ID (empty) (empty) (empty)
Label2 lblAuthor Author (empty) (empty) (empty)
Label3 lblYearBorn Year Born (empty) (empty) (empty)
Step 12:
Run the application.
The running form of this application is shown below.

Sample Application - The Data Report Designer


This application is actually a continuation of the previous sample application. Here you can
understand all the concepts of the Data Report Designer. In the previous sample, you made a
connection and a command object with the Biblio database. Here you can create a Report from that
database.
Follow the steps given below:
Step 1:
244
Open the Data Environment application form and place a Command button on it. Select the Add
Data Report menu item from the Project menu.
Set the properties of command button to:
Name - cmd_Show
Caption - Report
Step 2:
Next, set the properties of DataReport to:

Property Name Settings


Name rptBiblio
DataSource DataEnvironment1
DataMember Command1
Step 3:
Now, from the Data Environment Designer, drag the Command1 object onto the details section of
the rptBiblio.
Step 4:
Place the Labels and set their captions in the Header section.
Step 5:
Save the Project. Then write the following code in the Click event of the Command button
cmd_Show.
Private Sub cmd_Show_Click()
'For showing the Report
rptBiblio.Show
End Sub
Step 6:
Finally, Run the application.
The output of this application is shown below.

In the run time, you can view the report preview by clicking the Report command button. The report
preview is given below.
Report Preview

245
Self Assessment
Select the correct answer.
(1). The Data Environment Designer is used for,
(a) Creating the Database Reports.
(b) Creating the Form Design.
(c) Establishing the Database connection.
(d) All the above.
(2). The Connection object represents:
(a) Connection to a Form.
(b) Connection to a Remote database.
(c) Connection to a Remote server.
(d) Connection between two objects.
(3). The Command object gives:
(a) information about data environment.
(b) information about remote database.
(c) information about what data should be retrieved from the database
connection.
(d) information about connection objects.
(4). Which item should be selected from the References Dialog Box to add the Data Environment
Designer?
(a) Microsoft Data Environment 1.0
(b) Microsoft Data Report Designer 6.0
(c) Microsoft Development Environment 6.0
(d) Microsoft Data Environment Instance 1.0
(5). Which of the following is not a feature of Data Report Designer
246
(a) Drag and Drop functionality
(b) Tool Box controls
(c) Preview and Print Reports
(d) Export Files and Templates
(e) None of the above
(6). Which of the following object is not an object of Data Report Designer
(a) Data Report control
(b) Section object
(c) Connection object
(d) Data Report object
(e) None of the above
(7). The section Details of Data Report is for:
(a) Keeping the report title
(b) Storing information to display of the top of each page
(c) Storing the innermost repeating part
(d) Keeping the summary of information
(8). Which control is used in data report designer to format text
(a) Label Control
(b) Text Box Control
(c) Shape control
(d) Line control
(9). Retrieve structure is used for:
(a) To get the details of database
(b) To retrieve the structure of Data report
(c) To format the Data report
(d) To access data from database

Workshops
1. What are the advantages of the Data Environment designer?
2. How can you create a connection and add Command objects into the data environment
designer?
3. How can you manipulate Data Environment objects?
4. What are the features of Data Report designer?
5. What are the various objects, sections, controls and events of Data Report Designer?
6. How a can a Data Report be previewed?
7. How can a Data Report be printed?
Exercise
Add a Data Environment designer and create a Data Report using the employee database described
in chapter 9.
Chapter - 12
Workshops - Solution

1. What are the advantages of the Data Environment designer?


The advantages of the data environment designer is explained below:
The Data Environment Objects can be used to create ADO objects at design time instead of using
the ActiveX UserConnection to create Remote Data Objects (RDO). It has all the capabilities of the
UserConnection Designer plus:
 Multiple Connection objects.
 Connection and Command objects.
 OLE DB and ODBC data sources.

247
 Drag-and-drop support that allows your to drag Data Environment designer objects onto a
form or report creating data-bound controls.
 Execution of commands in the Data Environment as programmatic runtime methods.
 Programmatic access to a Data Environment that is bound to controls on a form without a
variable reference.
 The ability to group Command objects to create a grouped hierarchy.
The Data Environment extensibility object model, which allows you to create add-ins.
2. How can you create a connection and add Command objects into the data
environment designer?
The steps for creating connection object are given below:
Step 1:
Click Add Connection on the Data Environment designer toolbar or select Add Connection from the
shortcut menu opened by right-clicking the Data Environment designer.
A Connection will be created with the name "Connection", followed by a number.
Step 2:
Modify the Properties by selecting Properties from the menu opened by right-clicking the
Connection object. The dialog is shown below.

Step 3:
The default name can be changed in the Properties window. Specify the connection information on
the Provider and Connection tabs in the Data Link Properties dialog box.
If the database accessed with Connection object requires any authentication information, then
logon information should be supplied. You can specify the user identification and password in the
Visual Basic Properties window. The logon information specified in the Visual basic Properties
window overrides that specified in the Data Link Properties dialog box. Advanced options like

248
Connection and Command timeouts and network settings can also be set in the Data Link
Properties dialog box.
The Command object can be created using the following steps.
Step 1:
A Command object can be added by right-clicking the Connection object. Then a Command1
properties dialog box will appear. The Command1 Properties dialog box is shown below.

Step 2:
In the General Tab of the Command1 Properties dialog box insert the command1 name and select
the appropriate connection. Next, select the Database Object Name. It may be a Stored
Procedure or a Table or a View etc. Then select the Object Name. This is the procedure for
establishing a connection with a database.
Using the Insert Procedure dialog box, multiple Command objects can be created. To create
multiple Command objects, first you have to insert multiple stored procedures. For that open Insert
Stored Procedures dialog box from the Data Environment designer toolbar. In the dialog box, move
the required procedures from the available list to the Add list and click Insert to add them to the
Data Environment. A new Command object will be created for each stored procedure.
3. How can you manipulate Data Environment objects?
The Data Environment objects can be modified by accessing either its Properties dialog box or the
Visual Basic Properties window. Common modifications include renaming an object, changing a
Command object's connection source and adjusting the logon information of a Connection object.
Right-click the object that you want to modify the properties, and choose Properties menu. Make
necessary changes in the Properties dialog box. For deleting an object select it and press the Delete
key.
The functioning of the refresh function is different in Connection and Command objects. In the case
of a Connection object, the connection will be closed and the internal cache will be cleared of the
metadata, when a refresh is performed. This does not automatically refresh the Command objects
associated with the Connection object. In the case of Command objects all the metadata stored
with the object will be rebuilt when a refresh is performed. To refresh a Command or Connection
object, select the object and click Refresh in the Data Environment designer toolbar. They are also
refreshed whenever their respective source properties are modified.
4. What are the features of Data Report designer?
249
The important features of the Data Report Designer are given below:
a. Drag-and-Drop Functionality—Fields and Command object can be dragged from the Data
Environment designer to the Data Report designer while creating the report. During this process, a
text box control will be automatically created on the data report. The DataMember and DataField
properties for text box control will be set with appropriate values.
b.Toolbox Controls—Controls will be created in a new toolbox when the Data Report designer is
added to a project. These controls will be identical to those in Visual Basic in their function.
c. Preview and Print Reports—Using the Show method, a preview of the report can be seen.
Using the PrintReport method, the report can be printed programmatically. The report can also be
printed in the preview mode by clicking the Printer icon in the toolbar.
d. Export Files and Templates—Using the ExportReport method, the data report information can
be exported in HTML or text format. A collection of file templates can be created and used with the
ExportReport method, so that a variety of formats can be exported.
e. Asynchronous Operation—The state of asynchronous operations like PrintReport and
ExportReport methods can be monitored using the ProcessingTimeout event.
5. What are the various objects, sections, controls and events of Data Report Designer?
The various objects in the Data Report Designer are given below:
a. DataReport object — It has a visual designer where the layout of the report can be created
and a code module where code can be written to format controls or sections.
b. Section object — The Section object represents each section of the Data Report designer. They
can be used to dynamically reconfigure a report before it is built.
c. Data Report Controls — These are special controls placed on the tab DataReport in Visual
Basic.
The following are the important sections in the Data Report Designer.
a. Report Header— contains the report title, author name, or database name.
b. Page Header—contains information that is to be displayed at the top of every page.
c. Group Header/Footer—contains a repeating section.
d. Details—contains the innermost repeating part.
e. Page Footer—contains the information that is to be displayed at the bottom of every
page.
f. Report Footer—contains the summary information, or contact address.
The Controls in Data Report Designer are:
a. Label Control (RptLabel)—used to place labels on the report to identify f ields or sections.
b. TextBox Control (RptTextBox)—used to format text.
c. Image Control (RptImage)—helps to place graphics on the report.
d. Line Control (RptLine)—used to draw rules on the report, so that sections can be distinguished.
e. Shape Control (RptShape)—used to place rectangles, triangles and circles on a
report.
f. Function Control (RptFunction)—used to calculate values when a report is
generated.
6.How can a Data Report be previewed?
Using the following steps you can preview the Data Report.
a. To display the Form designer, double-click the frmShowReport icon on the Project Explorer
window.
b. Next, click the General tab on Toolbox, so that you can use standard Visual Basic Controls.
c. Place a CommandButton on the form.
d. Set the name and caption properties of the CommandButton.
e. In the Click event of CommandButton, write the following code:
rptABC.Show 'where rptABC is the name of the report.
f. Save the project.
250
g. Run the project and click the button to display the report in print preview mode.
7. How can a Data Report be printed?
A data report can be printed either by clicking the Print button that appears on the data report in
Print Preview mode (using the Show method), or by using the PrintReport method in the program.
If you are printing the report programmatically, then you can display a Print dialog box with the
help of a CommandButton. For that, place a CommandButton on the form and in the Click event of
the button, write the following code,
rptABC.PrintReport = True
Then by clicking this button the report will be printed.
Exercise - Solution
This application explains how to use the Data Environment Designer. Here the employee database
described in chapter 9 is used.
Step 1:
Open the sample project described in Chapter 9.
Step 2:
Select the Microsoft Data Environment 1.0 from the Reference Dialog box.
Step 3:
Select the Data Environment from the More ActiveX Designers menu item from the Project
menu.
Step 4:
The Data Environment window will appear. In the Data Environment window, right-click the
Connection1 and select the properties. Then the Data Link properties dialog box will appear.
Step 5:
In the Data Link properties dialog, set the database provider to Microsoft OLE DB Provider for
ODBC Drivers. Then press the Next button.
The figure of Data Link properties dialog is shown below.

Step 7:
Then in the connection tab select the User data source name. Here set the data source name as
Employee and you can also set the user name and password if available.

251
Step 8:
Now the connection is established. You can test connection by pressing the Test Connection
button. If the connection is OK, you will see a message saying, "Test connection succeeded". The
Data Link Properties dialog with Connection tab opened is shown below.

Step 9:
The next step is to create the Command object. For that select the item Add Command by right-
clicking the Connection1 object.
Step 10:
In the properties page of the Command1 object, set the Command Name as Employee, Database
Object as Table and set the Object name as "emptab" as shown below.

Now the Command object is created for your application.


Step 11:
After creating the Command object, you have to add the data report to the application. For that
select the Add Data Report menu item from the Project menu. The Data Report control will be
displayed.
Step 12:
Next, set the properties of Data Report control as given below.
Property Name Settings

252
Name EmpReport
DataSource DataEnvironment1
DataMember Employee
Step 13:
Now, from the Data Environment Designer, drag the table fields onto the Details section of the Data
Report, EmpReport.

The Data Environment Designer Window is shown below.

Step 14:
Place the Labels and set their captions in the Header section. Insert a line control below the
headings. Then the Data Report will look as shown below.

Step 15:
Save the Project. Then add a Command Button on the form from which you want to call the report
and set its properties as given below.
Name - cmdReport
Caption - Report

Step 16:
Then write the following code in the Click event of the Command button cmdReport.

253
Private Sub cmdReport_Click()
’ For refreshing the report
EmpReport.Refresh
' For showing the Report
EmpReport.Show
End Sub
Step 17:
Save and run the application. By clicking the “Report” button, the report will be displayed as shown
below.

254
CHAPTER 13
Introduction to Internet Programming
Internet is a commonly used term in this Information Technology era. The term Internet means a
network of networks. It allows communication between any two parts of the world. Special types of
files are needed for communicating through the Internet. Internet programming can be done with
Microsoft Visual Basic. By using the Microsoft Visual Basic, you can create applications to publish
and distribute information throughout the world.
Two important Internet related topics are Active Server Pages (ASP) and the scripting language -
VBScript are discussed in this chapter. In the second sample program you can see how a simple
Internet Browser is created.
The Active Server Page (ASP) is introduced to overcome some of the limitations of the Hyper Text
Markup Language (HTML) pages. ASP has mechanisms to provide user sessions on the web.
The VBScript is a scripting language which is embedded directly into a Web page. It has all the
syntax and structure of the Visual Basic language. You can get a good idea of VBScript while going
through the section on VBScript.
In the next topic, you will get an overview of ASP.
Introduction to ASP

Active Server Pages (ASP) is a technology used for server-side application development. With the
help of ASP, web developers can create dynamic web pages. ASP allows web programmers to
interact with existing systems like databases, mail servers, document retrieval services and COM-
based information services. It allows you to include executable script in HTML pages so that users
can interact with remote systems through the Internet. It is an interpreted language and therefore
needs no additional activity other than writing the program.
To reduce the work often associated with server-side programming, a number of built-in objects
and components are provide with ASP. They can be used to help you easily handle HTTP requests
and responses, the user's session and the Web environment.
ASP file
Files with extension .ASP are created when writing ASP programs. Web sites can be activated with
ASP files by using any combination of HTML, scripting and components. The scripts you write can be
used to assign values to variables, request information from the server, or combine any set of
commands into procedures. An advantage of using ASP is that a change made on the ASP file on
the server will be reflected on the web page, the next time the browser is refreshed.
When a user sends a request for an ASP file from the Web server, the Web server calls Active
Server Pages to read through the ASP file. The commands contained within the ASP file will be
executed and the resulting HTML page will be send to the user's browser.
Built-in objects
Standard objects used in ASP are
 Request - used to receive information from the user passed along with an HTTP request.
 Response - used to send information back to the user.
 Server - used to control the server (Internet Information Server).
 Session - used to store information about the current session of a user.
 Application - used to share application-level information and control settings.
An overview of VBScript is given in the next topic.
VBScript
VBScript Basics
VBScript brings active scripting to the Web. Microsoft Internet Explorer version 3.0 and above can
run VBScript programs. VB script programs are included within browsed HTML pages. VBScript can

255
be used to validate Form data on as web page, automatically generate custom pages etc. VBScript
is based on Visual Basic and therefore easy to learn.
Using VBScript in HTML

HTML code is written within control "tags". There are different tags used in HTML. For example, the
text in HTML is written within the pair of tags identifying the main, viewable part of the document.
The <BODY> </BODY> pair contain the viewable portion of a document.

The script language you will use should be specified in the SCRIPT tag as follows,
<SCRIPT LANGUAGE="VBScript">
</SCRIPT>
Data Types in VBScript
Variant is the only data type in VBScript. It can contain any kind of information either numeric or
string. A variant behaves differently depending upon the type of information stored in it. A Variant
can make distinctions about the specific nature of numeric, simple numeric and string information.
All functions in VBScript returns Variant data type since it is the only data type allowed.
The various subtypes of data that a Variant can contain, are listed below.
Type Value /Range
Value is 0 for numeric variables and zero-length string for string
Empty
variables when Variant is not initialized.
Null No data exist.
Boolean Value is either True or False.
Byte Integer between 0 and 255.
Integer Integer in the range -32,768 to 32,767.
Integer will be in the range -2,147,483,648 to 2,147,483,647. Single
contains a single-precision, floating-point number in the range -
Long
3.402823E38 to -1.401298E-45 for negative values; 1.401298E-45 to
3.402823E38 for positive values.
Double-precision is floating-point number in the range -
1.79769313486232E308 to -4.94065645841247E-324 for negative
Double
values; 4.94065645841247E-324 to 1.79769313486232E308 for
positive values.
Date It is a number that represents the date between January 1, 100 to
(Time) December 31, 9999.
Object Contains an object.
Error Contains an error number.
VBScript Variables
A variable is a name that points to a memory location where you can store data which can change
during the execution of the program. The actual location of the variable in the computer memory is
irrelevant. The value of the variable can be retrieved or changed by referring it with a name.
Declaring variables
Dim statement can be used to declare variables explicitly as shown below,
<SCRIPT LANGUAGE="VBScript">
<!--
Dim abc
-->
</SCRIPT>

256
Multiple variables can be declared by separating each variable name with a comma. For example:
<SCRIPT LANGUAGE="VBScript">
<!--
Dim X,Y,Z
-->
</SCRIPT>
A variable can also be declared implicitly by simply using its name in the script. In that case
misspelling a variable may cause the confusion of existence of two variables for the same purpose.
This may lead to false execution and bugs. Option Explicit statement can be used to force explicit
declaration of all variables. It can be included in the Script tag as the first statement.
Scope and lifetime of variables
Scope means the range of availability of a variable. Variables can be of two scopes. One is
procedure-level scope and other is script-level scope. In procedure-level scope, the variable can
only be used within a particular procedure. If a variable is defined with Script- level scope, then it
can be accessed by all procedures.
Scalars and arrays
A scalar variable is a variable with single value. A variable that can contain a series of values is
called an array variable. Array variables can be declared in the same way as declaring scalar
variables. The only difference is that they are declared with parentheses following the variable
name. For example,
<SCRIPT LANGUAGE="VBScript">
<!--
Dim Z(10)
-->
</SCRIPT>
Although the number shown in the parentheses is 10, the array actually contains 11 elements. The
arrays are zero-based, and the number of array elements will be one more than the number shown
in parentheses. An array with this features is called a fixed-size array.
VBScript Constants
Constants
A constant is a value that never changes during the execution of the script. VBScript does not have
any predefined constants. In VBScript constants are literal values assigned to variable names.
Creating constants
Constants are created using the Dim statement. The constants can be assigned literal values and
used in the script.
For example:
Dim Ourpage
Ourpage = "The web page string."
Dim Ourpage
Yourpage = 24
String literals are enclosed in quotation marks as shown. Using quotation marks, strings and
numeric data can be differentiated. You can represent Date/Time literals by enclosing them in
number signs (#).
For example:
Dim ApplDate
ApplDate = #11-21-99#
Operators
Operator precedence
VBScript has all common operators including arithmetic, comparison, concatenation and logical
operators. Operations will be performed in a specific order known as operator precedence.
257
Parentheses have the highest precedence. Multiplication and division are of equal precedence and
come after that of parenthesis. Addition and subtraction have equal precedence and follow
multiplication and division. Operators which have equal precedence will be evaluated from left to
right.
The string concatenation operator (&) falls between all arithmetic operators and before all
comparison operators. The IS operator checks whether two object references refer to the same
object.
Program Flow in VBScript
Program Execution
Conditional statements and looping statements can be used in VBScript to make decisions and
repeat actions.
Making decisions using If...Then...Else
The If...Then...Else statement is used to make decisions depending on whether a condition is True
or False. Depending on the result, the instructions after the if statements or after the else
statements will be executed. Comparison operators can be used in condition to compare two
variables or one variable with a constant value.
Running statements if a condition is true
If there is only one statement to execute according to a condition then simple If-Then can be used
in single line. The following example shows the single-line syntax without the Else keyword.
<SCRIPT LANGUAGE="VBScript">
<!--
Sub Greater()
Dim GRval
GRval = 10
If GRval < 100 Then GRval = 100
End Sub
-->
</SCRIPT>
If more than one statement are to be executed according to a condition, then multiline If-Then-Else
statement should be used with an end if indicating the end of the block of code.
Repeating Loops
Block of statements can be repeated using two types of loops. One type repeats the execution for a
predetermined period of time and the other type executes repeatedly depending on the outcome of
the program so far executed. The important looping structures are,
For...Next Loop
For...Next statement is used to run a block of statements a specific number of times. So this is an
example of determinate looping. The For loop uses a counter variable whose value is increased or
decreased in each repetition of the loop. For example, the following procedure causes a
procedure to execute 50 times. The For statement specifies the starting and ending values of the
counter variable A. The Next statement increments the counter variable by 1.
<SCRIPT LANGUAGE="VBScript">
<!--
Sub LoopProc ()
Dim A
For A = 1 To 25
MyProc
Next
End Sub
-->
</SCRIPT>
258
The Step keyword can be used to increase or decrease the counter variable by the value you
specify.
Sub procedures
A sub procedure is a set of statements given within Sub and EndSub statements.
Function procedures
Function procedures are enclosed between Function and End Function statement. Function
procedure return values while the Sub procedure returns no value. Arguments of any type can be
used in Function procedure that are passed to it by a calling procedure. If a Function procedure is
without arguments then the Function statement must be written with an empty set of parentheses.
Declaring procedures
Functions and procedures can be put inside the HEAD tag of the HTML document. All the
procedures and functions should be within the SCRIPT tag. An HTML comment tag is used inside
the <SCRIPT> tag to ensure that the statements in it are not displayed in browsers that do not
handle VBScript (Netscape).
Transforming Data into Procedures
Arguments are place holders used to pass values into procedures and functions. Parentheses are
used to list the arguments separated by commas.
Procedure using Sub Function
To use a function in your code, it should be used on the right side of a variable assignment. For
example:
<SCRIPT LANGUAGE="VBScript">
<!--
Temp = Celsius(fDeg)
-->
</SCRIPT>
or
<SCRIPT LANGUAGE="VBScript">
<!--
answer=MsgBox "The Celsius temperature is " & Celsius(fDeg) & " degrees."
-->
</SCRIPT>
A sub procedure can be called using the Call Statement with arguments in the parenthesis.
Sample Project - VBScript Programming
This is a sample application which helps you understand how to write VBScript in a browser based
application. In this application you can enter some data and can print it in an HTML page.
Enter the following code in between the <HEAD> and </HEAD> Tags
<SCRIPT>
<TITLE> This is a small VBScript application <TITLE>
<!--
<SCRIPT LANGUAGE="VBSCRIPT">
Option Explicit
Sub Welcome(Name)
Dim Reply
Reply=MsgBox("Hello " & Name & "! Welcome to the world of Visual Basic",64)
End sub
Sub Command1_OnClick()
Welcome Form1.Text1.Value
End Sub
-->
</SCRIPT>
259
Here we are using two functions. The first function Welcome is for displaying a welcome message
and the function written for the click event is for taking the text from the Text box and displaying it.
Write the following code between the <BODY> and </BODY> Tags.
<BODY>
<H2> Enter your Name:</H2>
< FORM NAME="Form1">
<input name="Text1" type="TEXT" value=" ">
<input name="Command1" type="BUTTON" value="Say Welcome">
</FORM>
</BODY>
Now save the file with extension .HTML and then open it in Internet Explorer. You can see the
output by clicking here.
Missing data 13.4.1
Sample Project - Internet Browser
This project will teach you to create a Web Browser within a Visual Basic Program. You can also
learn how to the use the Web Browser control. This is the general approach to understanding "WEB
Enabled applications".
Let's Start.
Step 1:
Start a Standard EXE Visual Basic Project.
Step 2:
Select and Place a Web Browser Component from the Components Gallery. (For Selecting the
Components Right Click on the Tool Box and Select the Components menu item). The component to
select from the component browser is called Microsoft Internet Controls.
Step 3:
Place a ComboBox and three Command Buttons on the form and make the Settings as follows.

Control Name Caption


Form frmWebBRO My Web Browser
Command Button1 cmdBrowser Browse
Command Button 2 cmdBack <<
Command Button 3 cmdForward >>
Combo Box cboList (empty)

Step 4:
On the Click Event of the Command Button, cmdBrowser, Add the following Code.
Private Sub cmdBrowser_Click()
'Navigate the Site
browWeb.Navigate (cboList.Text)
End Sub
Step 5:
On the Click Event of the cmdBack Button , Add the Following Code.
Private Sub cmdBack_Click()
'Method for Getting Back
browWeb.GoBack
End Sub
Step 6:
On the Click Event of the cmdForward Button , Add the Following Code.

260
Private Sub cmdBack_Click()
'Method for Getting Back
browWeb.GoBack
End Sub
Step 7:
On the Lost Focus Event of the Combo Box, Add the Following Code.
Private Sub cboList_LostFocus()
'For adding the item to the Browsing List
cboList.AddItem (cboList.Text)
End Sub
Step 8:
Save and run the application.
The output of this application is shown below.

Self Assessment
Select the correct answer.
(1) Which is the standard object in ASP.
(a) Request.
(b) Response.
(c) Server.
(d) Session.
(e) All the above.
(2) Active Server Pages create files with extension.
(a) .ACT
(b) .ASP
(c) .HTM
(d) .HTML
(e) None of the above.
(3) Which of the following cannot be accessed using ASP.
261
(a) Databases.
(b) Mail Servers.
(c) Document Retrieval Services.
(d) COM based information services
(e) None of the above.
(4) Which is the datatype used in VBScript.
(a) Integer.
(b) String.
(c) Variant.
(d) Boolean.
(5) Which tag is used for writing text in an HTML.
(a) Head.
(b) Title.
(c) Body
(d) table.
(e) None of the above.

Workshops
1. What is ASP? Explain its use.
2. What is the difference between ASP and HTML?
3. Explain how to declare a variable in VBScript? Give syntax.
4. Explain the syntax of looping statements in VBScript?
Exercise
Create a Web page having a TextBox to input data and two command buttons, one to display a
message by clicking it and other to reset the TextBox.
Chapter - 13
Workshops – Solution

1.
What is ASP? Explain its use?
Active Server Pages (ASP) is a technology used for server-side application development. With the
help of ASP, web developers can create dynamic web pages. ASP allows web programmers to
interact with existing systems like databases, mail servers, document retrieval services and COM-
based information services.
2. What is the difference between ASP and HTML?
Asp is the Server side scripting while the HTML is only the client side scripting. With ASP one can
create interactive web pages. But with HTML one can create only the static type of web pages. The
term static means that all the pages give the same appearance. ASP allows one to interact with
existing systems like databases, mail servers, document retrieval services and COM-based
information services. But with HTML one can not make any interactions.
3. Explain how to declare a variable in VBScript? Give syntax
A variable can be declared by using the DIM keyword. The Syntax for DIM keyword is: DIM varname
Example:
<SCRIPT LANGUAGE="VBScript">
<!--
Dim abc
-->
</SCRIPT>
4. Explain the syntax of a looping statement in VBScript?
The For…Next is an example of a looping statement. This statement can be used to run a block of
statements, a number of times. In the following example prints the alphabet ‘A’ up to 50 times.
262
Sub Print ()
Dim A
For A = 1 To 25
Print (“ A”)
Next
End Sub

Exercise - Solution
Create a Web page having a Textbox to input data and two command buttons, one to display a
message by on clicking it and other to reset the TextBox.
Solution
In this example you can create a web page with a Textbox and two command buttons.
For that enter the following code between the <HEAD> </HEAD>
<TITLE> Exercise13 Application</TITLE>
<SCRIPT LANGUAGE="VBSCRIPT">
<!--
Option Explicit
Sub Message (Name)
Dim Reply
Reply=MsgBox("Hello " & Name & "! You are lucky.",64)
End sub
Sub Command1_OnClick()
Welcome Form1.Text1.Value
End Sub
-->
</SCRIPT>
Write the following code between the <BODY> and </BODY> Tags.
<BODY>
<H2> Enter your Name:</H2>
<P>
<FORM NAME="Form1">
<input name="Text1" type="TEXT" value=" ">
<input name="Command1" type="BUTTON" value="Say Welcome"> <input
name="Command2" type="BUTTON" value= RESET>
</FORM>
</P>
</BODY>
Building Online Help
Every Windows application should have some type of help system. A help system uses a help file
that can be displayed by itself or from within a computer program. These help files are displayed as
a scrolling page with very little in the way of advanced options. A help system is made up of several
help files that are text or topic files. To design a help system you need WinHelp, the version of the
help engine with Windows’95 and Windows’ NT.
In Visual Basic, there is Microsoft Help Workshop that has the tools and information needed for
creating professional help files for Windows’95, Windows’98 and Windows NT based applications.
Before learning details of creating a Help system, you must know the windows standard Help
system. The windows help system includes a Help Topics dialog box.
The Help Topics Dialog Box

263
The help topics dialog box is a doorway to your application's help system and is created with
WinHelp. It consists of three tabbed pages to help the users locate the needed information. The
three tabbed pages are Contents page, Index page and Find page.
The contents page helps the user to display the help system topics by title. On the dialog box, the
topic headings are displayed as book icons whereas jumps to topics are displayed as page icons.
The figure of contents page is shown below.

The index page allows the users to look for topics based on keywords in the help file. The keywords
are sorted and one can navigate to the topics using them.

264
The Find page allows you to search the help file for topics that contain a specific word or phrase
specified by the user. The figure of Find page is given below.

Creating Topic Files


265
The steps involved in creating and compiling a topic file are,
1. Creating the topic information.
2. Formatting the text.
3. Separate the topics.
4. Give ID's to the topics so that WinHelp can find them.
5. Connecting the topics.
6. Adding graphics.
7. Saving the topic file.
8. Compiling it using Help Workshop.
Step 1:
To create the topics open Microsoft Word or WordPerfect. Start a new file. Type all the needed
information including the topic index as separate paragraphs.
Step 2:
Format the typed text in the desired font, size, style and color.
Step 3:
After formatting, you have to separate the paragraphs into different topics by inserting manual
page breaks.
Step 4:
All topics should have a unique ID, so that the WinHelp can find them easily. You can do this by
inserting a footnote for each topic. To insert a footnote place the cursor at the beginning of the
topic. Open the Footnote and Endnote dialog box by clicking Insert|Footnote menu item. The dialog
box is shown below,

Select the options Footnote and Custom mark. Corresponding to Custom mark give the appropriate
footnote symbol. The footnote symbols are,

# - used to create a tag to link from a jump phrase to its associated topic.
$ - used to define the jump page title, which will appear in the Search list box.
+ - used to define a browse code to specify the topic's position in a browse sequence.
K - used to define keywords to use in Index page for searching.

After giving the footnote a symbol, click OK. A footnote window will be displayed at the bottom of
the page. The footnote symbol you have given will be displayed there. Type a name for the
corresponding page close to this symbol. This will create an ID for that topic. Do these steps for
each of the pages. After creating ID's for each of the pages close the footnote window.

Step 5:

266
Using the topic ID's you create, you can make reference to any topic from anywhere in the help
system. To make a reference, first place the cursor at the end of the phrase that you want to act as
the link to a page. Type the topic ID of that page adjacent to the phrase. Single-underline the
phrase excluding the topic ID, if you want to open a pop-up topic and double-underline it to make a
jump to the related topic. Make the topic ID you have typed with the phrase as hidden text.

Step 6:

You can add an illustrative graphic to your Help topic. To include a graphic, place the cursor at the
beginning of the topic. From the Menu select Insert|Picture|From File. Select the required bitmap
from the Insert picture box.

Step 7:

After doing all these things, save the file in Rich Text Format ( with extension .RTF).

Step 8:

Compile the file using the Help work shop. The procedure is described below.

Using The Help Workshop

You can compile the help file you have created using the Help workshop. Open the Help Workshop
and start a new project. The project file contains all the instructions needed to compile the help
topic files into a working help. It can be displayed using the WinHelp engine. The figure of Help
Workshop is given below.

Starting a New Project

Choose File | New the Help Workshop. From the dialog box displayed, select Help Project and click
OK. The project Filename dialog box appears. Enter the name of the project and save it. You must
267
specify the location and name of each topic file to be included in each .Hlp file you create. To
specify the files, click the files button on the Workshop window. A Topic Files dialog box will be
displayed in which you can add or remove the file references to the project. Click the Add button to
display the Open dialog box. Select the RTF Topic file you created previously. Click the Open button
and then OK to add these files to the project. Click the Bitmaps button on the Workshop window to
display the Bitmaps Dialog box. Select the bitmaps and click OK.

The toolbar of the Workshop contains two buttons, one for compiling and the other for testing. By
clicking the Compile button the Compile a Help File dialog box will appear. In that give the file name
and click Compile. By clicking the Run button the View Help File dialog box will appear. In that give
the file name and click View Help. The help file will be displayed.

Mapping The Topic Ids

Each help topic has a unique number reference called the topic ID. Open the map dialog box by
clicking the map button on the Workshop window in which you can assign or map a value to a topic
ID. The map dialog box lists the topic Ids that have already been mapped with their related values.
To add a new topic ID to this list, click Add. Then the Add Map Entry dialog box will be displayed.
Here enter the topic Id of the topic in the .RTF file, a unique numeric value. You can also add a an
optional comment. Now you have created a working help system.

Creating The Help Topic Dialog Box

Help Topic dialog box is a doorway into the application’s help system and provides tabbed pages to
help users locate the needed information. For creating this dialog, you need to create the contents
file. For that choose File | New in the Help Workshop. Select help contents and then click OK. When
the contents file is first created, you need to specify default information for locating the entries in
the contents file, displaying the correct title at the top of the Help Topics dialog box and displaying
the help information in the correct window type. You can set this default information in the Default
Help Information dialog box. By clicking the Edit button you can display it.

Specify the title, Topic ID, help file to look in for given topic ID and the window type for displaying
the topic for every item you enter in the contents page. When adding items, the headings will be
identified by book icons that can be double-clicked to display the sub headings or topics they
contain. After saving the changes to the contents file, you can test it.
Enabling The Find Page
The Find page allows users to perform a full text search through every word in the help file. When
the users click the find tab for the first time, the Find Setup Wizard will setup the full text search
index. Users will have to do this only once, unless they deleted the index file (.Fts) that contains
this information.

Connecting Help with the Visual Basic application

After creating the help system, you have to connect it with the application you have created. You
can access the help system from Visual Basic using the Common Dialog control or by using built-in
help context features in Visual Basic.

To learn how Common Dialog control access help, start a new Visual Basic project. Place a Common
Dialog control and a Command Button on the form. Set the name and caption of Command button
as cmdHelp and Help. Set the name of Common Dialog control as dlgHelp and its HelpFile property
268
with the path and file name of the help file you have created.

On the Click event of the command button write the code as,
Private Sub cmdHelp_Click()
dlgHelp.HelpCommand = HelpFinder
dlgHelp.ShowHelp
EndSub
If an error showing that HelpFinder is not initialized is seen, you can initialize it in the general
section as
Const HelpFinder = &h00B

Save and run this application. By clicking the Help button, the Help Topic Dialog box will be
displayed. Write the code for a menu item and you can open the Help Topic Dialog box from the
menu.
In the coming topics, you will learn about Crystal Reports.
Introduction to Crystal Reports
The Crystal Report is a report writing tool with which you can add reports to your applications. It
was developed by Seagate Software. It is a powerful program for creating custom reports, lists and
labels from the data in the database. Crystal Reports 5.0 has the following features.
The Crystal Report is capable of faster design, seamless integration and has powerful capabilities at
run time. Using Crystal Reports you can create any type of report for about 130 software's of the
vendors like Microsoft, Oracle, etc.
The Crystal Reports can be used to create reports in various forms, like
1. Standard
2. Form Letter
3. Form
4. Cross Tab
5. Mail Label
6. Sub report
with the features given below.
a. It can do Calculations
b. It can calculate the subtotals and grand totals
c. It can calculate average values
d. It can count the total number of records in a query
e. It can filter the database records
f. It can test for the presence of specific values
Another important feature is that it can be used to export files to any format, like HTML and can
publish documents in Internet and Intranet Web servers.
In the next topic, you can learn how to create a Crystal Report.
Creating a Report
You can start Crystal Reports by choosing Crystal Reports 5.0 in the Programs menu. Then select
the 32-bit Crystal Reports Professional. The Steps for creating a report is given below:
Step 1:
Select File|New or Click New Button in the button bar, then a Report Gallery will appear as shown
below.

269
The Report gallery provides options to create the kind of report you want. The main feature of
Report gallery is that, it has experts to create popular forms of reports. Here you will create a
Standard Report.
Step 2:
Click on the Standard icon on the Report Gallery. Then the following dialog will be displayed.

Various options in this dialog are,


Data File - This option is used to load .mdb files (access databases).
Query - This option is useful if you are using SQL/ODBC datasource. You can use this when the
report is processed directly from the server.
SQL/ODBC - This option is used to create report by choosing appropriate DSN and tables.
Dictionary - This hides the complexity of data from the users. Users only need to know the name
of a dictionary to create reports.
Step 4:
In this application, you can use the Biblio database. Select the Data File option. Then the following
Dialog will be displayed.

270
Choose the Database file that you want to Add and then click Done.
Step 5:
This will list all tables in the database Biblio.mdb. Select the required table. Here you can select the
Publishers Table.
Step 6:
Then press Next to navigate between different Tabs allowing you to create the report.
Step 7:
Select the Fields tab for selecting the fields that you want to include in the report. It is shown in the
figure below.

Select the Fields that you want to add in the Report. Here select the Fields PubID, Name,
CompanyName, Address, Telephone from the Publishers Table. Then click the Sort tab.
Step 8:
The Sort tab is used to sort displayed figures in ascending or descending order. Here you can set
the sorting order. It is as shown in the figure below:

271
Step 9:
Click on the tab Style to select the appropriate style for your report. It is shown in the figure below.

Enter the title of your report then choose the style, such as tables, fonts, pictures. You can include
your company name also. In our report you can give the title as "Publisher Details" and select the
Standard format.
Step 10:
Click on the Preview Report button to view the Preview of the report as shown below.

272
Step 11:
You can format the report by selecting the Design tab of the Preview Report and move the fields.
The Design of this report is shown below.

Step 12:
Choose the required format and save the report.
273
InBands in the Crystal Reports
The Crystal Report is a banded report writer. Each band has its own processes and settings that you
can manipulate in order to create the report layout.
The Header band
The Header Band contains information that appear at the top of each page. This could be report
titles, page numbers, dates, etc.
The Detail band
This contains all the lines of the report. Each detail line represents a logical line.
The Footer Band
This contain the information that you need to display in the bottom of each page.
In the next topic you can study how to add necessary fields to the Report.

the next topic, the Bands in a report are discussed .


Crystal Reports and Fields
Within each band, you can add the fields to be displayed. The Crystal Reports has three types of
fields.
a. Database Field
The Database fields are the fields taken directly from data tables in the database. To include a
database field you can choose the Database item from the Insert menu. The following screen will be
displayed.

You can add the fields by selecting them from a list of available fields and click on Insert to place
them in the desired location of the report.
b. Text Field
These fields contain the explicit text that you want to appear on the report form. This field is not
stored in a data table. To include a Text Field you can choose the Text Object from the Insert menu.
Here you can enter the text that you want to display.
c. Add Formula Field
The Formula fields are the calculated results field. To add a formula field choose the Formula Field
from the Insert menu. Then the following dialog will appear.

274
Click New in the dialog. Then a dialog will appear. Here enter the name of the formula as total and
click OK. Then the following screen will be displayed.

In this dialog box, you can enter the formula and press the Accept button. Then choose Insert in the
Insert Fields Dialog and include fields.
How to access the report from Visual Basic is discussed in the next topic.
Accessing A Report from Visual Basic
You can access the Crystal Report by placing the Crystal Report control from the Components tab.
For that follow the steps given below:
Step 1:
Select Crystal Report Control from the Components tab.
Step 2:
Add the control to your application.
Step 3:
Make the following property settings:
- the name of the report you want to print in response to the application event.
- the destination for the report to be printed ( a window, file or a printer).
- the number of copies you want to print.
275
- print file information.
- sorting information and so on.
Step 4:
Place a command button on the Form and name it cmdRptShow. Write the following code on its
Click event.
Private Sub cmdRptShow_Click()
crtPublisher.ReportFileName= "c:\publishers.rpt"
crtPublisher.Action=1
End Sub
Save and run the application.
Self Assessment
Select the correct answer.
1. The help engine which is available with Windows.
(a) WindowsHelp
(b) WinHelp 4.0
(c) HtmlHelpWorkshop
(d) All the above
(e) None of the above
2. The doorway to the Windows help system is
(a) The Help topics dialog box
(b) The WinHelp dialog box
(c) The Find tab dialog box
(d) The Index Tab dialog box
3. Crystal Reports is a product of:
(a) Microsoft Corporaton
(b) Segate Software
(c) Oracle corporation
(d) Sun Microsystems
4. The Report gallery is used for:
(a) Printing a report
(b) Previewing a report
(c) Designing a report
(d) All the above
5. A Crystal report is accessed from Visual Basic using:
(a) The Crystal Report control
(b) The Crystal Report editor
(c) Crystal Reports
(d) A Database Report editor.
(e) All the above
Workshop
1. Describe the structure of the Windows Help Workshop?
2. Describe the steps for creating, saving and compiling a Crystal Report?
3. What are the styles of a Report?
4. What are the type of bands available in the Crystal Reports?
5. How can you add the fields to a Report?.
Exercise
1. Create a Help system for your application.
2. Create a Crystal Report in a standard format.
Chapter - 14

276
Workshops – Solution
1. Describe the structure of Windows Help WorkShop?

The Help Workshop consists of three tabbed pages as described below.


a. Contents: This will page helps the user to display the help system topics by title. On the dialog
box, the topic headings are displayed as book icons whereas jumps to topics are displayed as page
icons.
b. The index page allows the users to look for topics based on keywords in the help file. The
keywords are sorted and one can navigate to the topics using them.
c. The Find page allows you to search the help file for topics that contain a specific word or phrase
specified by the user.

2. Describe the steps for creating, saving and compiling a Crystal Report?
The steps for creating a Crystal Report is given below:
Step 1:
Start the Crystal Reports then Select File| New. Then a report gallery will appear.
Step 2:
Select the Standard icon from the Report gallery. Then a dialog will appear.
Step 3:
Select the database from which the report is to be generated. Then press Next.
Step 4:
Select the fields that you need to convert include in the Report.
Step 5:
Select the Sort tab and select the field.
Step 6:
Select the Style that you need.
Step 7:
Select the preview button and arrange the report fields.
Step 8:
Then format the Report.

277
3. What are the styles of Report?
The important styles of the Report are given below:
a. Standard
b. Form Letter
c. Form
d. Cross Tab
e. Mail Label
f. Sub report
4. What are the types of bands available in the crystal Report?
The important types of bands of Crystal Report are given below.
The Header band
The Header Band contains information that appears at the top of each page. This could be report
titles, page numbers, dates, etc.
The Detail band
This contains all the lines of the report. Each detail line represents a logical line.
The Footer Band
This contains the information that you need to display in the bottom of each page.
5. How can you add the fields to a Report?
Select the Insert Fields option. Here you can select one of the options. The important fields are
Database, Formula, Parameter, and Group Name. Insert the corresponding data field. Thus you can
add the fields to a Report.

278
Exercises - Solution
1. Create a Help system for your application?
For including a help system for your application, the first step is to create a topic file, which will be
in .rtf format. The steps for creating topic files are given below.
Creating Topic Files
The steps involved in creating and compiling a topic file are,
1. Creating the topic information.
2. Formatting the text.
3. Separate the topics.
4. Give ID's to the topics so that WinHelp can find them.
5. Connecting the topics.
6. Adding graphics.
7. Saving the topic file.
8. Compiling it using Help Workshop.
Step 1:
To create the topics open Microsoft Word or WordPerfect. Start a new file. Type all the needed
information including the topic index as separate paragraphs.
Step 2:
Format the typed text in the desired font, size, style and color.
Step 3:
After formatting, you have to separate the paragraphs into different topics by inserting manual
page breaks.
Step 4:
All topics should have a unique ID, so that the WinHelp can find them easily. You can do this by
inserting a footnote for each topic. To insert a footnote, place the cursor at the beginning of the
topic. Open the Footnote and Endnote dialog box by clicking Insert | Footnote menu item.

279
The dialog box is shown below,

Select the options Footnote and Custom mark. Corresponding to Custom mark give the appropriate
footnote symbol. The footnote symbols are,
# - used to create a tag to link from a jump phrase to its associated topic.
$ - used to define the jump page title, which will appear in the Search list box.
+ - used to define a browse code to specify the topic's position in a browse sequence.
K - used to define keywords to use in Index page for searching.

After giving the footnote a symbol, click OK. A footnote window will be displayed at the bottom of
the page. The footnote symbol you have given will be displayed there. Type a name for the
corresponding page close to this symbol. This will create an ID for that topic. Do these steps for
each of the pages. After creating ID's for each of the pages close the footnote window.

Step 5:

Using the topic ID's you create, you can make reference to any topic from anywhere in the help
system. To make a reference, first place the cursor at the end of the phrase that you want to act as
the link to a page. Type the topic ID of that page adjacent to the phrase. Single-underline the
phrase excluding the topic ID, if you want to open a pop-up topic and double-underline it to make a
jump to the related topic. Make the topic ID you have typed with the phrase as hidden text.

280
Step 6:

You can add an illustrative graphic to your Help topic. To include a graphic, place the cursor at the
beginning of the topic. From the Menu select Insert|Picture|From File. Select the required bitmap
from the Insert picture box.

Step 7:

After doing all these things, save the file in Rich Text Format ( with extension .RTF).

Step 8:

Compile the file using the Help Workshop. The procedure is described below.

Using The Help Workshop

You can compile the help file you have created using the Help workshop. Open the Help Workshop
and start a new project. The project file contains all the instructions needed to compile the help
topic files into a working help. It can be displayed using the WinHelp engine.
Starting a New Project in Help Workshop
Choose File | New the Help Workshop. From the dialog box displayed, select Help Project and click
OK. The project Filename dialog box appears. Enter the name of the project and save it. You must
specify the location and name of each topic file to be included in each .Hlp file you create. To
specify the files, click the files button on the Workshop window. A Topic Files dialog box will be
displayed in which you can add or remove the file references to the project. Click the Add button to
display the Open dialog box. Select the RTF Topic file you created previously. Click the Open button
and then OK to add these files to the project. Click the Bitmaps button on the Workshop window to
display the Bitmaps Dialog box. Select the bitmaps and click OK.
The toolbar of the Workshop contains two buttons, one for compiling and the other for testing. By
clicking the Compile button the Compile a Help File dialog box will appear. In that give the file name
and click Compile. By clicking the Run button the View Help File dialog box will appear. In that give
the file name and click View Help. The help file will be displayed.
Mapping the Topic Ids
Each help topic has a unique number reference called the topic ID. Open the map dialog box by
clicking the map button on the Workshop window in which you can assign or map a value to a topic
ID. The map dialog box lists the topic Ids that have already been mapped with their related values.
To add a new topic ID to this list, click Add. Then the Add Map Entry dialog box will be displayed.
Here enter the topic Id of the topic in the .RTF file, a unique numeric value. You can also add an
optional comment. Now you have created a working help system.

Creating the Help Topic Dialog Box


Help Topic dialog box is a doorway into the application’s help system and provides tabbed pages to
help users locate the needed information. For creating this dialog, you need to create the contents
file. For that choose File | New in the Help Workshop. Select help contents and then click OK. When
the contents file is first created, you need to specify default information for locating the entries in
the contents file, displaying the correct title at the top of the Help Topics dialog box and displaying
the help information in the correct window type. You can set this default information in the Default
Help Information dialog box. By clicking the Edit button you can display it.

Specify the title, Topic ID, help file to look in for given topic ID and the window type for displaying
281
the topic for every item you enter in the contents page. When adding items, the headings can be
viewed as book icons that can be double-clicked to display the sub headings or topics they contain.
After saving the changes to the contents file, you can test it.
Connecting Help with the Visual Basic Application
After creating the help system, you have to connect it with the application you have created. You
can access the help system from Visual Basic using the Common Dialog control or by using built-in
help context features in Visual Basic.
To learn how Common Dialog control access help, start a new Visual Basic project. Place a Common
Dialog control and a Command Button on the form. Set the name and caption of Command button
as cmdHelp and Help. Set the name of Common Dialog control as dlgHelp and its HelpFile property
with the path and file name of the help file you have created.
On the Click event of the command button write the code as,
Private Sub cmdHelp_Click()
dlgHelp.HelpCommand = HelpFinder
dlgHelp.ShowHelp
EndSub
If an error showing that HelpFinder is not initialized is seen, you can initialize it in the general
section as
Const HelpFinder = &h00B
Save and run this application. By clicking the Help button, the Help Topic Dialog box will be
displayed. Write the code for a menu item and you can open the Help Topic Dialog box from the
menu.
2. Create a crystal report in a standard format?
You can start Crystal Reports by choosing Crystal Reports 5.0 in the Programs menu. Then select
the 32-bit Crystal Reports Professional.
The Steps for creating a report is given below:
Step 1:
Select File | New or Click New Button in the button bar, then a Report Gallery will appear.
The Report gallery provides options to create the kind of report you want. The main feature of
Report gallery is that, it has experts to create popular forms of reports. Here you will create a
Standard Report.
Step 2:
Click on the Standard icon on the Report Gallery. Then the Crystal Report Expert dialog will be
displayed. Various options in this dialog are,
Data File - This option is used to load .mdb files (access databases).
Query - This option is useful if you are using SQL/ODBC datasource. You can use this when the
report is processed directly from the server.
SQL/ODBC - This option is used to create report by choosing appropriate DSN and tables.
Dictionary - This hides the complexity of data from the users. Users only need to know the name
of a dictionary to create reports.
Step 4:
You can use the database for creating the report by selecting the Data File option and then a dialog
will be displayed. Choose the Database file that you want to Add and then click Done.
Step 5:
This will list all tables in the database Biblio.mdb. Select the required table. Here you can select the
Publishers Table.
Step 6:
Then press Next to navigate between different Tabs allowing you to create the report.
Step 7:

282
Select the Fields tab for selecting the fields that you want to include in the report. Here select the
Fields that you want to add in the Report. After selecting the required fields click the Sort tab.
Step 8:
The Sort tab is used to sort displayed figures in ascending or descending order. Here you can set
the sorting order.
Step 9:
Click on the tab Style to select the appropriate style for your report. Enter the title of your report
then choose the style, such as tables, fonts and pictures. You can include your company name also.
In our report you can select the Standard format.
Step 10:
Click on the Preview Report button to view the Preview of the report.
Step 11:
You can format the report by selecting the Design tab of the Preview Report and move the fields.
Step 12:
Choose the required format and save the report.
Step 13:
For accessing a report from Visual Basic, select Crystal Report Control from the Components tab
and add it to your application.
Step 14:
Make the following property settings:
- the name of the report you want to print in response to the application event.
- the destination for the report to be printed ( a window, file or a printer).
- the number of copies you want to print.
- print file information.
- sorting information and so on.
Step 15:
Place a command button on the Form and name it cmdRptShow. Write the following code in its
Click event.
Private Sub cmdRptShow_Click()
crtPublisher.ReportFileName= "c:\publishers.rpt"
crtPublisher.Action=1
End Sub
Save and run the application.
Introduction to Software Engineering Concepts

Software Engineering is defined as the technological discipline concerned with systematic


production and maintaining of software products that are developed and modified on time and
within cost estimates. It is a complex task to develop and maintain software products. By improving
the process used to develop and maintain software products, we can improve the quality of the
software and productivity of the programmer. Achieving these goals depends on selecting the right
application and following the Project Life Cycle. You need to decide what service the application will
give ... before creating it.
Project Life Cycle
A developer must take several steps to ensure that he is following the right method while creating
an application. These steps are generally called a Project Life Cycle. The number of steps in the life
cycle of a project may change depending on the complexity of a particular project. These steps will
allow the developer to plan each section of work and set goals.
The universal steps in the Project Life Cycle are.
1. Design
2. Coding
283
3. Testing and Debugging
4. Documentation
Design
The most important part of creating any application is determining how it will be done. Once the
right approach to the problem is decided, the rest is easy. The time spent on designing an
application is the most important portion of the project. Time spend in designing is time saved in
coding and debugging.

The design process consists of creating the design description, functional definitions, technical
definitions, and form layouts of the application. The first step in the design process is to define the
overall application in words. This method gives a road-map for the developer to follow. A good
method for defining the functionality of an application is putting the functional definitions on paper,
describing each function in detail. In the second step, the function definitions are translated into a
technical definition called pseudocode. In the final step,you define the forms and reports that are
needed according to the functions already defined.
Coding
Coding is the next step in the design phase. In this phase, the actual coding is implemented
according to the design we have created. When you code the application, start with what the user
will actually see. In Visual Basic, code is organized in a hierarchical fashion. An application can
contain many modules like form modules, standard modules and class module. A good set of
coding conventions should be followed while coding.
Testing and Debugging
Testing is the process of detecting programming errors, while debugging is the process of
identifying the cause of an error and correcting it. The testing process is carried out in two steps:
1. Unit testing - In this testing method, the individual routines or sections are tested.
2. Integration testing - Here the project is tested as a single system by correlating all different
units.
Testing and debugging occupies as much as half of the total developing time and is the hardest
part in developing an application.
Documentation
Documentation of the application including description of the project, online help for the user and
printed manual should be made in the last phase.
You can understand these steps clearly when you go through the Sample Project - My Address
Book
Introduction
My address book is a Windows based Address book application having many features. You can
create this application by following the procedure given here and can use this program to keep
details of your friends and relatives.
This application helps the user to store names, addresses and telephone numbers. It also has a
provision to keep details of a person like his date of birth and a description about him. Reports are
another feature. This sample project is provided with code for producing a report of the addresses
of all people. Also you can view the contents in various formats like tree view and list view.
This project uses an explorer style format. This style is similar to Single Document Interface (SDI),
but has tree view and list view controls on it. You can click a particular root node in the tree view to
expand it. The contents of the item selected in the tree view will be listed in the list view space.
Design
After studying the project in detail, you can move to the design phase. The first step in design
process is designing the tables of the database. This should be done with great care because tables
are the foundation of the database. From the specifications collected, you can prepare the
necessary tables. For that, gather related entities and group them as a single table. After preparing
284
a rough layout of the tables, you can go through the process of normalizing these tables. Before
this, you have to decide the primary keys, foreign keys and indexes of the tables. Normalization
includes separating repeating fields from tables and making another table to contain these
repeated fields. Any fields which do not depend on the primary key should also be formed as a
separate table.
The database of this application includes two tables, one called address table for storing the details
of a person like name, address, telephone number, etc. and the other called description table for
storing additional information regarding him.
Database Design
Database design should be done carefully. It is a pen-and-paper process to create the visual
representation of the tables and their relationships. This will make the remaining work more easy.
You have to identify various entities and then design the table according to them.
After designing the layout of the tables, you can think about how to link these tables. Then you can
decide about the primary keys, foreign keys and indexes. Indexes can be created with primary key
field or any other field and can be used for searching and sorting the table records.
Points to remember while designing a database are given below.
 Try to keep the data atomic. That is, you have to separate your data into the smallest
meaningful pieces.
 Keep a primary key field for every table. You can use compound fields as a primary key or
can include a new field to serve as primary key, called a surrogate key. It is generally better
to not use big fields as a primary key.
 Try to use descriptive table and field names. This means that you have to give table and
field names that gives the information it contains. But the names should not be too long.
Do not include space or other special characters like (#,!@= etc...)in any names you create.
Address Table
The address table stores the details of a person like name, address, date of birth, e-mail address and telephone number. The fields in the address table with their data type and description are given in the following

table.

Field Name Data Type Description


A unique ID given to each
add_id Number
person
first_name Text First name of the person
last_name Text Last name of the person
address1 Text First part of address
address2 Text Last part of address
Zip code of the place of the
zipcode Text
person
dateofbirth Date/Time Date of birth of the person
email_address Text Email address of the person
Office telephone number of
office_phone Text
the person
Residential telephone
residence_phone Text
number of the person
Here a unique field, add_id is provided which helps to identify a person. Keep the add_id field as the
primary key.
Description Table
This table keeps the information to remember regarding a person. The fields and their description in this table are given below.

285
Field Name Data Type Description
A unique ID given to each
add_id Number
person
Keep the description regarding
description Memo
the person
The add_id field of this table refers to the primary key field, add_id, of the address table.
Next topic deals with creating a prototype of this application.
sample project described in the next topics.
Creating a Prototype
After designing the tables, you can move to designing the forms also known as the user interface of
your application. This includes placing necessary controls on the form and setting their properties.
While designing, you can first create a prototype of the application. You can use VB Application
Wizard to create a prototype. The steps for using the wizard are given below.
Step 1:
Start a new Visual Basic project. Select VB Application Wizard from the New Project dialog box.

Step 2:
Then the Introduction dialog box will be displayed.

286
You can select a profile if you want and click Next button.
Step 3:
Then the dialog box for selecting interface type will be displayed. Form it choose Explorer Style.
Then type a name for your project and click Next. The dialog box is shown below.

Step 4:
The next dialog box helps you to create the menus for your application. To add a new menu or sub
menu you can click the plus marked button on the right side of the lists of menus and sub menus.
You can delete a menu or sub menu using the "X" marked button. By clicking the up and down
arrow buttons you can change the position of the menu items. You can also add separators
between menu items. The dialog box is shown below.

287
The dialog for creating a new menu item is shown below.

After selecting the required menus, click Next to move to the next dialog box.
Step 5:
Then a dialog box will be displayed which helps you to create the tool bar for your application. You
can customize the toolbar by moving required items from the left list to the right list. You can clear
the right list box using the button marked "<<" and change the order of the items using the up and
down arrows. New items can be added using the image button. The dialog box is shown below.

288
Click Next to view the next dialog box.
Step 6:
If you want to add Resource files to your application, choose the option Yes in the dialog box for
Resources. Otherwise select the option No. The dialog box is as shown below.

Click Next to view the dialog box for including Internet Connectivity for your application.
Step 7:
If you want the application to have access to the Internet, then choose the option Yes in this dialog
box. Otherwise choose No. The dialog box is shown below.

289
Step 8:
The next dialog box allows you to include standard forms to your application like a splash screen,
login dialog box, options dialog box and About box. You can select the required forms by checking
the boxes. The dialog box is given below.

Step 9:
Next, the dialog box for including Data Access Forms to your application will be displayed. It is
shown below.

290
If you want to create a new form click Create New Form. Then the Introduction dialog box of the
Data Form Wizard will be displayed. It is shown below.

Click Next to view the dialog to select the database type. Here select the type of the database you
want to use with your application and click Next. The dialog box is shown below.

291
In the next dialog box you can select the name of the database you want to connect with your
application. The dialog box is shown below.

Select the database and click Next to display the dialog box for entering the name of the form, form
layout and binding type. The dialog box is shown below.

292
Click Next. A dialog will be displayed in which you can select the record source. The dialog box is
shown below.

After selecting the record source you can select the fields to appear on the form and then click
Next. In the next dialog box, you can select required controls to place on the form. The dialog box is
shown below.

293
Select the desired buttons and click Next. In the dialog box displayed you can click Finish to create
the form. The dialog box is shown below.

Step 10:
After creating the forms you require, click next on the Data Access Forms dialog box to view the
Finished dialog box. Here, click Finish to build the application. The dialog box is shown below.

294
You can also create the application by developing it from the scratch. After creating the prototype
you can make necessary modifications. The various forms of this application are discussed in the
following section.
Forms of the application
When you start the My Address Book application, a dialog box to enter the user name and password
will be displayed. It is shown below.

After entering the user name and password, click OK. Then a splash screen will be displayed. The
figure of the splash screen is given below.

295
After loading is finished, the explorer style main window will be displayed. It is shown below.

This window has a tree view field and a list view field. In the tree view field, you can see the root
node as "Address Book". By double-clicking it, the tree view will be displayed. It will be in the
alphabetical order and the letters from A to Z will be seen. Then by clicking on the plus sign with
any letter, the names starting with that letter will be branched from it. Also by clicking the letter,
icons will be displayed for each name starting with that letter will be displayed in the list view field.
By clicking a name, a dialog box will be displayed showing the details of the person with that name.
In the dialog box you can see the description about that person by clicking the description button. It
is shown below.

296
To enter new data, select the New | Entry item from the menubar and type the details in the dialog
box which appears.
To view the report, select the Report | Address item from the menubar. Only one report is provided
with this application. You can include other reports as you need.
The form designing and coding for this application are given in the following topics.
Form Design and Coding of Login Form
The form layout of the login form is given below. Place the controls according to this form. The
properties of each of the controls are given below the figure. The coding for each control is also
given after the property settings.

Begin VB.Form frmLogin


BorderStyle = 3 'Fixed Dialog
Caption = "Login"
ClientHeight = 1590
ClientLeft = 45
ClientTop = 330
ClientWidth = 3750
LinkTopic = "Form1"
MaxButton = 0 'False
297
MinButton = 0 'False
ScaleHeight = 1590
ScaleWidth = 3750
ShowInTaskbar = 0 'False
StartUpPosition = 2 'CenterScreen
Tag = "Login"

Begin VB.CommandButton cmdCancel


Cancel = -1 'True
Caption = "Cancel"
Height = 360
Left = 2100
TabIndex = 5
Tag = "Cancel"
Top = 1020
Width = 1140
End

Begin VB.CommandButton cmdOK


Caption = "OK"
Default = -1 'True
Height = 360
Left = 495
TabIndex = 4
Tag = "OK"
Top = 1020
Width = 1140
End

Begin VB.TextBox txtPassword


Height = 285
IMEMode = 3 'DISABLE
Left = 1305
PasswordChar= "*"
TabIndex = 1
Top = 525
Width = 2325
End

Begin VB.TextBox txtUserName


Height = 285
Left = 1305
TabIndex = 3
Top = 135
Width = 2325
End

Begin VB.Label lblLabels


Caption = "&Password:"
Height = 248
298
Index = 1
Left = 105
TabIndex = 0
Tag = "&Password:"
Top = 540
Width = 1080
End

Begin VB.Label lblLabels


Caption = "&User Name:"
Height = 248
Index = 0
Left = 105
TabIndex = 2
Tag = "&User Name:"
Top = 150
Width = 1080
End
End
Write the following in the general declarations.
Private Declare Function GetUserName Lib "advapi32.dll" Alias "GetUserNameA" (ByVal lpbuffer As
String, nSize As Long) As Long
Public OK As Boolean
Write the following code in the form load.
Private Sub Form_Load()
Dim sBuffer As String
Dim lSize As Long
sBuffer = Space$(255)
lSize = Len(sBuffer)
Call GetUserName(sBuffer, lSize)
If lSize > 0 Then
txtUserName.Text = Left$(sBuffer, lSize)
Else
txtUserName.Text = vbNullString
End If
End Sub
Write the following code in the click event of the command button cmdCancel.
Private Sub cmdCancel_Click()
OK = False
Me.Hide
End Sub

Write the following code in the click event of the command button cmdOK.
Private Sub cmdOK_Click()
'check for correct password
If txtUserNametxt.Text = "admin" and Password.Text = "admin" Then
OK = True
Me.Hide
Else
MsgBox "Invalid Password, try again!", , "Login"
299
txtPassword.SetFocus
txtPassword.SelStart = 0
txtPassword.SelLength = Len(txtPassword.Text)
End If
End Sub
The form design and coding of the main form is given in the next topic.
Form Design and Coding of the Main Form
The form layout of the main form is given below. Place the controls according to this form. The
properties of each of the controls are given below the figure. The coding for each control is also
given after the property settings.

Begin VB.Form frmMain


Caption = "AddressBook"
ClientHeight = 3195
ClientLeft = 165
ClientTop = 735
ClientWidth = 6195
LinkTopic = "Form1"
ScaleHeight = 3195
ScaleWidth = 6195
StartUpPosition= 3 'Windows Default

Begin Crystal.CrystalReport crtAddress1


Left = 3420
Top = -150
_ExtentX = 741
_ExtentY = 741
_Version = 262150
ReportFileName= "D:\Addressbook\report1.rpt"
End

Begin VB.PictureBox picSplitter


BackColor = &H00808080&
300
BorderStyle = 0 'None
FillColor = &H00808080&
Height = 4800
Left = 4350
ScaleHeight = 2090.126
ScaleMode = 0 'User
ScaleWidth = 780
TabIndex = 4
Top = 660
Visible = 0 'False
Width = 72
End

Begin ComctlLib.TreeView tvTreeView


Height = 5220
Left = 0
TabIndex = 3
Top = 240
Width = 2010
_ExtentX = 3545
_ExtentY = 9208
_Version = 327682
PathSeparator= ""
Style = 7
Appearance = 1
End

Begin ComctlLib.ListView lvListView


Height = 5460
Left = 2070
TabIndex = 2
Top = 210
Width = 4110
_ExtentX = 7250
_ExtentY = 9631
View = 2
MultiSelect = -1 'True
LabelWrap = -1 'True
HideSelection= -1 'True
_Version = 327682
Icons = "imlIcons"
SmallIcons = "imlIcons"
ForeColor = -2147483640
BackColor = -2147483643
BorderStyle = 1
Appearance = 1
NumItems = 0
End

Begin VB.PictureBox picTitles


301
Align = 1 'Align Top
Appearance = 0 'Flat
BorderStyle = 0 'None
ForeColor = &H80000008&
Height = 300
Left = 0
ScaleHeight = 300
ScaleWidth = 6195
TabIndex = 1
TabStop = 0 'False
Top = 0
Width = 6195
End

Begin ComctlLib.StatusBar sbStatusBar


Align = 2 'Align Bottom
Height = 270
Left = 0
TabIndex = 0
Top = 2925
Width = 6195
_ExtentX = 10927
_ExtentY = 476
SimpleText = ""
_Version = 327682

BeginProperty Panels {0713E89E-850A-101B-AFC0-4210102A8DA7}


NumPanels = 3
BeginProperty Panel1 {0713E89F-850A-101B-AFC0-4210102A8DA7}
AutoSize = 1
Object.Width = 5292
Text = "Status"
TextSave = "Status"
Object.Tag = ""
EndProperty

BeginProperty Panel2 {0713E89F-850A-101B-AFC0-4210102A8DA7}


Style = 6
AutoSize = 2
TextSave = "12/28/99"
Object.Tag = ""
EndProperty

BeginProperty Panel3 {0713E89F-850A-101B-AFC0-4210102A8DA7}


Style = 5
AutoSize = 2
TextSave = "5:18 PM"
Object.Tag = ""
EndProperty
EndProperty
302
End

Begin MSComDlg.CommonDialog dlgCommonDialog


Left = 1830
Top = 1410
_ExtentX = 847
_ExtentY = 847
_Version = 393216
End

Begin VB.Image imgSplitter


Height = 4788
Left = 1965
MousePointer= 9 'Size W E
Top = 705
Width = 150
End

Begin ComctlLib.ImageList imlIcons


Left = 1740
Top = 1350
_ExtentX = 1005
_ExtentY = 1005
BackColor = -2147483643
ImageWidth = 16
ImageHeight = 16
MaskColor = 12632256
_Version = 327682

BeginProperty Images {0713E8C2-850A-101B-AFC0-4210102A8DA7}


NumListImages = 11
BeginProperty ListImage1 {0713E8C3-850A-101B-AFC0-4210102A8DA7}
Picture = "frmMain.frx":0000
Key = ""
EndProperty

BeginProperty ListImage2 {0713E8C3-850A-101B-AFC0-4210102A8DA7}


Picture = "frmMain.frx":0352
Key = ""
EndProperty

BeginProperty ListImage3 {0713E8C3-850A-101B-AFC0-4210102A8DA7}


Picture = "frmMain.frx":06A4
Key = ""
EndProperty

BeginProperty ListImage4 {0713E8C3-850A-101B-AFC0-4210102A8DA7}


Picture = "frmMain.frx":09F6
Key = ""
EndProperty
303
BeginProperty ListImage5 {0713E8C3-850A-101B-AFC0-4210102A8DA7}
Picture = "frmMain.frx":0D48
Key = ""
EndProperty

BeginProperty ListImage6 {0713E8C3-850A-101B-AFC0-4210102A8DA7}


Picture = "frmMain.frx":109A
Key = ""
EndProperty

BeginProperty ListImage7 {0713E8C3-850A-101B-AFC0-4210102A8DA7}


Picture = "frmMain.frx":13EC
Key = ""
EndProperty

BeginProperty ListImage8 {0713E8C3-850A-101B-AFC0-4210102A8DA7}


Picture = "frmMain.frx":173E
Key = ""
EndProperty

BeginProperty ListImage9 {0713E8C3-850A-101B-AFC0-4210102A8DA7}


Picture = "frmMain.frx":1A90
Key = ""
EndProperty

BeginProperty ListImage10 {0713E8C3-850A-101B-AFC0-4210102A8DA7}


Picture = "frmMain.frx":1DE2
Key = ""
EndProperty

BeginProperty ListImage11 {0713E8C3-850A-101B-AFC0-4210102A8DA7}


Picture = "frmMain.frx":2134
Key = ""
EndProperty
EndProperty
End

Begin VB.Menu mnuNew


Caption = "New"
Begin VB.Menu mnuEntry
Caption = "Entry"
End
End

Begin VB.Menu mnuReport


Caption = "Report"
Begin VB.Menu mnuAddress
Caption = "Address"
304
End
End

Begin VB.Menu mnuHelp


Caption = "Help"
Begin VB.Menu mnuHelpAbout
Caption = "&About AddressBook..."
End
End

Begin VB.Menu mnuExit


Caption = "&Exit"
End
End

Coding for various controls are given below.

Attribute VB_Name = "frmMain"


Attribute VB_GlobalNameSpace = False
Attribute VB_Creatable = False
Attribute VB_PredeclaredId = True
Attribute VB_Exposed = False

Private Declare Function OSWinHelp% Lib "user32" Alias "WinHelpA" (ByVal hwnd&, ByVal
HelpFile$, ByVal wCommand%, dwData As Any)
Dim mbMoving As Boolean
Const sglSplitLimit = 500
Dim db As Database
Dim MyNode
Dim address_id As String

Private Sub Form_Load()


'Setting the Forms's position and size
Me.Left = GetSetting(App.Title, "Settings", "MainLeft", 1000)
Me.Top = GetSetting(App.Title, "Settings", "MainTop", 1000)
Me.Width = GetSetting(App.Title, "Settings", "MainWidth", 6500)
Me.Height = GetSetting(App.Title, "Settings", "MainHeight", 6500)
Set dB = OpenDatabase("d:\Addressbook\addressbook.mdb")
Call SetTree
Call SetTreeNodes
End Sub

Private Sub Form_Paint()


lvListView.View = Val(GetSetting(App.Title, "Settings", "ViewMode", "0"))
'tbToolBar.Buttons(lvListView.View + LISTVIEW_BUTTON).Value = tbrPressed
End Sub

Private Sub Form_Unload(Cancel As Integer)


Dim i As Integer
'close all sub forms
305
For i = Forms.Count - 1 To 1 Step -1
Unload Forms(i)
Next
If Me.WindowState <> vbMinimized Then
SaveSetting App.Title, "Settings", "MainLeft", Me.Left
SaveSetting App.Title, "Settings", "Maintop", Me.Top
SaveSetting App.Title, "Settings", "MainWidth", Me.Width
SaveSetting App.Title, "Settings", "MainHeight", Me.Height
End If
SaveSetting App.Title, "Settings", "ViewMode", lvListView.View
End Sub

Private Sub mnuAddress_Click()


crtAddress1.ReportFileName = "d:\AddressBook\Report1.rpt"
crtAddress1.Action = 1
End Sub

Private Sub mnuEntry_Click()


'Show the address entry form
frmaddress.Show
End Sub

Private Sub mnuExit_Click()


'Closing the application
End
End Sub

Private Sub mnuHelpAbout_Click()


frmAbout.Show vbModal, Me
End Sub

Private Sub Form_Resize()


On Error Resume Next
If Me.Width < 3000 Then Me.Width = 3000
SizeControls imgSplitter.Left
End Sub

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


With imgSplitter
picSplitter.Move .Left, .Top, .Width \ 2, .Height - 20
End With
picSplitter.Visible = True
mbMoving = True
End Sub

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


Dim sglPos As Single

If mbMoving Then
sglPos = X + imgSplitter.Left
306
If sglPos < sglSplitLimit Then
picSplitter.Left = sglSplitLimit
ElseIf sglPos > Me.Width - sglSplitLimit Then
picSplitter.Left = Me.Width - sglSplitLimit
Else
picSplitter.Left = sglPos
End If
End If
End Sub

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


SizeControls picSplitter.Left
picSplitter.Visible = False
mbMoving = False
End Sub

Sub SizeControls(X As Single)


On Error Resume Next
'set the width
If X < 1500 Then X = 1500
If X > (Me.Width - 1500) Then X = Me.Width - 1500
tvTreeView.Width = X
imgSplitter.Left = X
lvListView.Left = X + 40
lvListView.Width = Me.Width - (tvTreeView.Width + 140)

'set the top


If tbToolBar.Visible Then
tvTreeView.Top = tbToolBar.Height + picTitles.Height
Else
tvTreeView.Top = picTitles.Height
End If
lvListView.Top = tvTreeView.Top
'set the height
If sbStatusBar.Visible Then
tvTreeView.Height = Me.ScaleHeight - (picTitles.Top + picTitles.Height + sbStatusBar.Height)
Else
tvTreeView.Height = Me.ScaleHeight - (picTitles.Top + picTitles.Height)
End If
lvListView.Height = tvTreeView.Height
imgSplitter.Top = tvTreeView.Top
imgSplitter.Height = tvTreeView.Height
End Sub

Private Sub TreeView1_DragDrop(Source As Control, X As Single, Y As Single)


If Source = imgSplitter Then
SizeControls X
End If
End Sub

307
Private Sub tbToolBar_ButtonClick(ByVal Button As ComctlLib.Button)
Select Case Button.Key
Case "Back"
'To Do
MsgBox "Back Code goes here!"
Case "Forward"
'To Do
MsgBox "Forward Code goes here!"
Case "Cut"
'To Do
MsgBox "Cut Code goes here!"
Case "Copy"
'To Do
MsgBox "Copy Code goes here!"
Case "Paste"
'To Do
MsgBox "Paste Code goes here!"
Case "Delete"
'To Do
MsgBox "Delete Code goes here!"
Case "Properties"
'To Do
MsgBox "Properties Code goes here!"
Case "ViewLarge"
lvListView.View = lvwIcon
Case "ViewSmall"
lvListView.View = lvwSmallIcon
Case "ViewList"
lvListView.View = lvwList
Case "ViewDetails"
lvListView.View = lvwReport
End Select
End Sub

Private Sub mnuHelpContents_Click()

Dim nRet As Integer


'if there is no helpfile for this project display a message to the user
'you can set the HelpFile for your application in the
'Project Properties dialog
If Len(App.HelpFile) = 0 Then
MsgBox "Unable to display Help Contents. There is no Help associated with this project.",
vbInformation, Me.Caption
Else
On Error Resume Next
nRet = OSWinHelp(Me.hwnd, App.HelpFile, 3, 0)
If Err Then
MsgBox Err.Description
End If
308
End If
End Sub

Private Sub mnuHelpSearch_Click()

Dim nRet As Integer


'if there is no helpfile for this project display a message to the user
'you can set the HelpFile for your application in the
'Project Properties dialog
If Len(App.HelpFile) = 0 Then
MsgBox "Unable to display Help Contents. There is no Help associated with this project.",
vbInformation, Me.Caption
Else
On Error Resume Next
nRet = OSWinHelp(Me.hwnd, App.HelpFile, 261, 0)
If Err Then
MsgBox Err.Description
End If
End If
End Sub

Public Sub SetTree()


Dim strNode As String * 1
tvTreeView.Nodes.Clear
Set MyAddressNode = tvTreeView.Nodes.Add(, , "AB", "Address Book")
For i = 1 To 26
strNode = Mid("ABCDEFGHIJKLMNOPQRSTUVWXYZ", i, 1)
Set MyAddressNode = tvTreeView.Nodes.Add("AB", tvwChild, strNode, strNode)
Next i
End Sub

Public Sub SetTreeNodes()


Dim strAddNodeKey As String
Dim strEntry As String * 1
Dim strNodeName As String
Set dbDyn = db.OpenRecordset("Select * from [address]", dbOpenDynaset)
If Not dbDyn.EOF And Not dbDyn.BOF Then
dbDyn.MoveFirst
Do Until dbDyn.EOF
strAddNodeKey = CStr(dbDyn.Fields(0)) & "!" & dbDyn.Fields("last_name")
strEntry = Mid(dbDyn.Fields("last_name"), 1, 1)
strNodeName = dbDyn.Fields("last_name") & "," & dbDyn.Fields("first_name")
Set MyNode = tvTreeView.Nodes.Add(strEntry, tvwChild, strAddNodeKey, strNodeName)
dbDyn.MoveNext
Loop
End If
dbDyn.Close
End Sub

Private Sub tvTreeView_NodeClick(ByVal Node As ComctlLib.Node)


309
If Len(Node.Key) = 1 Then
Call ViewList(Node.Key)
Else
If InStr(1, tvTreeView.SelectedItem.Key, "!") > 0 Then
sqlEntry = "select * from [address] where [add_id] = " & Mid(tvTreeView.SelectedItem.Key, 1,
InStr(1, tvTreeView.SelectedItem.Key, "!") - 1)
Unload Me
frmaddress.Show
End If
End If
End Sub

Public Sub ViewList(KeyCode As String)


Dim itemList As ListItem
On Error GoTo errh
lvListView.ListItems.Clear
Set dbDyn = db.OpenRecordset("Select * from [address] where [last_name] like """ & KeyCode &
"*""", dbOpenDynaset)
dbDyn.MoveFirst
Do Until dbDyn.EOF
Set itemList = lvListView.ListItems.Add(, , dbDyn.Fields("last_name") & "," &
dbDyn.Fields("first_name"), 1, 1)
dbDyn.MoveNext
Loop
dbDyn.Close
errh:
If Err = 3021 Then
MsgBox (Err.Description)
End If
End Sub
The form design and coding of the address form is given in the next topic.
Form Design and Coding of the Address Form
The form layout of the Address form is given below. Place the controls according to this form. The
properties of each of the controls are given below the figure. The coding for each control is also
given after the property settings.

310
Begin VB.Form frmaddress
Caption = "Address Entry"
ClientHeight = 6720
ClientLeft = 1110
ClientTop = 345
ClientWidth = 5760
LinkTopic = "Form2"
ScaleHeight = 6720
ScaleWidth = 5760

Begin VB.TextBox txtAddress2


DataField = "address2"
DataSource = "datPrimaryRS"
Height = 285
Left = 1950
TabIndex = 27
Top = 1800
Width = 3375
End

Begin VB.CommandButton cmdQuit


Caption = "Close"
Height = 315
Left = 4440
311
TabIndex = 26
Top = 6300
Width = 1215
End

Begin VB.CommandButton cmdUpdateDesc


Caption = "Update"
Height = 315
Left = 3060
TabIndex = 25
Top = 6300
Width = 1290
End

Begin VB.TextBox txtDescription


DataField = "description"
DataSource = "datSecondaryRS"
Height = 1275
Left = 60
ScrollBars = 2 'Vertical
TabIndex = 24
Top = 4920
Width = 5550
End

Begin VB.CommandButton cmdClose


Caption = "&Close"
Height = 300
Left = 4440
TabIndex = 22
Top = 4080
Width = 1185
End

Begin VB.CommandButton cmdUpdate


Caption = "&Update"
Height = 300
Left = 3330
TabIndex = 21
Top = 4080
Width = 1065
End

Begin VB.CommandButton cmdDesc


Caption = "Description"
Height = 300
Left = 2250
TabIndex = 20
Top = 4080
Width = 1005
312
End

Begin VB.CommandButton cmdDelete


Caption = "&Delete"
Height = 300
Left = 1140
TabIndex = 19
Top = 4080
Width = 1065
End

Begin VB.CommandButton cmdAdd


Caption = "&Add"
Height = 300
Left = 90
TabIndex = 18
Top = 4080
Width = 1005
End

Begin VB.TextBox txtDateofBirth


DataField = "dateofbirth"
DataSource = "datPrimaryRS"
Height = 285
Left = 1920
TabIndex = 9
Top = 2550
Width = 3375
End

Begin VB.TextBox txtZipCode


DataField = "zipcode"
DataSource = "datPrimaryRS"
Height = 285
Left = 1935
TabIndex = 8
Top = 2175
Width = 3375
End

Begin VB.TextBox txtAdress1


DataField = "address1"
DataSource = "datPrimaryRS"
Height = 285
Left = 1935
TabIndex = 7
Top = 1440
Width = 3375
End

313
Begin VB.TextBox txtLastName
DataField = "last_name"
DataSource = "datPrimaryRS"
Height = 285
Left = 1935
TabIndex = 6
Top = 1080
Width = 3375
End

Begin VB.TextBox txtFirstName


DataField = "first_name"
DataSource = "datPrimaryRS"
Height = 285
Left = 1950
TabIndex = 5
Top = 750
Width = 3375
End

Begin VB.TextBox txtAddressID


DataField = "add_id"
DataSource = "datPrimaryRS"
Height = 285
Left = 1680
TabIndex = 4
Top = -615
Width = 2175
End

Begin VB.TextBox txtDesc


DataField = "description"
DataSource = "datSecondaryRS"
Height = 735
Left = 240
TabIndex = 3
Top = 11040
Width = 5775
End

Begin VB.Data datSecondaryRS


Connect = "Access"
DatabaseName = "D:\Addressbook\Addressbook.mdb"
DefaultCursorType= 0 'DefaultCursor
DefaultType = 2 'UseODBC
Exclusive = 0 'False
Height = 345
Left = 4125
Options = 0
314
ReadOnly = 0 'False
RecordsetType = 1 'Dynaset
RecordSource = "description"
Top = -675
Visible = 0 'False
Width = 1140
End

Begin VB.Data datPrimaryRS


Caption = ""
Connect = "Access"
DatabaseName = "D:\Addressbook\Addressbook.mdb"
DefaultCursorType= 0 'DefaultCursor
DefaultType = 2 'UseODBC
Exclusive = 0 'False
Height = 405
Left = 60
Options = 0
ReadOnly = 0 'False
RecordsetType= 1 'Dynaset
RecordSource = "select * from [address]"
Top = 4470
Width = 5580
End

Begin VB.TextBox txtFields


DataField = "residence_phone"
DataSource = "datPrimaryRS"
Height = 285
Index = 9
Left = 1965
MaxLength = 50
TabIndex = 1
Top = 8820
Width = 3375
End

Begin MSDBGrid.DBGrid grdDataGrid


Bindings = "frmaddress.frx":0000
Height = 1305
Left = 120
OleObjectBlob= "frmaddress.frx":0182
TabIndex = 2
Top = 9480
Width = 5535
End

Begin VB.Frame Frame1


Height = 6645
Left = 60
315
TabIndex = 10
Top = 30
Width = 5640

Begin VB.TextBox txtEmail


DataField = "email_address"
DataSource = "datPrimaryRS"
Height = 285
Left = 1860
TabIndex = 33
Top = 3630
Width = 3375
End

Begin VB.TextBox txtResphone


DataField = "residence_phone"
DataSource = "datPrimaryRS"
Height = 285
Left = 1860
TabIndex = 32
Top = 3240
Width = 3375
End

Begin VB.TextBox txtOfficePhone


DataField = "office_phone"
DataSource = "datPrimaryRS"
Height = 285
Left = 1860
TabIndex = 31
Top = 2910
Width = 3375
End

Begin VB.TextBox txtAdd_id


DataField = "add_id"
DataSource = "datPrimaryRS"
Height = 285
Left = 1905
TabIndex = 30
Top = 375
Width = 3375
End

Begin VB.Label Label3


AutoSize = -1 'True
Caption = "Email address :"
BeginProperty Font
Name = "MS Sans Serif"
Size = 8.25
316
Charset = 0
Weight = 700
Underline = 0 'False
Italic = 0 'False
Strikethrough = 0 'False
EndProperty
Height = 195
Left = 360
TabIndex = 34
Top = 3720
Width = 1305
End

Begin VB.Label Label2


AutoSize = -1 'True
Caption = "Phone (Resi) :"
BeginProperty Font
Name = "MS Sans Serif"
Size = 8.25
Charset = 0
Weight = 700
Underline = 0 'False
Italic = 0 'False
Strikethrough= 0 'False
EndProperty
Height = 195
Left = 360
TabIndex = 29
Top = 3330
Width = 1230
End

Begin VB.Label Label1


AutoSize = -1 'True
Caption = "Phone (Office) :"
BeginProperty Font
Name = "MS Sans Serif"
Size = 8.25
Charset = 0
Weight = 700
Underline = 0 'False
Italic = 0 'False
Strikethrough= 0 'False
EndProperty
Height = 195
Left = 360
TabIndex = 28
Top = 2940
Width = 1365
End
317
Begin VB.Label lblDateOfBirth
AutoSize = -1 'True
Caption = "Date of Birth :"
BeginProperty Font
Name = "MS Sans Serif"
Size = 8.25
Charset = 0
Weight = 700
Underline = 0 'False
Italic = 0 'False
Strikethrough = 0 'False
EndProperty
Height = 195
Left = 360
TabIndex = 17
Top = 2580
Width = 1215
End

Begin VB.Label lblZipCode


AutoSize = -1 'True
Caption = "Zip Code :"
BeginProperty Font
Name = "MS Sans Serif"
Size = 8.25
Charset = 0
Weight = 700
Underline = 0 'False
Italic = 0 'False
Strikethrough= 0 'False
EndProperty
Height = 195
Left = 360
TabIndex = 16
Top = 2220
Width = 900
End

Begin VB.Label lblAddress2


AutoSize = -1 'True
Caption = "Address 2 :"
BeginProperty Font
Name = "MS Sans Serif"
Size = 8.25
Charset = 0
Weight = 700
Underline = 0 'False
Italic = 0 'False
Strikethrough= 0 'False
318
EndProperty
Height = 195
Left = 390
TabIndex = 15
Top = 1800
Width = 975
End

Begin VB.Label lblAddress1


AutoSize = -1 'True
Caption = "Address 1 :"
BeginProperty Font
Name = "MS Sans Serif"
Size = 8.25
Charset = 0
Weight = 700
Underline = 0 'False
Italic = 0 'False
Strikethrough = 0 'False
EndProperty
Height = 195
Left = 390
TabIndex = 14
Top = 1440
Width = 975
End

Begin VB.Label lblLastName


AutoSize = -1 'True
Caption = "Last Name :"
BeginProperty Font
Name = "MS Sans Serif"
Size = 8.25
Charset = 0
Weight = 700
Underline = 0 'False
Italic = 0 'False
Strikethrough= 0 'False
EndProperty
Height = 195
Left = 360
TabIndex = 13
Top = 1080
Width = 1035
End

Begin VB.Label lblFirstName


AutoSize = -1 'True
Caption = "First Name :"
BeginProperty Font
319
Name = "MS Sans Serif"
Size = 8.25
Charset = 0
Weight = 700
Underline = 0 'False
Italic = 0 'False
Strikethrough= 0 'False
EndProperty
Height = 240
Left = 360
TabIndex = 12
Top = 780
Width = 1065
End

Begin VB.Label lblAddID


AutoSize = -1 'True
Caption = "Address ID :"
BeginProperty Font
Name = "MS Sans Serif"
Size = 8.25
Charset = 0
Weight = 700
Underline = 0 'False
Italic = 0 'False
Strikethrough= 0 'False
EndProperty
Height = 240
Left = 360
TabIndex = 11
Top = 450
Width = 1065
End
End

Begin VB.Frame Frame2


Height = 6810
Left = -30
TabIndex = 23
Top = -120
Width = 5835
End
Begin VB.Label lblLabels
Caption = "Residence Phone:"
Height = 255
Index = 9
Left = 120
TabIndex = 0
Top = 8820
Width = 1815
320
End
End

Coding for various controls are given below.

Attribute VB_Name = "frmaddress"


Attribute VB_GlobalNameSpace = False
Attribute VB_Creatable = False
Attribute VB_PredeclaredId = True
Attribute VB_Exposed = False

Private Sub cmdAdd_Click()


' For adding record to the database
datPrimaryRS.Recordset.AddNew
End Sub

Private Sub cmdDelete_Click()


'For deleting a record
With datPrimaryRS.Recordset
.Delete
.MoveNext
If .EOF Then .MoveLast
End With
End Sub

Private Sub cmdRefresh_Click()


'This is only needed for multi user apps
datPrimaryRS.Refresh
End Sub

Private Sub cmdDesc_Click()


'For showing the Description
frmaddress.Height = 7320
frmaddress.Width = 5880
End Sub

Private Sub cmdQuit_Click()


' For resizing the form to the previous state
frmaddress.Height = 5520
frmaddress.Width = 5880
End Sub

Private Sub cmdUpdate_Click()


' For updating the record
datPrimaryRS.UpdateRecord
datPrimaryRS.Recordset.Bookmark = datPrimaryRS.Recordset.LastModified
End Sub

Private Sub cmdClose_Click()


' For closing the address form
321
Screen.MousePointer = vbDefault
Unload Me
End Sub

Private Sub cmdUpdateDesc_Click()


' For Updating the Description Record
Dim intAddno As Integer
Dim strDesc As String
intAddno = txtAddressID.Text
strDesc = txtDescription.Text
datPrimaryRS.Recordset.MoveFirst
datSecondaryRS.Recordset.AddNew
datSecondaryRS.Recordset!add_id = intAddno
datSecondaryRS.Recordset!Description = strDesc
datSecondaryRS.Recordset.Update
' datSecondaryRS.Recordset!hobby = txtHobby.Text
End Sub

Private Sub datPrimaryRS_Error(DataErr As Integer, Response As Integer)


'This is where you would put error handling code
'If you want to ignore errors, comment out the next line
'If you want to trap them, add code here to handle them
MsgBox "Data error event hit err:" & Error$(DataErr)
Response = 0 'Throw away the error
End Sub

Private Sub datPrimaryRS_Reposition()


Screen.MousePointer = vbDefault
On Error Resume Next
'This will synch the grid with the Master recordset
datSecondaryRS.RecordSource = "select [add_id],[description],[hobby] from [description] where
[add_id]=" & datPrimaryRS.Recordset![add_id]
datSecondaryRS.Refresh
'This will display the current record position for dynasets and snapshots
datPrimaryRS.Caption = "Record: " & (datPrimaryRS.Recordset.AbsolutePosition + 1)
End Sub

Private Sub datPrimaryRS_Validate(Action As Integer, Save As Integer)


'This is where you put validation code
'This event gets called when the following actions occur
Select Case Action
Case vbDataActionMoveFirst
Case vbDataActionMovePrevious
Case vbDataActionMoveNext
Case vbDataActionMoveLast
Case vbDataActionAddNew
Case vbDataActionUpdate
Case vbDataActionDelete
Case vbDataActionFind
Case vbDataActionBookmark
322
Case vbDataActionClose
Screen.MousePointer = vbDefault
End Select
Screen.MousePointer = vbHourglass
End Sub

Private Sub Form_Load()


'Create the grid's recordset
datPrimaryRS.Refresh
If sqlEntry = "" Then
sqlEntry = "select * from [address]"
End If
datPrimaryRS.RecordSource = sqlEntry
datPrimaryRS.Refresh
If datPrimaryRS.Recordset.RecordCount = 0 Then
datPrimaryRS.Recordset.AddNew
End If
'Setting the size at run time
frmaddress.Height = 5520
frmaddress.Width = 5880
End Sub

Private Sub Form_Unload(Cancel As Integer)


' When the form unloads it have to show the Main form
Screen.MousePointer = vbDefault
Unload Me
frmMain.Show
End Sub

Private Sub Form_Resize()


On Error Resume Next
'This will resize the grid when the form is resized
grdDataGrid.Width = Me.ScaleWidth
grdDataGrid.Height = Me.ScaleHeight - grdDataGrid.Top - datPrimaryRS.Height -
picButtons.Height - 30
End Sub

Private Sub Text1_Change()


End Sub
Private Sub Text2_Change()
End Sub
A description about testing and debugging is given in the next topic.
Testing and Debugging
Before going into the tools and techniques for debugging in Visual Basic, you should have a good
idea about the terms testing and debugging. Testing is the process of finding the errors, including
logical errors. In Visual Basic this is fairly easy, because the execution of the application will stop
and displays the Error Dialog when a problem occurs. The Error Dialog will give the information like,
1. Error description
2. Option to go into debugging mode

323
From the error code, the developer can easily find out some details of the error and can go into the
debugging process with a good starting point.
The process of testing and debugging can be made simple by following the points given below.
 Try to use Option Explicit statement to prevent misspelled variables and object names.
 Include well written error handling routines in your application.
 Try to keep routines short and easy to follow.
 Increase readability by giving indents for inner statements and loops.
 Use meaningful comments that describe, in a general sense, what a section of code's
purpose is.
 Name forms, objects and variables logically and use a standard convention.
While debugging, trapping logical errors is tedious work because the error usually occurs further
down the execution path in the application. Sometimes the application may run without showing
any errors but the output will not be correct. These types of errors can be found only by checking
the output against manually calculated results. This type of checking is known as desk-checking.
Though there is no easy route to trap an error besides going through the code, Visual Basic
provides certain tools which makes the debugging process easier. You can easily debug an
application if you know how it works.
The Debugging Environment
While creating programs in Visual Basic, you can operate in three modes: design, run and debug. In
the design mode the application is written and formatted. The created application is made to
execute in the run mode. Whenever an error occurs the application will turn into debug mode. In
this mode, the execution of the application will be suspended and you can examine and alter any
data or code.
Visual Basic provides three buttons on the standard tool bar to change from one mode to another.
In addition to mode buttons, Visual Basic provides a Debug toolbar that you can optionally display
or you can use the Debug Menu. You can see the values of expressions and variables while passing
through each step of the application with the help of the debugging windows. Three different
debugging windows used in Visual Basic are Immediate window, Watches window and Locals
window. Some of the debugging functions are BreakPoint, Step Into, Step Over, Step Out and Call
Stack.
The Debug toolbar is shown below,

The immediate window is used to display value or expression during the execution of the
application. The watches window displays the values of any Watch expressions that you have
already chosen to watch. The Locals window displays the value of any variable that are within the
scope of the current procedure.
In design mode, you can modify the code but you can not see how the changes made will affect the
running of the application. In the run time mode, you can see the changes you have already made
but cannot make any changes to the code. In the break mode you can halt the execution of the
application and do various actions like modify code, track and display the values of variables and
statements, specify the next statement to be executed, modify any values, view the changes made
to the user interface and execute statements in the immediate window. You can enter break mode
by pressing Ctrl+Break keys or by choosing Run|Break or by clicking Break on the toolbar.
324
Next topic deals with application performance and tuning.
Performance and Tuning
While creating an application, the performance is an important aspect to be considered. Some
techniques will help to make faster applications where as others will make it slower. The important
factors that improve the performance are given below:
1. Optimizing the code - here the concept used is when we reduce the number of lines the
execution speed can be increased. For that we can use the following steps:
 Avoid declaring variables as Variant.
 Replace procedure calls with inline procedures
 Use constants
 Pass arguments By Val instead By Ref.
2. Distracting the user - use a progress bar or some animation to inform the user that some
process is taking place in the background.
3. Make necessary brushings - a splash screen should be provided with the application. Easily
accessible help should be available. The form should be laid out in such a way that it can navigate
the user to all aspects of the application.
4. Compile to native code - Choose compiling to native code, which will make the application
run faster than if it is compiled to P-code executable. Visual Basic includes an option in the File
menu, Make Project.exe, to compile to native code.
Resource Files
The changes in the static resources used by the application affect the size and speed of it.
Resources are generally the memory used by the application. It can be of two groups - string and
binary. String resources include a text string data and the binary resources contain bitmaps, icons,
cursors, sound, video clippings, etc. A resource file allows you to collect all the version-specific
resources for an application into a single file.
A resource file is a plain text file containing preprocessing directives, single line statements and
multiline statements. Resource file can be created by using the application wizard or using a word
editor. The first set of statements in the file defines the values that will be used later in the file. The
next step is to add the string table, containing the string statements your application will use. After
defining all the resources you want in the file, save the file with .RC extension. This file is compiled
using the Resource Compiler, which is a DOS-based program. The file will be complied into a .RES
file, allowing the resources to be used in your application.
To add the resource files to a project right-click the Project menu and select the Add option. Then
select Add Resource File to display Open a Resource File dialog box. From the dialog box, locate the
resource file and select it. Then it will be displayed in the Project window in the group Related
Documents. You can also create a resource file using the resource editor.
The product related issues and support related issues you need to consider while developing an
application are discussed in the next topic.
Next topic discusses finishing and distributing an application.
Finishing and Distributing the Application
Finishing the Application
Just creating a working application doesn't make the job complete. Other issues to be considered
are advertising, customer support, protecting the product and the actual distribution of the
software. The different areas that should be considered when creating an application package fall
into two groups - product related and support related issues.
Product Related Issues
You have to consider many topics before you create an application. Many of the product related
issues come under any of the following categories.
Design of the program

325
This is the phase where you study the problem and create the outline of how to carry out the
development procedure. A good design helps to minimize the time taken for coding.

Reporting - The reports generated by the application should meet the requirements of the user.
Online Help - The topics and the help files for that particular topic should be designed together.
This can reduce the delay for finishing the process .
Performance - The performance of the software is an important issue to be considered. The
finished application should meet the requirements of the user in every respect. The application
should be designed to run as fast and efficiently as possible.
Error Handling - The code should contain enough error handling routines so that even if Visual
Basic is unable to recover the errors, the application won't stop executing
Documentation - A printed documentation should be provided, which can give the users all
details about what the application will do. It should contain the table of contents, product
introduction, how to start, how to use the product, troubleshooting, how to get technical support
and an index.
Support-Related Issues
Providing customers with a way of getting good application support is part of the overall application
package that you create. The following issues should be considered when you develop a plan for
supporting your application:
Easy Access - Before Internet became popular, technical support was provided by telephone, faxes
or mail. But now, most software providers provide it through a page on their Web site. The best and
most used method of offering technical support is over the telephone. You can provide technical
support by direct technical support phone number, by fax, through Email address or though a Web
page.
Questions and Problems - Questions and problems reported by the users should be dealt with in
a different manner. For questions dealing with how the application works, you can give a simple
answers, often right from the documentation. Try to collect enough information from the user
before giving them the remedies. When a problem is very hard to resolve try to come up with a way
around the problem. This workaround will allow the user to continue working with the application,
while you find a permanent solution for the problem.
Distributing The Application
After the development and testing of your application is over, prepare the distribution package. In
the distribution package you have to provide an installation program that copies all application files
and required Visual Basic files to the appropriate directory on the user's system. The installation
program can be created using the Application Setup Wizard included with Visual Basic. Installation
is perhaps the most difficult part of any application as all PC's are configured differently.
Using the Application Setup Wizard
The Application Setup Wizard helps to creates a professional looking installation program for your
application. The tasks done by the Application Setup Wizard include the following.
1. Compiles the application and compresses the files
2. Creates the actual installation program
3. Determines the number of disks needed and group the files according to the capacity of the
disk.
The Application Setup Wizard will go through several steps by prompting you for information
needed to build the installation disk.
Ownership of the Software
After creating the product, you have to make it sure that you own everything related to the
application. Many legal issues related to the ownership of the application and the source code have
to be dealt with. Issues like user registration of the application, software theft, trademark and
application copyright should be considered.
326
To protect the name of your application, you have to trademark the name. This process is little bit
expensive. You have to know many rules before you go for getting a trademark for your application.
Also you have to get protection against theft of your idea, design and implementation of
application.
The Project Package and deployment wizard is discussed in the next topic.
Project Packaging and Deployment
After you create a Visual Basic application you need to distribute it to others. This can be carried
out with the help of the Package and Deployment Wizard. Thus you can distribute any application
that you have created with Visual Basic to anyone who uses the Microsoft Windows operating
system.
Package and Deployment Wizard
The Visual Studio Package and Deployment wizard helps to create a package that contains all the
information needed for installing your application. Thus you can distribute your application on disks,
CDs, across networks and over the Internet and Intranet. The Package and Deployment wizard is
actually the newest form of the Setup Wizard, and has the additional features such as data access
support for ADO, OLE DB and RDO as well as support for the new DHTML and IIS applications.
You can launch the Package and Deployment Wizard by selecting Start->Programs->Microsoft
Visual Studio->Microsoft Visual Studio Tools->Package and Deployment Wizard
Then the following dialog appears:

The Package and Deployment Wizard has three options:


The first option is to create the .Cab files or to create self extracting setup program. The
created .Cab files have to be gathered to form a complete installation package. This can be carried
out by using the Package option.
The second option is to Deploy the application. The created application needs to be sent to the
user's location. This can be carried out by using the appropriate media such as CD's or Floppy disks
or a Web Site.
The Manage Scripts option allows you to manipulate the scripts you have saved from the previous
packaging and deployment sessions in the wizard.
Steps for making a Package of a project
Step 1:
327
Start the Packing and Deployment wizard and browse the project name that you want to distribute.
Step 2:
Next, select the package option, then the system will check whether the corresponding EXE of that
project exists or not. If that project does not exist, then the system will give you a message box. If it
exists the following dialog will be seen.

Here you can either select the corresponding EXE file (if it exists) or you can compile the project file
to create the corresponding EXE file.
Step 3:
If you selected the name of the EXE file then it will do some process and will show a dialog as
shown in the figure

Step 4:
328
In this dialog box you want to choose the type of the package that you want to create. If you chose
a Standard Setup Package, then it will create a package that can be installed by a setup.exe
program. If you choose a Dependency File package, then it will create an installation program that
uses a file listing information about the run-time components required by your application. Press
the Next button.
Step 5:
The following dialog will appear as shown below:

Here select the name of the folder in which you want to store the package. Then press the Next
button.
Step 6:
This will display the following dialog:

329
This dialog will display the list of files that the system inserts into the installation package. Here you
can add more files that you want to add with the installation program. You can also remove the
items by deselecting the check boxes. Press the Next button.
Step 7:
This will display a dialog which is shown as below:

Here you can set the cab file options. That is you can create a single cab file or multiple cab files. If
you want to distribute your application on floppy disks then you can use multiple cab file with each
of size less than 1.44 MB.
Here select the cab option and press Next.
Step 8:
This will display a dialog as shown below:

330
Here you can enter the name of the installation file. Then press Next.
Step 9:
The dialog displayed here (it is shown below)

This screen enables you to determine the start menu groups and items that will be created by the
installation process. Then press Next.
Step 10:
Then a dialog will appear.

Here you can set the path for install location. Then press the Next button.
Step 11:
The dialog displayed here (it shown below), enable you to specify which file is to be used as a
shared file.
331
Then press the Next button.
Step 12:
This will display a dialog box. Here you can enter the name that you want to save the settings for
this session. Then press the Finish button.

Then wait for a few seconds and your installation package is ready.
The steps for deploying the package are given in the next topic.
Steps for Converting a Package to Deploy
You can make a Package to deploy by using the second option Deploy. This enables you to create
the distribution media and copy all files to the location from which the user can access it. For that
do the following steps.
Step 1:
332
Select the Deploy option in the main dialog box of Package and Deployment Wizard. Then it will
display a dialog as shown below.

Click the Next button after entering the deployment script.


Step 2:
In this dialog box, you have to choose the package to deploy.

After selecting the package, press the Next button.


Step 3:
This will display a dialog as shown below:

333
Here you can select the Deployment method. If you want to use to distribute a package to a local or
network folder then you can select the Folder deployment method. If you want to use to publish
the package on a Web Server then you can choose the Web Publishing deployment method. Then
click on the Next button.
Step 4:
This will display a Dialog box as shown below:

In this dialog box you have to specify the location that you want to deploy the package. Then press
the Next button.
Step 5:
Next, a dialog box will appear, here you can enter the name of the file that you want to keep the
settings that are made within this Deployment.

334
Then click the finish button. Thus you can deploy your package.
Managing Scripts
The managing scripts option allows you to Rename, Duplicate and Delete your Packaging and
Deployment wizard. That is this wizard enables you to reuse the script that you already created.
The figure of Manage Scripts dialog box is shown below.

Workshops
1. What are the universal concepts of project life cycle?
2. What is testing and debugging?
3. What are product related issues?
Chapter – 15
Workshops - Solution
1. What are the universal concepts of project life cycle?
The universal steps in the Project Life Cycle are.
1. Design
2. Coding
3. Testing and Debugging
4. Documentation
Design
The most important part of creating any application is determining how it will be done. Once the
right approach to the problem is decided, the rest is easy. The time spent on designing an
335
application is the most important portion of the project. Time spend in designing is time saved in
coding and debugging.

The design process consists of creating the design description, functional definitions, technical
definitions, and form layouts of the application. The first step in the design process is to define the
overall application in words. This method gives a road-map for the developer to follow. A good
method for defining the functionality of an application is putting the functional definitions on paper,
describing each function in detail. In the second step, the function definitions are translated into a
technical definition called pseudocode. In the final step, you define the forms and reports that are
needed according to the functions already defined.
Coding

Coding is the next step in the design phase. In this phase, the actual coding is implemented
according to the design we have created. When you code the application, start with what the user
will actually see. In Visual Basic, code is organized in a hierarchical fashion. An application can
contain many modules like form modules, standard modules and class module. A good set of
coding conventions should be followed while coding.
Testing and Debugging
Testing is the process of detecting programming errors, while debugging is the process of
identifying the cause of an error and correcting it. The testing process is carried out in two steps:
1. Unit testing - In this testing method, the individual routines or sections are tested.
2. Integration testing - Here the project is tested as a single system by correlating all
different units.
Testing and debugging occupies as much as half of the total developing time and is the hardest
part in developing an application.
Documentation
Documentation of the application including description of the project, online help for the user and
printed manual should be made in the last phase.
2. What is testing and debugging?
Testing is the process of detecting programming errors, while debugging is the process of
identifying the cause of an error and correcting it. The testing process is carried out in two steps:
Unit testing - In this testing method individual routines or sections are tested.
Integration testing - Here the project is tested as a single system by correlating all different units.
Testing and debugging occupies as much as half of the total developing time and is the hardest
part in developing an application
3. What are product-related issues?
The important product related issues are given below:
Design of the Program
This is the phase where you study the problem and create the outline of how to carry out the
development procedure. A good design helps to minimize the time taken for coding.
Reporting - The reports generated by the application should meet the requirements of the user.
Online Help - The topics and the help files for that particular topic should be designed together.
This can reduce the delay for finishing the process.
Performance - The performance of the software is an important issue to be considered. The
finished application should meet the requirements of the user in every respect. The application
should be designed to run as fast and efficiently as possible.
Error Handling - The code should contain enough error handling routines so that even if Visual
Basic is unable to recover the errors, the application won't stop executing
Documentation - A printed documentation should be provided, which can give the users all
details about what the application will do. It should contain the table of contents, product

336
introduction, how to start, how to use the product, troubleshooting, how to get technical support
and an index.

337
338
339

You might also like