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

Visual Programming 1

Unit 1

Uploaded by

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

Visual Programming 1

Unit 1

Uploaded by

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

SONA COLLEGE OF ARTS AND SCIENCE, SALEM

SUBJECT NAME: VISUAL PROGRAMMING SUB. CODE:21UCA12

CLASS / SEM : III BCA / V FACULTY : Mrs. B. Mythreyee

CHAPTER 1

INTRODUCTION
 Visual basic is considered as the fastest and easiest way to create applications for
Microsoft Windows.
 It provides with a complete set of tools to simplify rapid application development.
 Windows based applications have a consistent user interface that helps the user to
simply ‘Point and Click’.
 All windows application provides a picture or icon or a button for a function. The will
point at that picture with a mouse and click. The computer jumps up to perform the task.

VISUAL BASIC
 Visual basic is an ideal medium for developing Windows based application.
 It is an event driven programming language.
 The “Visual” part refers to the method used to create the Graphical user interface (GUI).
 Instead of writing lines of codes to describe the appearance and location of elements, we
simply drag and drop pre-built objects into place on the screen.
 The advantage of such an approach was that there were fewer bugs and lesser surprises.
 Building prototypes became very easy.
 The “Basic” part refers to the BASIC language, a language used by more programmers
than any other language in the history of computing.
 Visual Basic has evolved from the original BASIC language and it contains several
hundred statements, functions, and keywords, which relate to the windows GUI.
Note:
The Visual basic programming language is not unique to Visual Basic. The Visual Basic
programming system, Applications Edition included in Microsoft Excel, Microsoft Access and
many other Windows applications uses the same language .

1
Windows Graphical User Interface:
Microsoft Windows uses a graphical user interface, or GUI. The Windows GUI defines how
the various elements look and function. As a Visual Basic programmer, you have available a
toolbox of these elements. You will create new windows, called forms. Then you will use the
toolbox to add the various elements, called controls. The projects that you will write follow a
programming technique called object-oriented programming (OOP).
Programming Languages: Procedural, Object-oriented, Event – driven :
There are literally hundreds of programming languages. Each was developed to solve a
particular type of problem. Most traditional languages, such as BASIC, C, COBOL,
FORTRAN, PL/I, and Pascal, are considered procedural languages.
That is, the program specifies the exact sequence of all operations. Program logic
determines the next instruction to execute in response to conditions and user requests.
The newer programming languages, such as Visual Basic, C#, and Java, use a different
approach: object-oriented programming. As a stepping stone between procedural programming
and object-oriented programming, the early versions of Visual Basic provided many (but not
all) elements of an object-oriented language.

For that reason, Microsoft referred to Visual Basic (version 6 and earlier) as an event-driven
programming language rather than an object-oriented language. But with Visual Studio,
which includes Visual Basic, C#, and F#, we have programming languages that are truly object
oriented. (Another language, C++, has elements of OOP and of procedural programming and
doesn’t conform fully to either paradigm.) F#, introduced in 2007, applies the object-oriented
paradigm to scripting languages for cross-platform development.

In the OOP model, programs are no longer procedural. They do not follow a sequential logic.
You, as the programmer, do not take control and determine the sequence of execution. Instead,
the user can press keys and click various buttons and boxes in a window. Each user action can
cause an event to occur, which triggers a Basic procedure that you have written. For example,
the user clicks on a button labeled Calculate. The clicking causes the button’s Click event to
occur, and the program automatically jumps to a procedure you have written to do the
calculation.

2
Visual Basic can be used in
1. To create a small utility programs.
2. An application for a department, work group, a large enterprise-wide system.
3. Distributed applications spanning the globe via the Internet.
Features of Visual Basic
 Data access features allow creating database and front-end applications for most popular
database formats, including Microsoft SQL Server and other enterprises-level databases.
 ActiveX technologies allow using the functionality provided by other applications, such
as Microsoft Word, Microsoft Excel spreadsheet, and other Windows applications.
 Internet capabilities makes it easy to provide access to documents and applications
across the Internet form within your application.(ActiveX Documents).
 Your finished applications is a true .exe file that uses a run-time dynamic-link library
(DLL) that you can freely distribute.(Application Setup Wizard).

Visual Basic Editions

 The Visual Basic Learning Edition, allows the programmers to easily create
powerful applications for Microsoft Windows 95 and Windows NT(r). It includes
all intrinsic controls, grid, tab, and data-bound controls.
 The Professional edition provides computer professionals with a full-featured set
of tools for developing solutions for others. It includes all the features of the
Learning edition, plus additional ActiveX controls, including Internet controls
and the Crystal Report Writer. Documentation provided with the Professional
edition includes the Programmer’s Guide, online Help, the Component Tools
Guide and the Crystal Reports for Visual Basic User’s Manual.
 The Enterprise Edition allows professionals to create robust distributed
applications in a team setting. It includes all the features of the Professional
edition, plus]
 The Automation manager,
 Component manager,
 Database management tools,
 The Microsoft Visual SourceSafe™ project-oriented version control
system and more.
The Object Model:

In Visual Basic you will work with objects, which have properties, methods,and
events. Each object is based on a class.

3
Controls / Objects
Think of an object as a thing, or a noun. Examples of objects are forms and
controls.Forms are the windows and dialog boxes you place on the screen; controls are
the components you place inside a form, such as text boxes, buttons, and list boxes.
Any applications must consist of a number of programs or procedures that perform
various activities. For example,
 There is one program that accepts text data from the user. Another
program that verifies the numeric data or validates the data entered by the
user.
 Another program that picks up the data from a database or a file and
displays it
 Another code to locate a picture file and shows it on the screen and to
check the options selected by the user.
 Another routine to update a file or database and so forth
Properties
Properties tell something about or control the behavior of an object, such as
itsname, color, size, or location. When you refer to a property, you first name the
object, add a period, and then name the property. For example, refer to the Text
property of a form called SalesForm as SalesForm.Text
For example, a control like the Label Box should not allow the user to edit its contents.
A control like Text Box that can accept multilane text or Word-wrap.
All these attributes are called properties therefore each control has certain properties
Methods
Actions associated with objects are called methods. Methods are the verbs of object
oriented programming. The action taken when the event occurs is the method. A method is a
piece of code that accomplishes a task. So in an event driven program, there are ‘Controls’,
which have ‘Properties’. When an ‘Event’ occurs to the ‘Controls’, some ‘Methods’ are
invoked. Unless an event occurs no method will be invoked.
Events
we can write procedures that execute when a particular event occurs. An event occurs
when the user takes an action, such as clicking a button, pressing a key, scrolling, or closing a
window. Events also can be triggered by actions of other objects, such as repainting a form or a
timer reaching a preset point. Visual Basic allows writing code to respond to such activities.

4
Therefore we need to write code only for those events. For example if your program has to
respond when the user clicks a command button, we need to write code only for click event.
Classes
A class is a template or blueprint used to create a new object. Classes contain the
definition of all available properties, methods, and events. Each time that you create a
new object, it must be based on a class. For example, you may decide to place three
buttons on your form. Each button is based on the Button class and is considered one
object, called an instance of the class. Each button (or instance) has its own set of
properties, methods, and events. One button may be labeled “OK”, one “Cancel”, and
one “Exit”. When the user clicks the OK button, that button’s Click event occurs; if the
user clicks on the Exit button, that button’s Click event occurs. And, of course, you have
written different program instructions for each of the buttons’ Click events.

Developing An Application
It has two main phases. 1. Planning 2. Programming. Each phase has a three – step
process.
The Three-Step Process in Planning Phase:
1. Design the user interface. When you plan the user interface, you draw a sketch of the
screens the user will see when running your project. On your sketch, show the forms and
all the controls that you plan to use. Indicate the names that you plan to give the form
and each of the objects on the form. The User Interface is built using the controls and
setting the properties for the controls. For example the location of the TextBox, where
the user will enter the Customer Id, or the location where the current date is to be
displayed. The size of the Command Buttons, the help displayed when the user moves
the mouse around the screen, etc.
2. Plan the properties. For each object, write down the properties that you plan to set or change
during the design of the form.
3. Plan the Basic code. In this step, you plan the classes and procedures that will execute when
your project runs. You will determine which events require action to be taken and then make a
step-by-step plan for those actions.
Later, when you actually write the Visual Basic code, you must follow the language syntax
rules. But during the planning stage, you will write out the actions using pseudocode, which is
5
an English expression or comment that describes the action. For example, you must plan for the
event that occurs when the user clicks on the Exit button. The pseudocode for the event could
be Terminate the project or Quit.
The Three-Step Process in Programming Phase:
After you have completed the planning steps and have approval from your user, you are
ready to begin the actual construction of the project. Use the same three-step process that you
used for planning.
1. Define the user interface. When you define the user interface, you create the forms and
controls that you designed in the planning stage.
2. Set the properties. When you set the properties of the objects, you give each object a name
and define such attributes as the contents of a label, the size of the text, and the words that
appear on top of a button and in the form’s title bar.
3. Write the Basic code. You will use Basic programming statements (called Basic code) to
carry out the actions needed by your program. The code invokes the methods associated with
the controls. If the user clicks on the control that displays the next record from the database, or
the user selects a particular option, or wants to ‘find’ the details of a client, etc. All such events
have to be acted upon.

There are number of built-in keywords, associated with the controls that accomplish the
given task. Visual basic provides a Form, which is another control. It also has properties, events
occur on it and it has Methods associated with it.
Visual Basic Integrated Development Environment also known as Visual Basic IDE, has
all the tools and fixtures to make the work easy. It has toolbars and menubars.

6
CHAPTER : 2

CREATING AN APPLICATION
Creating an application in Visual Basic means working with projects. A project is the
collection of files that is used to build an application.
A project consists of :
 One project file that keeps track of all components (.vbp).
 The .frm file. One file for each form(.frm). It contains the description of
the properties of the form and the controls on it.
 One binary data file for each form containing data for properties of
controls on the form (.frx). These files are not editable and are
automatically generated for any .frm file that contains binary properties,
such as picture or icon.
 The (.cls) file for each class module. This file is optional. The class file is
created when the own objects are created.
 The standard (.bas) file . This is also optional, one file for each standard
module. It contains module level declarations, procedures.
 The ActiveX Control (.ocx) file , becomes a part of the project file only if
optional controls are added in the program.
 The resource (.res) file, contains bitmaps, text strings that are used in the
program. We can have only one resource file.
The project file is simply a list of all the files and objects associated with the project as
well as information on the environment options. This information is updated every time the
project is saved. All these files and objects can be shared by other projects as well. When all the
files for a project is completed we can convert the project into an executable file. We can also
create other type of executable files such as .ocx, .dll files etc.
Example:
Visual Basic 6.0 (VB6) can be invoked by two ways:
 Double clicking on the shortcut path
 Going through the pull-up menu from start.
VB6 will first show a screen with the name of the owner of this copy of the software as
shown below.

7
Here a number of icons are displayed along with the type of projects that each will start.
The New Project Screen has three tabs:
 New
 Existing
 Recent
The current tab is ‘New’. Clicking the ‘Existing’ tab will display the existing projects
on the system. Clicking the ‘Recent’ tab will display the projects on which we have recently
worked.
First choose the Standard.Exe Icon by clicking on it. Then the following screen will be
displayed.

8
In all cases the types of files listed are the following
 .vbp : Visual basic Project File
 .vbg : Visual Basic Group File
 .mak : Project files built with earlier versions of Visual Basic.
Right on top we see “Project1-Microsoft Visual Basic [design]. This is the title of the
working project. The title is displayed on the title bar and it tells that we are currently working
on Project1 and we are in ‘design’ stage or design mode. There are two other modes. They are
‘run’ mode when the programs are running and ‘break’, while programs are being debugged.
Below the Title bar is the Menu Bar. The Menu bar has the following Menus:
File Menu :To open and save a new or existing project, to print and to make a project
file.
Edit Menu : For all editing requirement Cut, Paste, Find, Undo, etc.
View Menu : To view the various parts of the project, and the Visual Basic
environment.
Project Menu : Inserting or Removing forms, or objects to the project.
Format Menu : For spacing, placing and appearance of controls in the form.
Debug Menu : To remove the errors that have crept in.
Run Menu : To compile, start and stop a program.
Tools Menu : To add procedure and to customize the environment for the project.
Add-Ins Menu : To add tools like Data Manager, other Wizards, etc.
Window Menu : Arranging appearance of various windows on the desktop.
Help Men : For the on-line help that every programmer needs to refer to.

9
FILE MENU EDIT MENU

VIEW MENU PROJECT MENU

10
FORMAT MENU DEBUG MENU

RUN MENU TOOLS MENU

In order to built the application all the tools are needed. The most visible tools are
1. The Tool Box
2. The Project Explorer Window
3. The Properties Window
The Tool Box
The Tool Box contains a number of controls that will be used in order to built the
application.
The Project Explorer
The Project Explorer is located on the right side . It organizes the application as one
project. All the code, and controls that are used in the applications are stored in separate files.

11
It is called a ‘Project Explorer’ because it has an interface like the Explorer and it deals with the
working project.
The Project Explorer has three icons on its tool bar. Each icon represent a function.
1. To view the code
2. To view the controls
3. To show or hide the forms
Icon to View code to view object to toggle folders

The Properties Window


This Window lists all the properties for an object or control used in Visual Basic.
Currently the only object is the Form1. This is the big blank window that is sitting in the middle
of the screen. The caption in the properties window reads ‘Form1’.And that is the name on the
title bar of the Form1 window. We can change the caption, the height, the width, etc. Each
object has a number of properties that can be changed as the need dictates.

12
The Form Window
All the other windows are meant to serve this window. The form is used to see the
development of the application. The form has a title bar. It has the Maximize and the close
buttons. It is resizable and can be moved around the screen as needed.

To leave the environment there are two situations. They are


1. We have not made any changes
2. We have made some changes
In the first case there is nothing to worry about. In the second case we have to do a bit of
choosing and clicking.
Example:
Let as make a simple change.
o Click on the Form1 Window.
o Click on the properties Window.
o Click Caption.
Enter the option of your choice
Now the changes will be reflected on the Title bar of the Form.
Saving The Project
Go to file menu and choose the Save project option.
Then the name of the Form file will be asked. This is the name of the file and is different
from Form caption. Then the project name will be asked and the user will give it.
Note:
While saving the project on each time, Visual basic updates the project file(.vbp).A
project file contains the same list of files that appears in the Project Explorer window.

13
There are Four options available with regard to opening an saving projects. They are
 New Project
 Open Project
 Save Project
 Save Project As
New Project:
 Closes the current project, prompting you to save any files that have changed.
 We can select a type of project from the New Project dialog.
 Visual Basic creates a new project with a single new file.

Open Project:
Closes the current project, prompting you to save any changes.
Visual Basic the opens an existing project, including the forms, modules, and ActiveX
controls listed in its project (.vbp) file.
Save Project:
Updates the project file of the current project and all of its form, standards, and class modules.
Save Project As:
Updates the project file of the current project, saving the project file under a file name that is to
be specified.
Restart VB:
In the New Project Screen, press the recent tab. The project will be listed on the top.
Types of Project:
Following are the options available with Visual Basic:
Standard:
This project type must be chosen for the small or large standalone application is developed.

14
ActiveX EXE:
This option is chosen for the creation of an executable component. An ActiveX executable
component can be executed from other application. This will be a program that can provide
functionality to a number of other applications.
ActiveX Control:
This helps to create a custom ActiveX control that can be used in other application.
ActiveX DLL:
Like the ActiveX EXE it provides added functionality to the application, but will work ‘in-
process’ with an application.
Data Project:
Choose this option to create a project with the database components.
IIS:
This helps to create an Internet application.
ActiveX Document:
Creates a component that can take over the application at runtime. It creates an Internet
application that can be executed from a browser.
DHTML Application:
Creates an application that can be executed from a web browser only.

Customizing the Toolbar:

The following steps can customize the Tool Box:


 Place the Mouse on the Tool Box and click the right mouse button.
 From the pop-up menu choose components.
 A window pops up displaying the controls that are available.
 Click on the adding controls. Push the OK button and it will be on the Tool
box.
Tool Box:

Text Box Control:

15
 The Text box control is used to display or accept user input in the form of text like
name, customer ID, etc.
 It is used to display text and allows the user to edit the data in the box.
 A text box control is also called an edit field or edits control.
 It displays the information entered at the design time, entered by the user, or assigned to
the control in code at run time.
The Picture Box:
 A Picture Box control can display a graphic from a bitmap, icon, or metafile, as well as
enhanced metafile, JPEG, or GIF files.
 It clips the graphics if the control isn’t large enough to display the entire image.
Label Box:
Label Box is used to display text, which the user cannot change, such as a caption under
a graphic.

Option Button:
 The option button control is used to select one option from various options available.
 It allows displaying multiple choices from which the user can choose only one option.

Frame:

 Visual Basic 6 has only one set of option buttons to a form. In order to overcome this
limitation, VB6 provides the frame control.
 In this control each group of control can be placed on a different frame. It allows to
create a graphical or functional grouping control.
 To group controls, draw the Frame first and then draw controls inside the frame.
List Box:

Visual Basic 6 provides the List Box control to display a list of items from which the
user can choose one. The list can be scrolled if it has more items than can be displayed at one
time.
The List box has a small limitation:
 It can display only a set of items that are available.
 In future a new item cannot be added.

Combo Box:
 The combination of the Text Box and List Box gives the Combo Box.
 The user can either choose an item from the list or enter a value in the text box. The new
value entered can be added to the existing data.
16
 The List Box and the Combo Box display data usually from a database. In order to
access data and to manipulate data in a database like Access, SQL server, etc. For this
purpose VB provides a control called the Data control.

Data Control:

 Data control provides access to databases through controls on the form.


 It makes the job very easy when data has to be manipulated in a database.

If the Data control is not present in the toolbox it can be taken from the
components window.

For Example:

17
ScrollBar:
 The ScrollBar is used to scroll text box when the details does not fit in the text
box.
 There are two types of scrollbar. They are
o HscrollBar (Horizontal scroll bar)
o VscrollBar (Vertical scroll bar)

HscrollBar(Horizontal Scroll Bar):


It provides a graphical tool for
 Quickly navigating through a long list of items horizontally or
 A large amount of information, for indicating the current position on a scale, or
 As an input device or indicator of speed or quantity.

VscrollBar(Vertical Scroll Bar):


It provides a graphical tool for
 Quickly navigating through a long list of items vertically or
 A large amount of information, for indicating the current position on a scale, or
 As an input device or indicator of speed or quantity.
Command Button:
 It creates a button that the user can choose to carry out a command.
 When the user click on this button, then the computer will perform the task associated
with the button.
18
Check Box:
 It is used to make more than one choice
 It creates a box that the user can easily choose to indicate if something is true or false, or
to display multiple choices when the user can choose more than one.
Standard Set of Control:
The Drive, Directory and File List Controls:
 These controls are used to display available Drives, Directories and Files.
 The user can select a valid drive on the system.
 It lists the hierarchical structure of directories and files on the system.
 All the three controls are used in conjunction with each other or independently as
the need demands.

The Line and Shape Controls:


 These controls are used to draw lines, squares, circle, etc.

The Image Control:


 It is very similar to Picture Box control.
 Images displayed in an Image control can only be decorative.
 It use fewer resources than a Picture Box.

OLE (Object Linking and Embedding):


 It allows to link the program to another object or program.’
 For example, The word pad file is placed on the program and edit it through the
application.
 From within the program we can call Microsoft Excel, or MS Paint, complete the
work and get back to the application.
Other Tools for Software Development:
 An Editor to enter and edit code.
 A mechanism to trap syntax errors and other bugs.
 A table to record all the controls, files, etc. used in an application.
 Tools to create tables and more.
Integrated Development Environment (IDE):

The Visual Basic Integrated Development Environment (IDE) consists of the following
Elements:
Menu Bar:
 It displays the commands that will be used to work with Visual Basic.

19
 Besides the standard File, Edit, View, Window, and Help menus, menus are
provided to access functions specific to programming such as Project, Format, or
Debug.

For Example:

Context Menus:
 It contains shortcuts to frequently performed actions.
 To open the context menu,
o click the right mouse button on the using object.
o The specific list of shortcuts available from context menus depends on the
part of the environment where the right mouse button is clicked.
For example,
o When the toolbox is right clicked, context menu will be displayed.
o With the Components dialog box, hide the Tool Box, dock or undock the
Tool Box, add a custom tab to the Tool Box.

20
Tool Bars:

 It provides quick access to commonly used commands in the programming


environment.
 We can click a button on the toolbar once to carry out the action represented by
that button.
 By default, the standard Toolbar is displayed when the Visual Basic is started.
 Additional Toolbars for editing, form design, and debugging can be toggled on or
off from the Toolbar command on the view menu.
Tool Box:
 It provides a set of tools that will be used at design time to place controls on a form.
 We can also create our own custom layouts by selecting Add Tab from the context menu
and adding controls to the resulting tab.

Project Explorer Window:


 It lists the forms and modules in the current project.

21
 A project is the collection of files used to build an application.

Properties Window:
 It lists the property settings for the selected form or control.
 A property is a characteristic of an object, such as size, caption, or color.

Object Browser:
 It lists objects available for use in the project and gives a quick way to navigate through
the code.
 It is used to explore objects in visual basic and other applications.

Form Designer:
 It serves as windows that customize to design the interface of an application.
 We can add controls, graphics, and pictures to a form to create the look we want.
 Each form in an application has its own form designer window.
Code Editor Window:
 It serves as an editor for entering application code.

22
 A separate code editor window is created for each form or code module in the
application.
 The programmer can change the font size of the code.

Form Layout Window:


 The Form Layout Window allows to position the forms in the application using a
small graphical representation of the screen.

Immediate, Locals, and Watch Windows:

 These additional windows are provided for debugging the application.


 They are only available when we are running the application within the IDE.
Note:
 We can also add features to the Visual Basic interface by using program called an
Add-in.
 Add-ins, which are available from Microsoft and third-party developers, can provide
features like source code control, which allows to support group development project. 

23
Chapter:3
IDE, FORMS AND CONTROLS
Introduction:
(1) Here we shall begin with a simple example. The objective of the program is to accept
the password from the user. The program that we generate must allow us to enter the
text as password, verify the text entered and respond quickly.
(2) So the required components are,

(1) Text box to accept user input.


(2) Command button to initiate processing.
(3) Command button to exit the program.
(3) These controls are to be placed on the form. It is this window with which the user
interacts when they run the applications. It’s always possible to set the properties of a
form at its design time or at run time by writing codes.
(1) Design time is when the properties are set.
(2) Run time is when the application being executed
The Anatomy of a form
(1) The form occupies the control figure of the IDE it has got a title bar, Maximize,
Minimize the form can be resized and moved around the screen.

SETTING FORM PROPERTIES:


(1) A form has as many as 50 properties.
(2) Each of these properties will affect the appearance and behaviors of the form.
WORKING WITH PROPERTIES WINDOWS:
(1) All the controls placed on the form are assigned the properties during the design time
by invoking the properties windows.
(2) Shortcut key for the property windows: F4. Let us take a quick look of the properties
in the property windows

24
NAME:
(1) It is the name by which then form is referred in your code.
(2) The form must be given a meaningful name by default they are given names as
Form1, Form2.
(3) The name of a form cannot be changed at its run time.

CAPTION:
(1) The caption is the name that appears on the title bar. This name can be changed at the
run time but the names given must be meaningful
PICTURE:
(1) This consists of the name of the file that contains the picture to be displayed on the
form.
(2) This property can be changed both at it’s design and run time.
BACKGROUND COLOR:
(1) This property determines the background color of the form its very easy to select the
color by double clicking the value on the right side.
(2) A color pallet appears it’s always better to select standard windows color.
THE CONTROL BOX:
(1) This control box property has got only values (True / False) with it. If it is set true the
control box appears on the top left hand corner of the form.
(2) If it is set false, it does not appears.
(3) If it is set true, Maximize and minimize button appears on the title bar but, it is set
false, these buttons are not accessible by the user.

25
MIN BUTTON & MAX BUTTON:
(1) The value for this property is true or false.
(2) If this value is set False then the form cannot be minimized or maximized during run
time.
MOVABLE:
(1) The default is true if it is set false, the user cannot move the form all around the
screen during the run time, there by saving the information from getting lost.
BORDER STYLE:
(1) This property determines the type of window that the user will see during runtime.
(2) The users are not allowed to resize the windows because the important areas of the
application might get hidden.
FONT PROPERTIES:
The font properties for a form include.
Font Name:
Name of the font.
Font Bold:
If this is set true then the font appears bold.
Font Size:
The text sizes are set.
POSITION PROPERTIES:
This property like left, top, height and width is set at the design time as well as run time.
This property is used to locate the form at a place of your choice.
STARTUP POSITION:
This property is set at design time will specify the position of the form at runtime.
Mentioning all the 50 odd properties is not possible.

FORM METHODS:
Forms have methods that are used in control code to control their behavior. VB supports many
methods to change the appearance and behavior of the form at the run time.
MOVE:
It allows the programmer to position the form at a desired location on the screen.
Syntax:
FormName.Move Left, [Top], [Width], [Height]
Example:
Frm1.Move 0,0,3500,4000

GRAPHICS METHODS:
There are other properties for drawing lines, circles, clearing the form for any drawing
object. The methods are,
26
Circle : to draw circle(S).
Line : to draw a line(s).
Pset : to draw a point with a given color at a given location.
Point : returns the color of screen at the given location.
SHOW METHOD:
Usually a form comes to life only when the user click starts an application.
Initialize:
All the variables associated with the form are initialized.
Load:
During the load event the form with all the properties and events are loaded in the
memory.
Activate:
This event occurs when the Form gets the user input. This event also occurs when
the show or set focus method of the form is called.
Deactivate:
This event occurs when another form gets the focus.
Unload Event:
When the user closes the form, the form is unloaded from the memory. Another
event called the QueryUnload event occurs before the Unload event is fired.
Terminate:
This is the final event in the lifecycle of the form. All the memory held for the
form is released.

Show method:
This method displays the form to the user. It is like setting the ‘visible’ property
to True. Example: the statement:
Form1.show
This statement will show the form.
The show method had 2 optional parameters.
FormName.[showStyle],[Ownerform]
The ‘Show Style’ will determine the nature of the form
The Owner Form determines the form that is calling the new form.
Show Style:
There are two options.
1. The form can be opened, as Modal Form. The user cannot interact with the form
until it is active. This ShowStyle is chosen when you have to get user input or when
you have to pop up an important message.

27
2. The default option is a modeless form. The user can interact with other Forms even
while this Form is displayed.
Hide method:
When an application has a number of forms, it will appear as a crowded screen. So it is possible to
close the form, which is not required immediately. But as and when the user wants a particular form, the same
can be loaded. But this approach has a drawback. Loading and Unloading a form may be a time consuming. To
provide the form quickly the user the best way is to hide it.
Syntax:
Form1.Hide
This will not unload the form rather it will make the form invisible to the user. It
is opposite to Show method.
HOW DO YOU PUT OR CREATE THE CONTROL ON THE FORM?
There are two methods of creating the control on the form.
First Method:
 Now to place a command button, click with the left mouse button on the command
button.
 Move the mouse pointer from the toolbar to the particular location on the form where
you want the command button to appear.
 Notice the pointer has changed to a crosshair.
 Hold down the left mouse button and drag in any direction.
 Release the left button. The button will appear on the form.

Second method:
 Double-click the desired control on the toolbox. The control will appear at the center of
the form. Now you can move the control to any location on the form.

28
WORKING WITH A CONTROL:
(1) After you have placed the control on the form you may want to change the location or its
dimension.
(2) For resizing each control they have give 8 sizing handles that looks like a small solid
squares. During the design time these squares indicate that the control has got the focus.
(3) You can select the control by moving the mouse pointer inside the control and clicking
the left mouse button. The sizing handles will appear.
(4) The four handles on the 4 corners are to increase or decrease the length and breadth of
the control proportionately.

(5) The 2 sizing handles on the horizontal edges are used to increase or decrease the height
of the control.
(6) The 2 sizing handles on the vertical edges are used to increase the width of the control.
(7) To move the control to any location, click on the control, hold down the left mouse
button and drag the control to the locations of your choice.

MORE WORK ON A CONTROL:


(1) Click the right mouse button on the command button that you have created. A pop-
up menu will appear.
(2) This menu helps to align the control, view the code directly, view its properties. you
can also remove the control.

29
(3) This option will be useful when there are a number of control. And if suppose the
currently visible control is hiding another control, this option will get enabled. Select
it and you can see the control.
(4) Say, suppose you have group of controls on the form and you don’t want a control or
a group of controls to be moved from where you have placed them, then you can
select the Lock controls from the Format menu.

(5) To select the property option for a control select the control press F4 or Choose
Properties option from the View Menu.

30
The following are the important properties listed.
Cancel : this button is used to close the form. This property is set to True in
the property box.
Caption : this is what will be displayed on the button.
Default : a form can have only one default button. This button will
be activated by pressing the enter key.
Enabled : if, set to true the user can access it.
Name : the name by which it is referred to in the program.
Tab Index : the sequence in which the buttons get focus.
Tab Stop : if set to True, the user can use the TAB to set the focus on this
button.
Picture : the picture that will be displayed on the button when it is down or
selected.
Style : determine if the button will display text only or graphics also.
Visible : if set to true, the button will be visible to the user.
There are many properties other than this. To see other properties you can scroll
the mouse down and select the properties you want.
Command Button Properties:
Appearance : returns/sets whether or not an object is painted at run time.
Back color : sets the background color used to display text and graphics
in an object.
Caption : determines the text displayed on an object.
Disable Picture : determines the picture to be displayed when the button is
disabled.
Down picture : determines the picture to be displayed when the button is
clicked.
Mask color : determines the color in a picture’s button that will be
transparent.
(6) Enter the caption property of the command button “Start”. This name Start will be
displayed on the button.
(7) To allow the users to access the button using keyboard instead of the mouse, use ‘&’
symbol in front of the caption. Example: &Start. This will display the letter S with an
underline. Then you can access the button by pressing ‘Alt+S’.
(8) Properties like Appearance, Default, Cancel will have only True/False values.

THE CODE WINDOW:


(1) Open the code window by pressing the right mouse button on the control.
(2) It is also possible to select the code window from the View menu.
31
(3) Or press F7 after clicking on the control.

ANATOMY OF THE CODE WINDOW:


(1) The title bar of the code window will contain the name of the project and Form Name.
(2) There are two combo boxes. One contains the objects placed on the Form. Default is Form.
Other contains the events associated with the control. Default is Load.
(3) To write the coding for the command button placed on the form, just select it from the
combo box containing the controls and select an appropriate event for the command button,
may be ‘click’ event.
(4) A Form has 31 events associated with it and command button have 17 events associated
with it.
(5) The code for an event must be entered in the code window.
(6) Example:
Private Sub Command1_Click ()
End Sub

(7) The Private means that the variables declared and the code used here can be used only by
this function. The word Sub denotes sub-routine or function. End Sub means end of the
subroutine.
(8) The above two lines denotes that you are going to write coding for the command button.
The coding you write must be in between the two lines.

EXAMPLE PROGRAM:

32
This is a simple program, which tells that the color select must be displayed on the text box.
Suppose if the ‘RED’ button is select then it must tell the users the name of the color selected.
 We need 3 buttons with 3 different colors.
 We need a place where the message can be displayed.
 We need a button that will tell the computer that we are through with this exercise.
Step 1: creation and placement of controls
Create four Command Button controls
Create one TextBox.
Design a form as given above.
Step 2: Naming the controls
Click on a command button and press F4 to access the properties Window.
Change the caption appropriately for each of the Buttons.
On one button, the caption must be “&Quit”. This will be the button that you will click to exit
from the program.
Step 3:Changing the color for the Command Buttons.
Click on the style property and change it to ‘Graphical’ from ‘Standard’.
Click on the Backcolor property and change it to the color that you want the button to
display.
Observe that the color of the command button has changed to the color you have
selected.
Step 4: the Textbox Control
Click on the TextBox Control and press F4.
In the properties window, click on Text. The default value for this property is ‘Text1’.
Delete this value.
Now you have 4 buttons.
Three of the buttons have relevant colors.
One button is the ‘Quit’ button.
One is the TextBox.
Now entering the code:
(1) Click on one of the buttons. Press F7 or double-click on the button. The code window
will pop up. Click on the event Window. Usually click event procedure will be
displayed as the default property.
(2) Enter the following:

33
Text1.text = ”this is green”
(3) For the other 2 Command Buttons, add the appropriate code.
(4) For the Quit command button enter
End.
(5) Press F5.Save the changes.
Now you have successfully created and executed the first sample program using VB 6.0

Chapter: 4
VARIABLES IN VISUAL BASIC
What is a Variable?
(1) The values stored in what is called as Variables. Example: consider, a variable
‘TotalBillAmount’, which holds the total invoice value, another variable ‘ItemRate’
that holds the rate of the item and the variable ‘ItemName’ which holds the name of
the item. The variable ‘TotalBillAmount’ will keep changing as the items are added
to the invoice.
Code:
TotalBillAmount = TotalBillAmount + ItemAmount
(2) An application is a piece of code acting on data; data is manipulated by transferring
it into variables.

Declaring Variables:
(1) To write a program variables must be used. But before using the variables it is very
important to inform VB that the particular word is a variable. This process is called
as declaring the variables.
(2) Visual basic uses variables for storing values. Variables in VB are declared using the
DIM statement.
Syntax:
Dim variablename [As type]
For example:
Dim TotalBillAmount [As integer]
(3) A variable has to have a name. Here are the naming conventions.
 Must begin with an alphabet
 Must not have an embedded period or a special character.
 Must not exceed 255 characters.
 Must be unique within the same scope.
Data Types:
(1) Variables have a name and a data type.
34
(2) A data type of a variable determines how the bits/bytes representing those values are
stored in the computer’s memory.
(3) When a variable is declared it must have a data type along with it.
(4) All variables have a data type that determines what kind of data they can store.
(5) There are 2 types of variables. One needs to use different types of variables for
different requirements in order to optimize speed, and memory requirements.
(6) When you assign a value to a property, that value has a data type.
(7) You can declare arrays of any of the fundamental types.
(8) Here is the table, which will give you an idea about variables and their purposes.
Integer:
A numeric variable holds numeric values –32,768 to 32,767
Long (Long Integer):
A numeric variable holds a wide range of integers than integer. –2,147,483,648 to
2,147,483,647.
Single:
A numeric variable holds numbers with decimal places. –
3.402823E38 to –1.401298E-45 for negative values.
1.401298E-45 to 3.402823E38 for negative values.
Double:
A numeric variable with a wide range than single.
-1.79769313486232E308 to –4.94065645841247E-324 for negative values.
4.94065645841247E-324 to 1.79769313486232E308 for negative values.
Currency:
For holding monetary values.
-922,337,203,685,477.5808 to 922,337,203,685,477.5807

String:
For holding text or string values.
Byte:
A numeric variable, holding less than the value 255, 0 to 255.
Boolean:
For holding true or false values.
Date:
For holding date values inclusive of and between January 1, 100 to December 31,
9999.
Object:
For holding reference to objects in visual Basic and other applications.
User-defined (using Type):

35
Number required by elements. The range of each element is the same as the range
of its data type.
Variant:
A general-purpose variable that can hold most other types of variables values. Any
numeric value up to the range of a Double. With character values, it has the same range as for a
variable-length String.

VARIOUS DATA TYPES:


Integer:
 This data type is used to store whole numbers.
 They cannot be used in calculations where decimal numbers and fractions are involved.
 The integer data type occupies 2 bytes of memory.
 They are fast when used in calculations.
Long:
 This is big brother of the integer data type.
 It can hold much larger values than integer data type.
 It occupies twice as much space as integers.
 It must be used only in the places of the calculations where large numbers are involved.
 They are slower when compared to integer data type.
Single:
 This is equivalent of the floating-point numbers.
 It can store fractions and provide precision to a high level.
 It occupies 4 bytes of memory space and must be used in the calculations where very high
precisions are not needed.
 Example: if you want the value say, 400000000 raised to the power 50 then you may not have
the exact figure.
Double:
 This data type solves the problem of precision that the single data type lacks.
 It occupies 8 bytes of memory space and must be used in places where the requirement of
precision is very high.
 It should be used in places where we need accuracy beyond fourth decimal point.
Currency:
 This data type is used for holding values related to items rates, payroll details and other
financial functions.
 This data type must be used when you need accuracy beyond fourth decimal point.
Byte:
 This data type is used to hold values from 0 to 255.
 It cannot hold negative numbers or numbers larger than 255.
 The Byte data type occupies only one byte of memory.
36
Boolean:
 This data type accepts only True or False values.
 Since the default values for all numeric data type is zero, the default value for a Boolean data
type is also zero.
 Zero value for false and a non-zero value for True
 VB has the keywords as True or False.
Date:
 This data type holds date and time data.
 It can hold time from January 1 100 to December 31 9999, and time from 00.00.00 (midnight)
to 23.59.59 (one second before midnight).
 It occupies 8 bytes of memory.
 Midnight is 0, and midday is 0.5.
The string data type:
 This data type is used to hold values like strings. Most of the application has details such as
Name, Addresses.
 It is better to declare the variables with this data type if it will always contain a string value and
not a numeric value.
 You can declare the variables as a ‘variable-length string’ or ‘fixed-length string’. By default a
string variable is of variable-length string.
 Syntax:
To declare a fixed-length and variable-length strings:
Dim itemname as String * 30 ‘fixed-length strings.
Dim itemname as String ‘variable-length strings.
Here, in the fixed-length strings itemname will always be 30 characters long. If you add string
less than 30 characters then the itemname will be padded with enough trailing spaces. If you
assign string of too long the extra characters will be truncated.
Object data type:
 In visual basic forms, controls, and procedures are all considered as objects.
 VB is very much an object based programming language
 An object variable refers to an object within the application or in some other application. The
object can be a text box, or form.
 A variable declared as an Object is one that can subsequently be assigned to refer to any actual
object recognized by the application.
 A variable declared as an object occupies 4 bytes.
Example:
Dim db as database
Set db = opendatabase (“c:\SISI\asd.mdb”)
Variant data type:
 A variant data type is a variable that can change its type freely.
 It can accept text, numeric data, and byte data easily.

37
 The variable is given the variant data type by default. VB automatically converts the data type
when assigned to a variant.
Example:
Dim Var ‘ Var is a variant data type.
Var = “100” ‘ Var now contains a String value.
Var = Var – 80 ‘Var now contains the numeric value 20.
 Variant data type comes in handy when the data type is not known properly. But it may result in
error when you try to assign a mathematical value to a variant when it does not contain a
numerical value already.
 It is always better to check if a variant variable contains a value that can be used as a number.
The IsNumeric function performs this task.
 If you are performing concatenation then you must make sure that the values in the variants are
strings. Its always better to use “&” operator rather than the “+” operator.
 If both variant contains numbers then, “+” operator performs addition. If both of the Variant
contains strings, then the “+” operator performs concatenation. However if one of the operators
is string and other is numeric then there may be some problem. Visual basic first tries to convert
String into a Number. If the conversion is successful then, the “+” operator adds the two values,
if unsuccessful, it generates a Type mismatch error.
 Variant contains values that the other variables cannot handle. They are,
The Null Value
The Empty Value.
The Error Value.
 A variant occupies 16 bytes of memory regardless of the data type stored in it.
 It is always better to use the variant data type only when it is required as because it takes up
space, it is slow and may also cause error.
The Null Value:
 Null is commonly used in database applications to indicate unknown or missing data.
 If you assign Null to a variable of any type other than Variant, a trappable error occurs.
 Assigning Null to a variable doesnot cause an error.
Z = Null
 You can also use the IsNull function to test if a Variant variable contains Null:
If IsNull (X) Then
Debug.print………
End If
 Variables are not set to Null unless you assign Null to them.
The Error Value:
 In a variant, ERROR is a special value used to indicate that an error condition has occurred in a
procedure.
 An error value is created by converting a real number using the CVErr function.
The Empty Value:
 A variant has the Empty value before it is assigned a value.

38
 The Empty value is a special value different from 0, a zero length string (“”), or the Null value.
 The Empty value can be tested with the IsEmpty function.
 A variant containing Empty value can be used in expressions where it is treated as either 0 or a
Zero-length string depending on the expression.
 The Empty value disappears as soon as any value is assigned to a Variant variable.
Option Explicit and Option Strict:
Visual Basic provides two options that can significantly change the behavior of
the editor and compiler. Not using these two options, Option Explicit and Option
Strict, can make coding somewhat easier but provide opportunities for hard-to-find
errors and very sloppy programming.
Option Explicit
When Option Explicit is turned off, you can use any variable name without first
declaring it. The first time you use a variable name, VB allocates a new variable.
For example, you could write the line
Z = MyTotal + 1
without first declaring either Z or MyTotal. This is a throwback to very old versions of
Basic that did not require variable declaration. In those days, programmers spent many
hours debugging programs that had just a small misspelling or typo in a variable name.
You should always program with Option Explicit turned on. In VB, the option is turned
on by default for all new projects. If you need to turn it off (not a recommended
practice), place the line
Option Explicit Off before the first line of code in a file.
Option Strict
Option Strict is an option that makes VB more like other strongly typed
languages, such as C++, Java, and C#. When Option Strict is turned on, the editor and
compiler try to help you keep from making hard-to-find mistakes. Specifically, Option
Strict does not allow any implicit (automatic) conversions from a wider data type to a
narrower one, or between String and numeric data types.

39
THE SCOPE OF A VARIABLE:
(1) Visual basic is an event-driven programming language. Codes are written for each control
and individually for each event of the control and variables are declared for each procedure.
(2) Some variables used for calculations may not be used for changing the address of the
customer. So instead of hanging the variable around the computer’s memory, it is better to
define the scope of the variables.
(3) The value of a variable in one procedure cannot be accessed from another procedure. The
value of a variable is local to that procedure.
(4) Variables declared with Dim statement within a procedure exist, only as long as the
procedure is executing. When the procedure finishes, the value of the variable disappears.
These characteristics allow you to use the same variable name at different procedures
without any confusion.
(5) The scope of the variable is determined by the way it has been declared. It can be a
procedure-level variable or a module-level variable.

APPLICATION

MODULE 1
FORM FORM

MODULE 1
Public intx as Integer
Form1
Public inty as Integer

Public Sub Command1_click ()


Dim intx as Integer
Intx=30
Module1.intx = 10
Form1.inty = 20
Intx = 30
Msgbox “Module1.intx = “ & str (Module1.intx)
Msgbox “Form1.inty = “ & str (form1.inty)
Msgbox “Intx = “ & str (intx)
Load Form2
40
Form2.Show
End Sub

Private Sub Form_Load()


Msgbox “Module1.intx = “ & str (Module1.intx)
Msgbox “Form1.inty = “ & str (form1.inty)
Msgbox “Intx = “ & str (intx)
End Sub
Run the above program and check the values.
(6) Procedure-level variables are recognized only in the procedure in which they’re declared.
These are also known as local variables. You declare them using the DIM keyword.
Example:
Dim tot As Integer
Local variables are available only to that procedure where they have been declared and
another procedure cannot affect the value in this variable.
(7) Variable declared with Dim key \word exists as long as the procedure is executing.
(8) Values in the variables declared with Static keyword exist the entire time your application
is running.
Example:
Static count As Integer
(9) Variables declared with Static keyword exist as long as the application is running and are
usually used to update counters.
(10) A best example is that when the procedure terminates due to some problem the counter
variable, which is used to increment the value automatically, will again start from the first
say 0.in order to avoid this problem, the counter can be declared as Static variable. In this
case the value of the value of the counter will remain in the memory even if the procedure
terminates. When the procedure is invoked again the last value will be available to it.
(11) The advantage of this method is that this variable can be accessed only by this procedure
and not by any other procedure.

MODULE LEVEL VARIABLES


(1) These variables are used in case of situation where you need a variable to be available to
more than one procedure in a module.
(2) Variables declared as module-level variables would be available to all procedures within
that module. However they will not be available to procedures in other module.
(3) A module variable is declared using the keyword Private, in the declaration section of the
module.
Private count As Integer

41
(4) In order to make the variable available to all other modules, use the Public keyword. The
declaration must be made in the declaration section of the module. Public variables cannot
be declared in a procedure. They can be declared only in the declaration section of the
module.
Public temp As Integer.

Scope Private Public


Procedure – Level Variables are private to the Not Applicable. Can’t declare
procedure in which they appear the public variables within a
procedure
Module – Level Variables are private to the Variables are available to all
module in which they appear modules

Private and Public Variables:


(1) Can we have 2 variables with the same name? If the variables are local to their procedures
then there will be no problem. If we have public variable and private variable with the same
name then they will need to be referenced.
Example:
Public x as integer
X = 15
Again in a procedure we have declared a variable as,
Public x as integer
X = 10
Accessing x outside the procedure will give you the value “15”.
(2) If we have to access the variable x declared in the module-level then,
Debug. Print Module1.x
This will display the value “15”.
Declaring Variables:
(1) Variables can be declared using DIM statement and other methods also.
(2) By declaring variables in the declaration section of a form, standard, or class module, rather
than within a procedure, the variable will be available to all the procedures in the module.
(3) By declaring a variable using Public keyword, it will be available throughout the
application.
(4) Declaring a procedure-level variable using the Static keyword preserves its value even when
a procedure ends.
(5) You can use a variable without declaring it first. Visual basic will automatically create a
variable with that name. This is called Implicit Declaration.
Example:
Private Sub Command1_click ()
Invoiceamount = invoiceamount + salevalue
Msgbox” total invoice amount = ” & inviceamount
42
This program results in an error but the message box will show the result as, “total invoice
amount = 0”
(3) This is because when VB comes across “inviceamount” it automatically creates a new
variable with that name. It does not understand that you have misspelt the name of your
variable.
(4) Always declare a variable before they are used. This can be done by using “Option
Explicit” statement. This will avoid the problem of misnaming the variable and visual
basic will warn you all time it encounters a name not declared explicitly as a variable.
(5) Place this statement in the declaration section of a form, module or a class,
“Option Explicit”
(6) The other method is, from the Tools menu, choose Options, click the Editor tab and check
the Required Variable Declaration option. This will automatically insert the Option
Explicit statement in any new module.
(7) The Option Explicit statement operates on a pre-module basis; it must be placed in the
declaration section of every form, standard, and class module for which you want visual
basic to enforce explicit variable declaration.
(8) The Option Explicit statement helps to catch these kinds of error.
Constants
(1) While performing calculations, you will need to work with the figures that are constants.
Example:
Pi = 22 / 7, the value of pi is 3.14. This number can be assigned to a constant.
(2) Constants store values like variables but its value remains the same throughout the
application. There are built-in constants also. At the same time you can create your own
constants.
Creating Your Own Constants
(1) Syntax:
[Public | Private] Const constantname [As type] = expression
constantname should be a valid name.
As Type is the data type.
expression is the numeric or string value that has to be assigned to the constant.
(2) The naming rules are the same as that of creating variable names.
Example:
Const pi = 3.14
Dim radius = Val (Text1.Text)
Circumference = 2 * pi * radius
Scope of a Constant
(1) By declaring a constant in the declaration section of a form, standard, module, rather than
within a Procedure, the Constant will be available to all the procedures in the module.
(2) By declaring a Constant using the Public keyword, it is available throughout the
application.
(3) Declaring a constant in a procedure will be available to that procedure only.
(4) Constants can be defined with reference to other constants.
43
Example:
Public Const conA = conB * 1.414
Public Const conB = conA * 2
(5) The method of defining constants where each is defined in terms of other is called Circular
reference.

Importance of variables:
(i) A variable in the module cannot have the same name as any procedures or types
defined in the module.
(ii) A local variable can have the same name as public procedures or types or
variables defined in other modules.

Converting Data Types:


(1) It is necessary to convert the data type to the required data type .For example: say, we need
to convert the text data into numeric.
(2) Visual basic provides functions to convert values into data types that you need.

Conversion function Converts an expression to


Cbool Boolean
Cbyte Byte
Ccur Currency
Cdate Date
CDbl Double
Cint Integer
CLng Long
CSng Single
CStr String
Cvar Variant
CVErr Error

Arrays, how do you define them?

(1) An array is a set of similar items.


(2) All items in an array have the same name and are identified by an index.
(3) Array allows you to refer to a series of variables by the same name and to use a number that
is an index.
Syntax:
Dim name [([subscripts])] as [New] type [, varname…]
Example:
Dim num (10) as integer

44
Dim x (10 to 20) as integer.
Here in this example num variable is set to ‘11’ integers.
Num (0) is the first element of the array ‘num’.
Num (10) is the eleventh and the last element of the array.
In the second case, the first element ix x (10) of the array ‘x’.

Example:
Let us say you want to compute monthly sales for an organization. Sales figure for each
month have to be calculated. This mean we need to have at least 12 variables. It will be a
very difficult to manage all the 12 variables. But you can easily do this with the help of a
single variable.
Dim sale (11) as Long
The array what we have declared now is called as fixed size array. We know the total number of
items the array will hold.
Declaring Fixed-Size Arrays:
The scope of the array will depend upon the method of declaration.
(1) To create a local array, use the Private statement in a procedure to declare the array.
DIM counter (12) As Integer
(2) To create a module-level array, use the Private statement in the Declarations section of a
module to declare the array
Private counter (10) As Integer.
(3) To create a public array, use the Public statement in the Declaration section of a form.
Public counter (10) As Integer.
(4) In case of a fixed-size arrays it is compulsory to enter the upper bound of the array in the
parenthesis. The upper bound is the upper limit for the size of the array.
Private counter (10) As Integer.
This will result in an array of 11 elements.
(5) To specify the lower bound of an array
Dim counter (1 to 10) As Integer
Index number of counter range from 1 to 10.
Lbound is a function that returns the lower bound of an array.
Ubound returns the upper bound of an array.
Example:
Dim sinarray(24)
X = Lbound (sinarray)
Debug.print x
This will display 0 in the debug window.
Multi-dimensional Arrays:
(1) Arrays can have more than one dimension. A table of data will be represented by a
multidimensional array.
(2) To record the sales figure for 12 months for 3 departments in the organization,
Dim sale (11,2) as Integer.
45
Here the subscripts 11 indicate the months and subscript 2 indicates the departments.
(3) This is a 2 dimensional array. You can also have 3 dimensional arrays.

Example:
Dim sale (11,2,4) As Integer.
Here this statement records the sale of 5 products in 3 departments for 12 months.
Where, the subscript 11 indicate months, the subscript 2 indicate the three departments and 4
indicate the 5 products.
(4) Multidimensional array takes up a lot of space.
Dynamic Arrays:
 Dynamic arrays are used when you do not know the number of elements for an array.
Example: When you are reading a string into an array, you will not know the capacity of
the size of the array.
 A dynamic array can be resized at any time and this helps to manage memory efficiency.
Example: you can use a large array for a short time and then free memory to the system when
you are no longer using the array.
 You can also increase the size of the array after having declared them small.
 The ReDim is used in conjunction with the Dim statement while declaring the arrays.
 It is also possible to declare the size of the arrays large and then ignore array elements that are
not required.
Declaration of dynamic arrays:
(i) You can declare the dynamic arrays by giving it an empty dimension list.
Dim sale ()
(ii) Use the Redim statement to allocate the actual number of elements.
ReDim sale (11,4)
 The ReDim is an executable statement and can appear only in a procedure.this ReDim statement
can be used each time if you want to change the upper or lower bounds of a dimension. But it is
not possible to change the number of dimensions.
 The rules of syntax for declaring dynamic arrays are same as they are for Fixed sized arrays.
The scooping rules are also the same
Example:
Dim sale () As Integer
ReDim sale (12,6)
This will create a two-dimension array. The values for the subscripts of the array can be
passed using variables.
Example:
Dim sale () As Integer
Dim Months As Integer
Dim Depts As Integer
Months = 12
Depts = 6
ReDim sale (Months, Depts)
46
In this way, if the numbers of departments vary later on, the array and the program need not
be modified.

The Preserve Keyword


(1) Whenever the ReDim statement is used the previous array and its contents are destroyed.
(2) Visual Basic reset the value of the empty array (variants) to be Zero (for numeric arrays), to
Zero-length strings (for string arrays) or Nothing (for arrays of objects). This will be useful
only when you want to shrink the size of the array to take up a minimal memory space.
(3) In order to allow the array to ‘grow ‘ the Preserve keyword is used.
ReDim Preserve sale (12,9)
This will not destroy the data previously entered. It will only allow the the values for the
second dimension.
(4) In the case of single dimension array you can enlarge an array by one element without
loosing the values of the existing element using the Ubound function. This function refers to
the upper bound of the array.
ReDim Preserve sale (Ubound (sale) + 1)
More on ReDim:
1. Only the upper bound of the last dimension in a multidimensional array can be changed
while using the Preserve keyword, if any of the other dimension, or lower bound is
changed, a run-time error will occur.
Dim sum (11,2,4) As Integer
It can be resized using the Preserve keyword as follows
ReDim Preserve sum (11,2,6) As Integer
The following statement will return an error
ReDim Preserve sum (15,2,6) As Integer
2. Date type of an array cannot be changed using the ReDim function except the variant
data type. If the array is contained in the variant data type, the type of the element is
changed using an As type clause unless you are using the Preserve keyword. The
preserve keyword does not allow the data type to change.
3. If the size of the array is reduced, then the data in the eliminated element will be lost.
4. The ReDim statement acts as a declarative statement. If the variable it declares does not
exist at the module or procedure level, a new variable will be created. If another variable
with the same name is created later, ReDim will refer to the later variable and will not
cause a compilation error, even if Option Explicit is in effect.
5. ReDim should not be used as a declarative statement, but simply for redimensioning
arrays.

47
Chapter: 5
WRITING CODE IN VISUAL BASIC
The Code Window:
(1) VBA is the name of the programming language used in visual basic.
(2) Visual basic provides you the code window to compose (view, write, edit) all your
VBA code. It is possible to have many code window, as there are modules and cut
and paste code between them
Opening the Code Window:
(1) You can open the code window by pressing the right mouse button on the control.
 Choose the “View Code” option
 OR press F7 after clicking the control
 OR click on View in the menu bar and click view code.
 OR right click the name of the form from the project explorer and select view
code.

(2) Say if the focus is on the form then the code window will open in the default Form_Load ()
Event.

PARTS OF THE CODE WINDOW


Project name:
The name of the project to which the procedure belongs is contained in the title bar.
Module name:
A project can contain more than one module. So, while editing the code it would be very helpful
to know the name of the module whose code is being edited.
Object box:
This displays all the objects associated with the form including the form itself. When the code
window is selected by pressing F7, it displays the name of the control selected. Just click on the

48
down arrow to display the names of the other controls associated with the form. The names of
the controls are sorted in the alphabetical order. The names displayed will be the name that you
have specified against the name property in the property box of the control.
Procedures/Events Box:
This will list all the events recognized by Visual Basic for the control or form displayed in the
object box. When you select an event the event procedure associated with the event name is
displayed in the code window.
Split Bar:
Use the Split bar to view different parts of the code window. Each part can be scrolled
independently at the same time. Click on ‘Windows’ on the menu bar. From the drop down
menu select ‘Split’. This will split the window into 2 horizontal panes. This way you can scroll
for two different procedures, compare, cut and paste the code from one pane to other. The object
box will display the names of the procedures that have the focus. Double click on the bar to
close the pane or move the split bar.
Margin Indicator Bar:
The gray area on the left side of the code window is the margin indicator. This area will appear
only when you debug program.
Procedure View Icon:
Displays the selected procedure. Only one procedure is displayed in the code window.
Full Module View Icon:
Displays the entire code in the module.
The Procedure Separator:
It is a horizontal gray line that separates two procedures. It can be turned on or off.
THE ANATOMY OF A PROCEDURE
The procedure is a piece of code that gets executed when the control associated with it gets
activated. A procedure consists of all or most of the following,
(1) Name
Every procedure will have a name. Example: Say for a command button we would have
given the name as “okcmd” so a procedure called “okcmd_click () “will be executed
against the ‘Click’ event of the ‘okcmd’ button. The ‘Sub’ before the name means that
the procedure is a Subroutine.
(2) Declaration area
It is always a good idea to declare the entire variable at the beginning of the procedure.
This makes it easy to locate variables and verify the same during the process of
debugging.
(3) Statements
A procedure will contain VBA statements or code, which will perform the intended task.
It is possible add many statements to a procedure but if your procedure is short and
simple then it will be easy to debug if any error occurs.
(4) Call to other procedures and/or functions
The best way to reduce the number of lines in a procedure is to break up the entire
procedure into smaller functions or procedures and can be called as and when required.
49
So, if a particular task is to be performed by more than one event, that task can be
written as a procedure to a function and can be called as and when required. The
principle used here is “Write once and Use many times”.
(5) Terminator
The “End Sub” statement terminates every procedure.
SUBROUTINE OR FUNCTION
(1) Subroutines and functions are both procedures that are executed as a unit of code.
(2) The difference is that a Function will return a value to the calling program.
(3) A procedure will not return any value to the calling program.
(4) The function is declared with the ‘Function’ key word and terminated with the ‘End
Function’ statement.
Example:
Function sum (intn1 as integer, intn2 as integer) as integer
Sum = intn1 + intn2
End Function
The function sum can be called any where in the program. It can call simply by passing the
variables to it as arguments.
Dim intnum1 as integer, intans as integer, intnum2 as integer
Intans = sum (intnum1, intnum2)

The subroutines are declared with the ‘sub’ keyword and terminated with the ‘End sub’
keyword.
Example:
private sub command1_click()
msgbox “ Welcome to VB”
End sub

EDITOR FEATURES
Automatic Word Completion
(1) Visual Basic provides you with an additional feature of Auto Word completion. Here with
the help of this facility, to enter a word like ‘MouseButtonConstants’, enter the alphabet ‘m’
and press Ctrl+Spacebar.
(2) A drop-down list box will appear with a scrollable list of keyword starting with ‘m’. From
the list select the word you want with the help of the arrow keys and press spacebar. The
rest of the word is completed by visual basic
Auto List Member
(1) This feature is similar to the Auto Word Completion. Here as soon as you enter the name of
a visual basic object that has been created on the form, followed by a period, a drop -down
list box appears with all the properties and methods of that object.
(2) In order to select a property for the control, just click the required property form the drop
down list box and press space bar. The word is completed by visual basic.
Color cueing
50
(1) This is an important feature that makes the programmer’s job easy.
(2) Statements appear red in color if any error occurs, comments in green, visual basic
keywords in blue and identifiers like SQL in black.
Line continuation character
(1) This character is the underscore “_”. Whenever you find any long line, it will not fit on one
line.
(2) The line continuation character makes the reading of statements easy too.
Commenting and Uncomment statements
(1) Debugging code is usually done procedure by procedure.
(2) Suppose in case if you don’t wants any particular statements to be executed the then you can
delete them or block a group of statements.
(3) Visual basic provides the ‘comment block’ button on the View/Toolbar/Edit. Select the
block and click on the comment button and the entire block will turn green.
(4) You can uncomment the block by clicking on the ‘uncomment block’ button.

CONTROL STRUCTURES
 A program is not always linear. Even a simple routine where you have to check the password
entered by the user involves branching. Checking the data entered by the user involves
branching. Computing the total number of invoices for the day will mean looping. In short an
application may consists of branching, looping, etc.
 Visual basic provides you with necessary control structures in order to develop your
applications. In a program you may want to
Perform an action if a condition is true.
Perform an action repeatedly a certain number of times.
Perform an action till a certain condition becomes true.
Performs an action as long as a condition remains true.
Perform different action for different values of a variable.
The control structures in Visual Basic are
 If condition then
[statements]
[else statements]
Which conditionally execute a group of statements, depending on the value of an
expression.
 For counter = start to end [Step step]
[Statements] …
Next
Which repeats a group of statements a specified number of times.
 Do [{While | Until}] condition]

Loop
Which repeats a block of statements while a condition is true or Until a condition
becomes True.
51
 While condition
[statements]
Wend
Which executes a series of statements as long as the given condition is true.
 Select Case test expression
[Case expression list-n
[statements-n]] …
End Select
Which executes one of several groups of statements, depending on the value of an
expression.

The For … Next Statement


This structure is used when you want to execute a statement or a block of statements a certain number
of times.
Syntax:
For counter = start to end [Step step] [Statements]…Next
Example:
For I = 1 to 10
Total = Total + 1
Next I
This loop will compute the sum of the numbers from 1 to 10
How does this loop work?
The loop will work as long as the value of I is more than 1 and less than 10.
(1) The For statement initializes the value if I as 1. Since 1 is less than 10 the next statement is
executed.
(2) The statement Total = Total + 1 is executed.
(3) The statement Next I increments the value of I by 1.
(4) The control shifts to the beginning of the loop, where the value of I is checked.
(5) If the value of I is more than 10, the loop terminates, else steps 2 to 4 are executed.
Variation
The increment value is decided by the [Step, step] keyword.
Example
For I = 0 to 100 Step 5
The variable I will assume the value 0,5,10,15, etc.
Code
For I = 5 to 50 Step 5
Print I
Next I
Will print all the numbers from 5 to 50 with an increment of 5.
The Decision Maker …. If

52
(1) The If condition…Statements is used when a program has to perform an instruction
depending upon the value of an expression.
(2) If the expression returns True, then the set of statements are executed. Or if the expression
returns False, no statements are executed.
Syntax:
If condition Then the condition must return a True of false
[Statements]
[ElseIf conditio-n Then the condition must return a True or False
[ElseIf statements]….
[Else
[elsestatements]]
End If
Example 1
If string1 = string2 then msgbox “both strings are equal”
Example 2
If age <= 18 then
Juniors = Juniors + 1
Else if age <= 50 then
Seniors = Seniors + 1
Else
Old = Old + 1
End if
How does it work?
(1) The first IF statement evaluates the expression.
(2) If an expression returns True value the statements after the THEN keyword are executed.
(3) If an expression returns False value, the rest of the ElseIf condition are evaluated by turn.
(4) If any expression returns a True value, the statements following the related THEN keyword
are executed.
(5) If there are no Else If or Else conditions, program continues with the statements following
the End If statement.
Example:
If text1.text = “a” then
Msgbox “you are here”
Else
Msgbox”try again”
End if

Private sub okcmd_click()


If txt1 = “a” then
Login = True
Else
Msgbox “invalid password”
53
End if
End sub

The Loop
This structure is used when we want the program to repeat a block of statements while a condition is
True.
Syntax:
Do [{While | Until} condition]
[Statements]
[Exit Do]
Loop
Example:
I=1
Do While I < 10
Sum = Sum + I
I = I + 1 Loop
How does it work?
(1) The value of I is initialized to 1.
(2) The exit condition is checked first to see if I is less than 10. If I is less than 10, then the
statements in the loop are executed. (3) Sum = Sum + 1 and I=I+1 are executed.
(3) The keyword Loop returns the control to the Do While ….. statement, where the exit
condition is checked.
The while loop
This structure executes a series of statements as long as a given condition is true.
Syntax:
While condition
[statements]
Wend
Example:
Dim I as integer
I=1
While I < 10
Sum = Sum + 1
I=I+1
Wend
How does it work?
(1) While checks the condition. If it is true the statements are executed.
(2) When the program encounters the Wend statement, the control returns to While.
(3) If the condition returns true, the process is repeated.
(4) If the condition is false, statements following the Wend are executed.
54
Select Case …. End Select
This method is used when the program has to execute one of several groups of statements, depending
on the value of an expression.

Syntax:
Select Case testexpression
[Case expressionlist-n
[statements-n]]….
[Case Else
[elsestatements]]
End Select
Example:
Select Case age
Case <=18
Msgbox”you are in juniors”
Case <=50
Msgbox “you are in seniors”
Case Else
Msgbox “you are in the old”
End Select
How does it work?
(1) the test expression is evaluated with the case expression.
(2) If the two match, the statement following that case, up to the next Case or End Select in the
case of the last clause are executed.
(3) If the two do no match, the test expression is evaluated with the next case expression.
(4) If more than one case expression matches with the test expression, the statements of the first
case only are executed.
(5) The case else is used to indicate the statements to be executed if no match is found between
the test expression and the case expression.
(6) If there are no matches, program execution continues with the statements after the end select

(7) The select case is used when using the IF becomes complex.
(8) The select case can evaluate any number of conditions without making the program difficult
to read and debug.
(9) The case expression can evaluate ranges too.
Example1: case 1 to 10
Example2: case 10,15,20..
Example3: case is<=10, where the is keyword is used.

55
Boolean Expressions:

The test in an If statement is a Boolean expression, which evaluates as True or False. To form
Boolean expressions, also referred to as conditions, you use comparison operators, also
called relational operators. The comparison is evaluated and the result is either True or False.
Boolean expressions can be formed with numeric variables and constants, string variables and
constants, object properties, and arithmetic expressions. However, it is important to note that
comparisons must be made on like types; that is, strings can be compared only to other strings,
and numeric values can be compared only to other numeric values, whether a variable,
constant, property, or arithmetic expression.
Comparing Numeric Variables and Constants
When numeric values are involved in a test, an algebraic comparison is made; that is, the sign
of the number is taken into account. Therefore, negative 20 is less than 10, and negative 2 is
less than negative 1.
An equal sign (=) means replacement in an assignment statement. In a comparison, the equal
sign is used to test for equality.
ARITHMETIC OPERATIONS:
The arithmetic operations you can perform in Visual Basic include addition, subtraction,
multiplication, division, integer division, modulus, and exponentiation.
Arithmetic Operators
+ Addition
– Subtraction
* Multiplication
/ Division
\ Integer division
Mod Modulus—Remainder of division
^ Exponentiation

The first four operations are self-explanatory, but you may not be familiar
with \, Mod, or ^.
Integer Division (\)

56
Use integer division (\) to divide one integer by another, giving an integer result and
truncating (dropping) any remainder. For example, if TotalMinutesInteger = 150, then
HoursInteger = TotalMinutesInteger \ 60
returns 2 for HoursInteger.
Mod
The Mod operator returns the remainder of a division operation. For example,

if TotalMinutesInteger = 150, then MinutesInteger = TotalMinutesInteger Mod 60


returns 30 for MinutesInteger.
Exponentiation (^)
The exponentiation operator (^) raises a number to the power specified and returns
(produces) a result of the Double data type. The following are examples of
exponentiation.
SquaredDouble = NumberDecimal ^ 2 ' Square the number--Raise to the 2nd power.
CubedDouble = NumberDecimal ^ 3 ' Cube the number--Raise to the 3rd power.

Evaluation of an expression occurs in this order:


1. All operations within parentheses. Multiple operations within the
parentheses are performed according to the rules of precedence.
2. All exponentiation. Multiple exponentiation operations are performed
from left to right.
3. All multiplication and division. Multiple operations are performed from
left to right.
4. All integer division. Multiple operations are performed from left to right.
5. Mod operations. Multiple operations are performed from left to right.
6. All addition and subtraction are performed from left to right.

The Comparison Operators


Symbol Relation
> greater than
< less than

57
= equal to
<> not equal to
>= greater than or equal to
<= less than or equal to Name
Comparing Upper case and Lower Case Strings:
The ToUpper and ToLower Methods—General Forms
TextString.ToUpper()
TextString.ToLower()
An example of a Boolean expression using the ToUpper method follows.

If NameTextBox.Text.ToUpper() = "BASIC" Then


' Do something.
End If

COMPOUND BOOLEAN EXPRESSIONS:


You can use compound Boolean expressions to test more than one condition. Create compound
expressions by joining conditions with logical operators, which compare each expression and
return a Boolean result. The logical operators are Or, And, Not, AndAlso, OrElse, and Xor.
Logical
Operator Meaning
Or If one or both expressions are true, then entire expression is true
And Both the expressions must be true for the entire expression to be true
not Reverse the condition so that true expression will evaluate to false and vice
versa
Displaying Messages in a MessageBox:
The MessageBox Object—General Forms
There is more than one way to call the Show method. Each of the following statements is a valid
call; you can choose the format you want to use. It’s very important that the arguments you supply
exactly match one of the formats.
MessageBox.Show(TextMessage)
MessageBox.Show(TextMessage, TitlebarText)
MessageBox.Show(TextMessage, TitlebarText, MessageBoxButtons)

58
MessageBox.Show(TextMessage, TitlebarText, MessageBoxButtons, MessageBoxIcon

The TextMessage is the message you want to appear in the message box.
The TitlebarText appears on the title bar of the MessageBox window. The MessageBoxButtons
argument specifies the buttons to display. And the Message-BoxIcon determines the icon to
display.
The MessageBox Statement—Examples

Two sample message boxes created with the MessageBox class.


MessageBox.Show("Enter numeric data.")
MessageBox.Show("Try again.", "Data Entry Error")
MessageBox.Show("This is a message.", "This is a title bar", MessageBoxButtons.OK)

Chapter: 6
WORKING WITH FILES
Introduction:
(1) All the data that you create, manipulate is stored as file. Example: Biblio.mdb, is a
database
(2) But with the advent of the database even the programmer did not have to deal with
files. But there may be some situations where we have to transfer the data from a file
to your database or write data from your database to a file.
(3) The easiest common medium for exchange of data between two applications or
hardware/software platforms is a file.
(4) The controls that Visual Basic has provided to help us navigate through the drives
and directories of our computer. Hard disk is divided into one or more drives. Each
drive will have one or more directories, and each directory will have zero or more
files.

Visual Basic File System Controls


Moving from one drive to another : the DriveListBox
Moving from one directory to another : DirListBox
List files in a directory : FileListBox
The DriveListBox
 This is a drop down list box. It will display the list of drives on your computer.
59
 It gets all the information from the operating system.
 It allows the user to select a drive of his choice.
 Selecting a particular drive records a change in the Drive property of the
DriveListBox.

The DirListBox Control


 A drop-down list box that displays a hierarchical list of directories in the current
drive.

The FileListBox
 Displays all files in the current directory or folder. Allows users to set up
search criteria for files.
These three controls allow the user to locate a file on his computer.
Let us create a program that will display the drives, directories and the files therein.
Phase I

Open a Form and create the following controls on it.


The DriveListBox
The DirListBox
The FileList Box

Your form will look like this.

Add the following code


Private sub Drive1_Change ()
Dir1.Path = Drive1.Drive
End Sub
60
This line establishes a connection between the DriveListBox and the DirListBox, such that the
directories for the selected drive are displayed.
Private Sub Dir1_Change ()
File1.Path = Dir1.Path
End Sub
This code establishes a connection between the DirListBox and the FileListBox, such that all
the files in the selected directory are displayed.
Run the program and check it out.
Phase II
Adding search criteria
Add a TextBox control to the form
Add the following code
Private Sub Text1_Change ()
File1.Pattern = Text1.Text
End Sub
This statement changes the ‘Pattern’ property of the FileListBox. If the user enters “*.Doc” in
the textbox, only files with “Doc” extension will be displayed.

Visual Basic has built in functions such as


ChDrive : changes the current logged drive.
ChDrive : changes the default directory
MkDir : creates a new directory
RmDir : deletes a directory
Name : renames a file
Kill : deletes a file
FileCopy : copies source file to destination
GetAttr : returns the date and time when the file was modified
SetAttr : sets the attributes of a file.
ChDrive: changes the current logged drive
Syntax:
ChDrive drive
 Drive is a string, which specifies an existing drive.
 If the drive does not exist, the drive will not change.

Example
ChDrive “A”
This will change the drive to “A”

ChDir: changes the current directory or folder.

61
Syntax:
ChDir path
 Path is the new directory or folder.
 Path cannot contain the name of the drive. If the drive is not mentioned, the
change is made on the current drive.

Example
ChDir “C: \ AZAM \ EMSQUARE”
This will change the current directory to “C: \ AZAM \ EMSQUARE”.

MkDir: creates a new directory or folder.


Syntax:
MkDir path
 Path is the string that identifies the directory to be created.
 Path may include the drive name. If the drive is not specified, the new
directory is created in the current drive.

Example
MkDir “C: \ EMSQUARE\ Expermnt”
This will create a directory ‘expermnt’ under ‘c:\ EMSQUARE’.

RmDir: deletes a directory. Removes an existing directory or folder.


Syntax:
RmDir path
 Path is the string that identifies the directory to be removed.
 Path may include the drive.

Example
RmDir “C: \ Temp\ Temp1”
This will delete the directory ‘Temp1’ which is a sub-directory of ‘c:\ Temp’’.

Name: renames a disk file, directory, or folder.


Syntax:
Name oldname as newname
 oldname is the name of the file that has to be renamed or moved.
 Newname is the string that identifies the new name that the file should have.
 If the Newname contains the name of the different directory then the file is
moved to the new directory.
 Newname cannot already exist.
 The file being renamed should not be open.
62
Example
Name Oldfile as Newfile
Oldfile is renamed as Newfile.

Kill: delete a file or files.


Syntax:
Kill pathname
 Pathname is the name of the files to be deleted.
 Kill accepts wildcard characters like “*” and “?” to delete a group of files.
 Kill will not delete open files.

Example
Kill “testdoc” -- to delete the file ‘testdoc’.
Kill “*.Doc” -- to delete all the “*.Doc” files in the current directory.

FileCopy: copies the source file to the specified destination.


Syntax:
Filecopy Source, Destination
 Source is the string that identifies the name of the file to be copied.
 Destination is the string that identifies the target file name.
 Filecopy should not be used to copy an open file.

Example
Filecopy Maxfile Highfile.
This will copy the contents of the file Maxfile to Highfile. If highfile exist it will be overwritten.

FileDateTime: returns a variant that indicates the date and time when a file was created or last
modified.
Syntax:
FileDateTime (pathname)
 Pathname is the name of the file.

Example
Dated = FileDateTime(“Maxfile”)
This will return the date and time when the file ‘Maxfile’ was last modified.

GetAttr: returns the attributes of the file as an integer value.


Syntax:
getAttr (pathname)

63
 Pathname is a string that identifies the file.

Example
Dim Fileattrib as Integer
Fileattrib = GetAttr(Maxfile)
Return values
The value returned by GetAttr is the sum of the following attributes values:

Constant Value Description


vbNormal 0 Normal
vbReadOnly 1 Read-Only
vbHidden 2 Hidden
vbSystem 4 System
vbDirectory 16 Directory or folders
vbArchive 32 File has changed since last backup

SetAttr: sets the attributes of a file


Syntax:
SetAttr pathname, attributes
 Pathname is a string that identifies the file.
 Attributes, is a numeric expression or constant that specifies a file attribute.

Example
SetAttr Highfile, vbHidden + vbSystem
This will set the attributes of the file as Hidden and system.
Settings
The attributes argument settings are:
Constant Value Description
vbNormal 0 Normal
vbReadOnly 1 Read-Only
vbHidden 2 Hidden
vbSystem 4 System file
vbArchive 32 File has changed since last backup

64
Types of Files:
(1) The common medium of exchange of data is the text file. The text file can be accessed in a
number of ways.
(2) The files are classified as,
 Sequential access files.
 Random access files.
 Binary access files.
Working with files
Before knowing the structure of the file, the length of a record, the details of it must be
known.
What is a Record?
(1) To explain what is a record let us first begin with an example. We have a file called the
“Item Master”.
(2) The data in this file contain the details of the items in the store.
Itemcode Itemname Itemrate Unitofmesr Qtyonhand
RR232 Raw Rice 17.00 KG 1400
RR435 Wheat 20.00 KG 2040

(3) These are called as records. Each record consists of details like Name, Code, and
Rate. A file can have 0 or more fields.
(4) Structure of the file as per the table:

Field name Start Width


position
Item code 1 17
Item name 18 29
Item rate 47 16
Unitofmesr 63 16
Qtyonhand 79 9

(5) A file can have records of the same size or of different sizes. There can a fixed-length or
variable length record.
(6) We can have the same file displayed as a variable-length record file.
RR232, Raw Rice, 17.00, KG, 1400
RR435, wheat, 20.00, KG, 2040
In this case each record is of different size and is separated by a comma.

65
(7) The size of the file is of great importance. The NewLine character is important. The
sequential file, whether the file has a fixed-length record or variable-length record, each
record is terminated by the NewLine character.
(8) While working with any type of file
 Open a file
 Read the file
 Close the file
 Determine the end of file
 Determine the length of file
 Determine the beginning of file.
There are commands to deal with all these activities.
Opening a sequential file
(1) A sequential file is a collection of ASCII characters. It is also referred to as a steam of
bytes.
(2) The file can be read character by character, or by line by line, or as a block of characters.
Complete Syntax
Open pathname For mode [Acess acess] [lock] As [#] filenumber [Len=reclength]
Syntax
Open pathname for Input As [#] filenumber
 Open is the command to open the file.
 Pathname is the full pathname of the file to be opened.
 Input specifies that the file must be opened for reading purpose.
 Filenumber is the number assigned to the file for purposes of identification.
 The filename must be unique. The range is from 1 to 511.
Example
Open c:\ EMSQUARE\ItemMaster.txt for Input As #1
 c:\ EMSQUARE\ItemMaster.txt is the full pathname of the file.
 The ‘Input’ keyword means that the file is being opened for reading.
 #1 is the file identifier. This number will identify this file till it is closed.

Closing a file
(1) Once a program has opened a file, another program cannot open it again.
(2) A file must be closed for the operating system to write the data from the associated buffer to
the file.

Syntax
Close [filenumberList]
 Close is the command.
 FilenumberList is the list of the filenumber that represent the files that have to be
closed.
 The filenumber will be returned to a list that id displayed by the function ‘FreeFile’.

66
 If the file has been opened for writing, then the output buffer is written to the buffer
allotted for that file.
Example
Close #1
 This will close the file C:\EMSQUARE\ItemMaster.txt
 The filenumber #1 will be returned to the list of free file numbers.

The FreeFile Function


This function returns a free file number that is available.
Syntax
FreeFile [rangenumber]
 FreeFile is the function name.
 Rangenumber can be 0 or 1. If ‘0’ then it returns a number between 256 and 511. If
‘1’ then it returns a number between 256 and 511.
Example
Dim Filenum As Integer
Filenum = FreeFile (1)
Open C:\EMSQUARE\ItemMaster.txt For Input As #Filenum.

Reading a file
(1) The open command creates a buffer in the memory, which helps in I/O operations.
(2) The buffer is a block of memory that is reserved for I/O operation on the file.
(3) The Read operation transfers the content of file from the disk to the buffer.
(4) The ‘Input’ function provided by VB reads a sequential file’s content into the disk.
(5) The Input function has 3 operation or methods
1. Input
Syntax
Input (number, [#] filenumber)
 Input is the command name.
 Number is the number of characters to read.
 Filenumber is the number of the open file that has to be read.
Example
String1 = Input (25, #1)
 String1 is the variable that will hold the data read from the file.
 The number of characters read is 25.
 The filenumber is #1.

2. Input #
Syntax
Input #filenumber, varlist
 filenumber is the file number of the file to be read.

67
 Varlist is the list of variables that will hold the data.
Example
Input #1, SerialNum, Name, Designation
 If the file has the details such as 0234, Maxworth and Operator, the example will suit
this.
3. Line Input #
(1) This version of input command reads an entire line into a variable.
(2) It will continue to read the contents of the file.
Syntax
Line Input #filenumber, databuffer
 Line means read the entire line.
 Filenumber is the file number of the file to be read.
 Databuffer is the variable that will hold the line that has been read.
Example
Line Input #1, linebuffer
This statement will read one line of the file into the variables ‘linebuffer’

EOF & LOF


EOF (file number): this will return true when the end of file is reached.
LOF (file number): this will return the size of the open file in bytes.
Example 1
Dim intfilelength as Long
Dim strfilename as String
Dim strdatabuffer as String
Dim intfilenum as Integer
strfilename = “C:\EMSQUARE\ItemMaster.txt”
intfilenum = freefile ()
open strfilename = LOF (#intfilenum)
strdatabuffer = Input (intfilelength, #intfilenum)
debug.print strdatabuffer
close #intfilenum
(1) The entire file is read into the string variable ‘databuffer’
(2) The contents of the file are displayed with the command ‘debug.print databuffer’

Reading a File with Variable-length Records


(1) A lot of work is involved when you need to read a data from a file with variable-length
records.
(2) The method of reading a file will be same but the only difference will be in the method of
parsing the line of data that has been read.
(3) The fields in the file are separated by a comma. The comma is a delimiter. We have to
separate the fields on the basis that each field ends with a comma.

68
(4) Visual basic provides the ‘inStr’ function. The Instr function searches for a string within
another string and returns the position where the string is found.
IntPos = InStr(1, datastring,”M”) will return the position of the first occurrence of the
character “m” in the string ‘datastring’
(5) We have to locate the first comma to arrive at the end if the first field. This will also mark
the beginning of the second field. The characters between the first and second commas will
represent the second field.
(6) Assume that our data is in the variable ‘strdatabuffer’.
Dim intstartpos as integer
Dim intendpos as integer
Intstartpos = InStr(1, strdatabuffer,”,”)
‘ This will return us the first occurance of the first comma
Txtitemcode = left (strdatabuffer, intstartpos –1)
‘The “-1” is to avoid including the comma in the item code
Intendpos = InStr (intstartpos +1, strdatabuffer, “,”)
‘This will give us the location of the second comma
Txtitemname = mid (strdatbuffer, intstartpos+1, intendpos-intstartpos-1)
‘The term “intendpos-intstartpos-1” specifies the length of the second field.

Writing to a Text File


(1) We can open a file to
Read only
Read and Write to the File
Append contents to the File.
Open pathname For [Input Output Append] As [#] filenumber [Len = Length]
(2) Before writing to a file, you have to decide if
Overwrite the existing file
Append new data to the file
Create a new file.
(3) When you open the file to write, the Open command
Creates a file if does not already exist
Overwrites the existing contents if the file is opened in the ‘Output’ mode.
Appends new data if the file is opened in ‘Append’ mode
Example:
Open pathname for Append as #1
Where,
 Open is the command to open the file
 Pathname is the filename of the file
 Append is the keyword to open the file in the append mode.
 #1 is the filenumber of the file to be written into.
Now we have to write data to it,
Syntax
69
Print #filenumber, Outputlist where
 Print is the command to write the data to the file.
 Filenumber is the number that has to be written to.
 Outputlists consists of the data to be written, and arguments to position the data
correctly.
The ‘Outputlist’ consists of the following.
[ { Spc (n) | Tab [ (n) ] } ] [Expression] [CharacterPosition]
 Expression is the data to be written Spc and Tab instruct where the data must be
placed.
 Characterposition indicates where the next data should be placed.
Example
Dim strdatastring As String
Dim strfilename As String
Strfilename = “C:\EMSQUARE\Itemmaster.txt”
Datastring = “ RR100, Raw rice , 17.00, KG,400”
Open strfilename For Append As #1
Print #1, datastring

Writing Data To A Fixed-Length Record File


While writing to a fixed-length record file we need to use the ‘Outputlist’.
Example
Open strfilename For Output As #1
Print #1, intItemCode, _
Tab (17) ; ItemName; _
Tab (46) ; ItemRate; _
Tab (63) ; Unitofmesr; _
Tab (79) ; QtyonHand;
Print #1, sug003
Tab (17) ; Sugar _
Tab (46) ; 15.78; _
Tab (63) ; KG; _
Tab (79) ; 600; _
Close #1

Here, Underscore( _ ) is used as a line continuation character.

70
Chapter: 7
MENUS
Building the user interface
The first step:
(1) Design the form that the user wants to see on paper. This helps to determine the locations of
various controls
(2) Then write the coding on the paper.
(3) Always design the form such that more importance is given to the grouping of the control.
Example: the employee name must always appear at the left side on the top of the screen.
(4) Commands like print, save must come at the bottom right hand corner.
Overcrowding:
(1) Don’t overcrowd the form. Let there be enough white space or blank space.
(2) Here it means that if the form is full of command buttons, text boxes and labels, then the user
may feel it is more confusing.
(3) At the same time all the controls should not be aligned at the same end, leaving the other end of
the form blank.
(4) Form must have enough empty spaces visible throughout.
Important information must be given Prominence:
(1) Only the important information must be given higher priority. Example: In an invoice program
the customer name and address must be given important than his personal information like his
pets etc. in such case an extra button can be provided such as “More Info”. When a user clicks
this button he can see all the other least important details of the customers.
(2) Always use a Frame control while grouping a set of controls or buttons so that we can easily
judge the relationship between them.
Consistency:
(1) In VB a number of controls can be used to the same job. For example: List box, Combo box
and Text box are used to display a list of names. For a particular task use the same control
throughout.
(2) The control must have the same appearance throughout the application. For example: say if
you use a textbox and set its background color as blue then follow the same color for the entire
text box in that form and application.
The Fonts:
(1) Always remember that a font that is available in your computer may not be available in others.
In that case windows will substitute a font of its own and your font in that case will look
different.
(2) Stick to standard fonts like Times New Roman, System, and Ariel.
Consistency across forms and application:
(1) Forms must also look related. The color of a form and placement of controls on individual
forms must be uniform.
(2) Example: if a save button is placed on the right hand bottom corner of one form then it should
not be placed in the middle on the other form.
Affordances:
71
(1) Buttons on your form must have a three dimension. This means that it has to be pushed.
(2) When a particular control or button should not be made available it must be grayed. It will tell
the user the option is unavailable.
Simplicity:
(1) Make sure the interface you present to user is simple and easy to use. Provide clues wherever it
is needed.
(2) It may seem that the new version has more advantages than the last version but some users may
be comfortable with the last version itself than the latest one.
Usability:
(1) The user must be able to use the application easily. It means that the user is not concerned with
the new version or last version of VB or the power of your coding.
(2) He doesn’t like to learn more new concepts than what he has learnt already. The user is not
concerned with the help and guidance he can get from the application itself. H e must be
provided with the alternate methods.
Images:
(1) Use only those icons and pictures in your program that is universally accepted. What you
understand may not be what the user understands.
(2) Use the status bar to display a message or use balloon help. Example: the icon for save is the
floppy, but if you use a hard drive instead of floppy the user may get confused.
Colors:
(1) Use simple colors. Make sure you use mild and soft colors always.
(2) To draw the attention of the user at times you can use some bright colors.
(3) Don’t have too many colors on your form.
(4) Use a standard 16-color palette.
Interacting with the user:
(1) Remember to give apt messages before an error occurs in advance.
(2) Example: “Bad Command Or File Name” means that the file does not exist or bad file name.
(3) The message box should have proper icons in it. For a warning message use the symbol an
exclamation mark.
All about Menus
(1) All windows product use “Menus and Toolbars”. Menus contain a number of options, logically
organized and easily accessible by the user.
(2) Toolbars and Menus take less memory space.
(3) Don’t provide a button for every activity that the user will want to accomplish. This will resul t
in an overcrowded screen and users may get confused.
(4) VB provides a simple method to create a menu. You can create a menu using Menu Editor.
Standard Menu Bar

File Edit View Format Window Help

72
The Menu System
(1) The menu bar consists of many options. The windows based application follow the standard as
the menu File on the top followed by other options such as Edit, Format etc.
(2) When the user clicks a menu option, a list of options is displayed. Clicking on any item on the
list will generate a click event. You can write a program correspond to that event.
(3) An option on the list can have its own submenu. A menu item can have 4 child menus. There
can be up to 5 menus displayed horizontally, in the form of main menu and 4 child menus. But
this design is considered as bad design.
(4) A menu is tied to a form. You cannot have a menu without a form. Usually the main form has
menus although all the forms can have their own menus.
(5) A menu item can
 Have a check mark to provide an on and off settings.
 Have an arrow on the right side to indicate a child menu.
 Be disabled or enabled depending upon the situation.
 Have keyboard equivalence for easy access.
 Have separator line to logically group menu items.
 Have an ellipse to indicate a dialog box.

Menu Conventions
(1) Keep menu caption short and simple. On the menu bar use one word for title. More than one
word can be confusing.
(2) Always follow windows conventions in naming and ordering the menu items on the menu bar
else confusion will exist.
(3) Keep the list of menu options short. Try to break the lists, which extends below the bottom into
child menus. Remember too many submenus are a bad design.
(4) Use separator to logically group menu options.
(5) Provide keyboard shortcuts wherever possible.

First decide on the Main options and Sub-options for each of the main options. The placement of
sub menus is very important. Each of the Menu items that you create will be treated like controls,
and can be coded to trigger related activities.

The Menu Editor


Start a new project. With the form in focus, click on Tools | Menu Editor. This will display a menu
editor.
The menu editor has the following items.
(1) The Caption Box: what you type here is what the user sees.
(2) The Name Box: the name entered here is the control name for the menu item. You enter the
code for menu item under this control name.
(3) Shortcut Box: you enter the shortcut keys for the menu items here. Click on the down arrow, a
drop down list box will be displayed with all the shortcut keys. Click on the one you want to
use.
73
(4) The Checked Check Box: click on this if you want to display a tick mark to show that a menu
item has been selected. The default is off. This can be turned ON or OFF at run time.
(5) Enabled Check Box: Click on this to make a menu item enabled. If a menu item is enabled, it
will respond to the mouse click. This can be turned ON or OFF at run time.
(6) The Visible Check Box: if it is set to OFF then the menu item and its sub-menus will not be
visible. This can be turned ON or OFF at run time.
(7) The Text Window: this gives a preview of what you have entered. You can also view the
hierarchy of menu and sub menus items.
(8) The left arrow button brings the menu item one level up.
(9) Clicking on the right arrow moves the menu item one level deeper.
(10) The up arrow interchanges the current line with the line above.
(11) The down arrow interchanges the current line with the line above.
(12) Index: Allow you to assign a numeric value that determines the control position within a
control array. This position is not related to the screen position.
(13) HelpContextID: Allow you to assign a unique numeric value for the context ID. This value is
used to find the appropriate Help file in the Help file identified by the Help file property.
(14) NegotiatePosition: Allows you to select the menu’s NegotiatePosition property. This property
determines whether and how the menu appears in a container form.
(15) Next: Moves selection to the next line.
(16) Insert: Inserts a line in the list box above the currently selected line.
(17) Delete: Deletes a currently selected line.
(18) OK: closes the menu Editor and applies all changes to the last form you selected.
(19) Cancel: Closes the Menu Editor and cancels all changes.
Using the Menu Editor
(1) Suppose say if you want to develop a windows application. All windows have similar menus.
The common menu items are
File, Edit, View, Format, Tools, Help
(2) Let us create a menu for a program like Notepad.

Start a project and open a form.


Click on tools.
Choose menu editor.
Remember that if your form is not active, the menu editor options will be disabled.
In the Caption Box, enter &File.
In the Name Box, enter file menu.
The entry in the text window will show ‘&File’.
Click on Next. A new line is created.
In the Caption Box enter &Edit.
In the Name Box enter Edit Menu.
Creating Sub-Menu Items:
Click on &Edit. Click Insert.
A line is inserted between &File and &edit.
74
The insert key always inserts a line above the item that has been selected. In the Caption Box
enter ‘&New’
In the Name Box enter FileMenuNew. This will tell you that the item belongs to the file Menu.
Press the right arrow key. This will make the Menu Item ‘New’ subordinate to the file
menu.

Making the Menu Better


Adding shortcut keys
Select a sub-menu item.
Click on the drop-down list box to list the shortcut keys available.
Select appropriate key combinations.
For example:
Save - Ctrl_S
SaveAs - Ctrl_A
Print - Ctrl_P
Adding separator bars
(1) It is a good idea to group the options in the menus.
(2) Menu options like New, Open, Save, SaveAs are a separate group from the options related to
printing. You can separate them by inserting a separator bar.
(3) Select the Print option in the Text window. Press Insert. This will insert a line above the Print
option.
(4) Enter ‘-‘ in the Caption Box.
(5) Enter ‘FileMenuSep1’ in the Name Box.
(6) This will create a separator bar.

75
Coding the Menu Items
 Each of the Menu items has a name that was assigned when it was created.
 To add the code, bring up the code window of the form.
 The menu items will have only one event, Click event.
 Click on the items list box to see the list of all the menu items available.
 Select the item that must be coded. Enter the code.
Example:
Let us enter a code for the FileOpenMenu item
 Here in this program let us ask the user to select the form of his own choice.
 Click on the option Open under the File Menu.
Private sub MenuFile New_Click()
Load Form1
Form1.Show
End Sub.
Adding a Toolbar
(1) The tool bar must hold relevant icons. Those icons must represent the frequently accessed
functions. Example: An icon with a scissors represents the action ‘Cut’. The icon with a floppy
represents the action ‘Save’.
Toolbar Conventions

(1) Toolbars offers mouse shortcuts for frequently used functions.


(2) Let us create a Toolbar
 You need the Toolbar control. So to add a toolbar do the following,
 Place the mouse on the toolbox and click the right mouse button.
 From the pop-up menu choose the components.
 A window pops up displaying the controls that are available.
 Click on Microsoft Windows Common Controls.
Push Ok button you will see some new controls on the Toolbox.
(3) Now double click on the Toolbar Control. A long flat button appears on the form below the
Menu Bar. Now place the mouse on the Toolbar and click the right mouse button. Select
properties from pop-up menu.

76
(4) Here in the figure there are 3 options.
General: using these options you can set the mouse pointer type, adjust the size of the buttons
and set other parameters.
Buttons: in this option you can insert the buttons, set the control keys for the buttons,
provide the tool tip text, etc. Observe that the Image parameter is grayed.
Add buttons you want. Supply the caption you want, key to access the button. The key you give
here will be used as a reference when you want to send the toolbar events to menu items.
Picture: View the picture of the icon selected.
Pasting Icons on Buttons
(1) Double click on the Image Edit Control on your toolbox.
(2) Bring up the property page of this control by clicking the right mouse button and selecting the
property page from the pop-up menu.

77
This has 3 options.
General: you can specify the size of the images under this option.
Images: insert or add images to the Image list. Click the Insert Image Button. Select the icon
you want. The selected icon will be displayed in the Image list.
Color: you can modify the color, which you like.
(3) Return to the property pages of the Toolbar control. Click on the list box labeled Image. Along
with the entry <None> you will see another entry called ImageList1. Select it.

(4) Select the Buttons option. The textbox labeled ‘Image’ will be available now. It was grayed
earlier. Refer to the icon by the number that was allotted to it when you were adding it to the
Image List. Click OK.

Sending Toolbar events


(1) Say suppose you have a menu item named ‘Save’ under the File Menu. You also have a button
on the Tollbar with the floppy icon that represents ‘Save file’ action.

Private Sub Toobar1_ButtonClick (ByVal Button As ComctLib.Button)


If Button.Key = “Save” then Save_Click
End Sub.

78
Chapter: 8
MULTIPLE DOCUMENT INTERFACE APPLICATIONS
Introduction

With the help of a Menu Editor and the Toolbar, we can build an application containing a Menu
system like Windows.
(1) The problem arises only when a user likes to display more than one document at one time.
So to display as many documents as the user wants, your application will have to replicate
itself as many times. So if this is possible then the number of controls and code that would
have to be loaded in the memory will also be high.
(2) So to solve the above problem, the more practical and efficient way is to use a Multiple
Document Interface.
(3) The MDI was mainly designed to show more than one document at the same time.
(4) An MDI application allows the user to display multiple documents at the same time, with
each document displayed in its own window.
(5) Documents or child windows are contained in the parent window, which provides
workspace for the entire child window in the application.
(6) Each document is a workspace. A form is a workspace too.

Why MDI forms?


(1) An MDI form acts like a container for other forms in the application. So, this facility helps
the users to minimize a form, close a form. The user need not close all the individual forms.
(2) Most of the control buttons and code for the various forms can be shared. Many of the
functions like adding, displaying, sorting records are commonly used by most of the form.
(3) Reduce the number of controls. Common controls can be available with the MDI form and
shared by other forms.
(4) All activities like day-end operations and updating of records can be handled from the MDI
form.
(5) MDI forms helps to reduce the amount of code and the number of controls in the
application.
(6) An MDI application consists of
 One MDI parent form.
 One or more MDI child forms.
 Optionally independent forms and modules.
Creating a simple MDI application
 Start a new Standard. Exe project.
 Click on projects.
 From the drop-down menu, click on ‘Add MDI Form’
 A form with a darker color will be displayed. This is the MDI form.

79
Features of an MDI form
(1) An application can have only one MDI form. Suppose if you have an MDI form in your
application and if you want to add a new MDI form, this option in the Project menu will be
unavailable.
(2) It can contain only those controls that have ‘Align’ property or those controls that are not
visible during run time. Some controls are Toolbar, Picture box, and Data control. The
Align property here is related to the alignment of the control on the form.

(3) To place other controls on an MDI form, draw a Picture box on the form, and then draw the
controls inside the picture box. You can use Print method to display text in a Picture box on
an MDI form, but not to display on the MDI Form itself.
(4) An MDI form object can’t be modal.
(5) The menu for child form will be displayed as the menu on the MDI form when the Child
form has the focus.
(6) You can access the controls on the MDI form using the control collection. To hide all the
controls,
For Each Control in MDIForm1.Controls
Control. Visible=False
Next Control
(7) The default AutoShowChildren property displays the child forms automatically when they
are loaded.
(8) The default ScrollBars property will display the scroll bars when the child forms extend
beyond the boundaries of the parent form.
(9) The count property of the MDI form tells you the number of controls in the controls
collection.

Child form
To create an MDI Child form, select Form1 and set its MDI child property TRUE.
(1) A child form cannot be moved outside the Parent form’s boundaries.
(2) Activating a child form will result in the activation of the parent form.
(3) When a child form is minimized, its icon will appear at the bottom of the workspace of the
parent form.
(4) When a child form is maximized, it fills the entire area of the parent form, and its menu will
become the menu of the parent form.

80
(5) There can be more than one child form in an application.
(6) The icons for MDI parent, child and a standard form are different.

Let us now create the simple MDI application.


Step 1
 On the child form add a Textbox control.
 Create a menu bar and add the menu items File and Exit.
 Run the application.
 The menu bar created for the child form has become the menu bar for the parent form.
 Click the minimize button on the child form. Now the child form has a Textbox on it.
The minimized icon does not appear on the taskbar but at the bottom of the parent Form.
Step 2
 To create multiple instances of the child form.
 Under the menu item ‘File’ add an option ‘New’
 Double click on the option ‘New’. It will display the code window of the
‘Newfile_Click’ event.

Add this code. It consists of only two lines.


Private Sub Newfile_Click()
Dim Newform As New Form1
Newform.Show
End Sub
 Here in the above coding, it creates a variable of object type ‘Newform’ with all the
properties of the object Form1.
 Run the application.
 Click File | New
 You will see another copy of the form Form1. Click again to see another copy.
 To close all the child forms of Form1, click on the Close button to the parent form.
 All the forms will close.
Loading MDI forms and Child Forms
(1) When you load a child form its parent form is automatically loaded and displayed. But
when you load the MDI form, its children are not automatically loaded.
(2) Set the AutoShowChildren property as False, to make MDI child window hidden.
(3) Users of MDI application may open, save, and close several child forms in one session.

81
(4) To control the program, always refer to the active form and maintain the information on the
child form.

The ActiveForm Property


This property returns the form that is the active window in the application. Example: if a child form has
focus then it returns the name of that form.
Syntax:
Object. ActiveForm
Step 3
In the click event of the MDI form add this code.
ActiveForm.Text1.Text = “this is to test if we have got it right”
Now run the application. Click any number of instances of the Child form and then click on the MDI
form. The string, which you have typed in the MDI click event, will be displayed in the Active form.

Changing the Caption of the New Forms


All the new forms created, will have their Captions remain the same. So let us make some changes to
the project, so that the new forms will have a different caption.
Step 4
Delete the menu bar from the child form. Add only File and Exit items to the menu bar. Under
the ‘File’ item add the following code.

Private Sub mdinewopen_Click ()


Dim NewForm As New Form1
I=I+1
Me.Caption = “form name” & I
Newform.Caption = “form name” & I
Newform.Show
End Sub
The main purpose of using the keyword Me is that no form should be referred to by its name. In case if
any work is to be done then, do it on the ActiveForm.
Listing Open Forms
To list all the forms that are open,
Step 5
Add a menu item Windows to your MDI form.
Check the box ‘WindowList’
Run the application. After creating a few form, click on the Windows menu item. It will pop-up a list of
all the forms that are open on the MDI parent form. The form that is currently active will have a tick
mark against it.

82
Setting Child Form Size and Position
Step 6
The size and the position of the Child form will be different from its size at the design time. To
determine the size and location of the child form, add the following code to Form_Load event
Private Sub Form_Load ()
Me.Height = 3000
Me.Width = 4000
Me,Top = (MDIForm1.ScaleHeight – Me.Height) / 2
Me.Left = (MDIForm1.ScaleWidth – Me.Width) / 2
End Sub
Here, me refers to the current active form on the screen
Run the application. Create new forms. All the instances of the new form will be displayed in the same
place.

Step 7
Open the menu editor again. To the menu item, Window, add a sub-option. Call it Arrange. In the click
event of the Arrange menu item, add the following line
Private Sub arrangemethod_Click()
MDIForm1.Arrange vbCascade
End Sub
Now run the above application. You will be able to cascade the windows. The MDI Forms ‘Arrange’
method has four options. They are
VbCascade : Arrange open forms such that the title bars of forms behind the current forms
are visible.
VbVertical : open forms are displayed vertically.
VbHorizontal : opened forms are displayed horizontally.
Saving your work
The user has to save the changes made to the MDI form.
Specifying the Active Form or Control
(1) If you are writing code that will be called by multiple instances of a form, it’s a good idea to
use the identifier when accessing the form’s control or properties.
Example: we refer to the height of the text box on Form1 as Text1.Height, instead of
Form1.Text1.Height. This way code will always affect the current form.
(2) Another way to specify the current form in code is to use the Me keyword. Use Me to
reference the form whose code is currently running.
Maintaining state information for a Child form
(1) As said earlier if you are developing a ‘Notepad’ application then you need to keep track of
the changes made to the text. He must save the work before he closes his application.
(2) To determine if the user has made changes to the text, declare a public variable. Let it be a
Boolean variable. If any change is made, it must be set to true. When the work is saved, it
must be set to false.
For each child form declare a public variable.
83
Declare a variable in the declaration section of the child form.
Public Textchanged As Boolean
Private Sub Text1_Change ()
Textchanged = True
End Sub
Unloading MDI forms with Query Unload
(1) The Textchanged flag becomes useful when the user decides to exit the application.
(2) This can occur when the user closes an MDI through a menu Item, provide an exit on the
File menu.
(3) When an MDI is unloaded, the query Unload event is invoked first for the MDI form and
every child form that is open.
(4) Give the user the opportunity to save a form before unloading it, because the QueryUnload
event is invoked first before a form is unloaded.. here is a code which uses thr Textchanged
flag to determine if the user should be prompted to save the child before it is invoked.
Private Sub Exitmnu_Click()
Unload FrmMDIend
End Sub
Private Sub Form_QueryUnload(Cancel As Integer, UnloadMode As Integer)
If Textchanged Then
SaveFile
End if
End Sub
Chapter: 9

DEBUGGING TIPS
Introduction
(1) Debugging is an important part of the software development.
(2) Let us see how to avoid bugs, handle bugs that could not be trapped, and how to trap
and correct the bugs that has occurred.
What is a Bug?
(1) A problem that occurs in a system is called as a Bug.
(2) A program cannot run successfully with an error in it.
(3) Any piece of code that does not allow the program to work, as it should, is a bug.
(4) The process of finding out and removing the error is called Debugging.
(5) So the programmer has to carry out the debugging process before distributing the
software to the end-users.
When do you have to Debug?
(1) When you application does not produce correct results.
(2) When your application halts unexpectedly.
(3) When you application go into an infinite loop.
84
Types of Bugs (errors)
The errors can be classified into 3 categories. They are
(1) Errors of Syntax.
(2) Logical Errors.
(3) Runtime Errors.
The first 2 types of errors are to be controlled by the users. But the 3rd type of error is
totally not under our control.
Errors of Syntax and How they can be Avoided
(1) These errors are caused by poor grammar. Example: “ Dim I Integer”. The moment
you type the enter button, a message box will pop-up and tell you that you made a
mistake.
(2) An option has been enabled that will check for syntax errors as one statement is
completed.
 Click on the Tools and choose Options from the menu.
 Under the ‘Editor’ tab you will find the following items checked.
 They are code settings and window settings.
Code settings
1. Auto Syntax check
2. Require variable declaration
3. Auto list members
4. Auto quick info
5. Auto data tips.
Window settings
1. Drag-and-Drop Text Editing
2. Default to Full Module View
3. Procedure Separator

85
Auto Syntax Check
This option will check for syntax errors as we enter the commands and statement.

Require variable declaration


This option requires declaring a variable before using it.
Consider this code
Dim I as Integer
Marks = Marks1 + Marks
Debug. Print Marks
The Auto Syntax check option will not trap this error.
Auto list members
This option will show a drop-down list box, listing all the members of a control.
When we enter the “Dim I as” a drop-down list box appears with all possible
options. This reduces the time taken to type and minimize the chances of spelling
errors.
Auto quick info
This option will provide the complete syntax for the function that is intended to
write. It is context sensitive and it is not necessary to remember the syntax for
every function.
Auto data tips
This option helps to minimize the syntax errors.
How can Errors be Avoided?
There are few principles used for avoiding these errors. But always remember that the
cost of maintenance
 Plan your program. Make sure you know where your program should begin,
the path it should take and where it should end. Draw data flow diagrams,
flow charts such that logic is clear. Then begin to write code.
 Use of standard naming convention. Always stick to the standard naming
convention as because other programmers may not know of your naming
convention.
 The names used for the controls, variables must be meaningful. Example a
variable name prescribed as ‘drug_prescribed’ makes more sense than
‘d_pres’.
 Declare the variables at the beginning. While declaring the variables declare
them in a separate line. Group the variables such that looking will be easy.
 Comment your code. Wherever needed add comments. Because the logic and
the approach used today may not be clear after 2 or 3 months. And also that

86
your coding is to be maintained by another programmer who may not think
like you.
Runtime and Logical Errors
(1) A run-time error results when a statement attempts an invalid operation.
(2) Logical errors occur when there is an error in the program logic. Example: ‘Divide
by Zero’, ‘Overflow Error’, ‘And Null Error’.
(3) Logical errors have to be trapped by carefully going through the programmer and by
supplying data of any type. So it is up to the programmer to enter the correct data. If
needed he should also add an error handling routine.
(4) Runtime errors are caused by hardware faults. Example: the user may have renamed
the database file or he may run the application from different directory. In both the
cases the application will come to halt after displaying a message.
The Debugging Methods
VB provides a number of methods for checking the bugs. The tools and methods
include setting watches, setting breakpoints, stepping through code using the
local window, the immediate window, and the stack.
The Message Box
The programmers use the message box to display a message that the others can
understand well.
Example code:
Private sub Command1_Click ()
Dim I as Integer
For I = 1 To 20 Step 4
Msgbox I
‘ Other statements……
Next I
End Sub
The above coding will help the programmers about the value of the variable I. By
this the programmer might know what to do.
Debug.print
The other method is to use the debug object. The debug object will send the output to the
immediate window.
Code:
Private sub command1_click ()
Dim I as Integer
For I = 1 to 20 Step 4
Debug.print I
Next I
End Sub

87
The value assigned to the variable I will be displayed in the ‘immediate window’
The Debug Toolbar
(1) In order to begin debugging you need the ‘Debug Toolbar’.
(2) The options on the debug toolbar are available as sub-options of the debug Menu
item.
(3) It is better to have the debug tool bar on the top.
(4) To bring up the debug toolbar, right click the tool-bar and select Debug from the
pop-up menu.

The debug toolbar has the following buttons:


Group 1
Start
Break
End
Group 2
Toggle Breakpoints
Step Into
Step Over
Step Out
Group 3
Locals Window
Immediate Window
Watch Window
Quick Watch
Call Stack
The Start Button
You start the program by clicking this button. It is just like pressing F5 button and
choosing Run option.
The Break Button
It pauses the program. It is like pressing the Ctrl + Break key.

88
The End Button
Halts the program.
The Breakpoint
Debugging is a process of removing the errors.
The first step is to isolate the problem. You can look at each modules or procedure in
your application where you feel the bug is being generated. On specifying the point where you
want to halt, you can set the ‘Breakpoint’. Click on the gray margin area on the left side of your
code window in line with the statement where you want to pause the execution. A brown dot
will appear in the margin. Now run the program. The program will pause before it reaches the
statement that has been marked as the Breakpoint. Now you can use the next set of buttons on
the Debug toolbar.

Toggle Breakpoints
It is possible to have more than one breakpoint. Click on this button to shift the
breakpoints.

Step Into
Now the program has paused where you want it. You can step in through the code line
by line. Click on Step Into icon to execute one line of code. Place the mouse pointer on the
variables that you are watching.

Step Over
The procedure you are watching may branch to another procedure. Click on the Step
Over icon. The called procedure will be executed, and the control will be returned to next line
in the current procedure.

Step Out
On clicking the Step Out icon control will be transferred to the line after the current
procedure or function.
The next set of buttons deals with the following windows.
 Locals window
 Immediate window.
 Watch window
 Quick watch
 Call stack

The Locals Window


Click on the Locals Window icon. This window will display all the variables that are
declared in the current procedure. You can watch the variables that are used in the current
procedure.

89
The Quick Watch Window
Right click on a variable whose value you want to watch. From the pop-up menu select
‘Add watch’. Enter the name of the variable for confirmation. Now run the application after
setting a breakpoint. Observe the value of the variable change as you step through the code.
You will be able to note when a variable assumes a certain value and take appropriate action.
The Immediate Window
This is the window to which the ‘Debug.print’ sends the output. We have used this
window before. In this window you can directly execute a statement as if you are directly
communicating with the interpreter. You can also check the values of the variables if you have
not used the Debug.print to send the output here. In the Immediate window enter
? Int I
To get the current value of the variable Int I

The watch window


In this window all the variables used in the application till the breakpoint are displayed.
The Watch window also displays the name of the procedure where the variables are used and
the value that variable assumes.

Error Handling
It is the responsibility of the software developer to expect the unexpected and include error-
handling routines.
What is an Error Handler?
(1) It is a routine that traps errors and directs the user or the program to perform a certain
task to overcome the error.

90
(2) It is the duty of the developer to control the errors that occur during the runtime and
to display them to the users.
(3) We have to display the messages that are easily understood such that the user takes
necessary steps to fix the problem.
The err object
(1) VBA engine handles all the error that occurs in VB.
(2) Whenever an error occurs, VBA activates the err object.
(3) The err object has the following methods and properties.
The Methods are
The Clear Method: the err.clear clears the properties of the error object.
The Raise Method: Helps raise a user-defined error.
The properties are
Description Property: this returns a description associated with the error.
HelpContext property: Returns a string containing the context ID for a topic in a Help
file.
HelpFile property: returns the full filename of the HellFile when the user presses the
F1 key.
Number property: this is the default property of the err object. It returns a number.
Source property: returns the name of the procedure or the project when the error
occurred.
LastDLLError property: returns the name of the called DLL. It also returns a code to
indicate whether the called DLL was a success or failure.

Look at the flowchart:

IS
HANDLER
ERROR

STMT

91
An error ‘trapper’ should be introduced in the procedure where you suspect the error
would occur. Once an error occurs, the program flow must be directed to another part of
the procedure where the error will be resolved.
In the error handler the error will be resolved by popping up a message box to the
user and initiating the action.
Let us have a look at the file opening routine.
Private Sub FileOpen_Click ()
Dim filelength As Long
Dim filename As String
Dim databuffer As String
Dim filenum As Integer
Filename = “C:\aazam.txt”
Filenum = freefile ()
Open Filename For Input As #Filenum
Msgbox Filelength
Databuffer = Input ( filelength, #Filenum)
Text1.Text = databuffer
Close #filenum
End Sub
For the above procedure we have to add an error handler routine.
Step 1
First we must trap the error. Add the statement to the code
On error go to err_FileOpen_Click
This will stop VB from popping up its message box.
Step 2
We have redirected the error to ‘err_FileOpen_Click’. The label is
‘err_FileOpen_Click’. The label must be within the procedure. Change the code like this.
Private Sub FileOpen_Click ()
Dim filelength As Long
Dim filename As String
Dim databuffer As String
Dim filenum As Integer
On Error GoTo err_fileopen_click
Filename = “C:\aazam.txt”
Filenum = freefile ()
Open Filename For Input As #Filenum
Msgbox Filelength
Databuffer = Input ( filelength, #Filenum)

92
Text1.Text = databuffer
Close #filenum
err_fileopen_click:
Dim Message, Title
Message = “ enter a valid file name or press enter to quit”
Title = “error Demo”
Filename = InputBox(Message, Title)
If Filename <> “” Then
Resume
Else
Resume exit_fileopen_click
End if
Exit_fileopen_click:
End Sub

Writing a Standard Error Handler:


It is a good practice to include an error handler in our program The following are the
Visual Basic Constants for error handling.
Option Explicit
Const ErrDeviceUnavailable=68
Const ErrDiskNotREady=71
Const ErrDiskFull=61
Const ErrBadFileName=64
Const ErrBadFileNameOrNumber=52
Const ErrPathDoesNotExist=76
Const ErrFileAlreadyOpen=55
Const ErrInputPastEndOfFile=62
Const ErrReturnWithoutGoSub=3
Const ErrCantperformrequestoperation=17

The idea is to trap the errors and display the error messages that are more meaningful and allow
the user to decide the next move.

93
CHAPTER 10

The Common Dialog Control


Introduction:
The MsgBox function was pretty good for what it was supposed to do, but the InputBox had
something lacking. Imagine using the InpuBox to specify the filename like “C:\Visual Studio\Program
Files \SISI\Datatrypro\file1.txt” goes against our idea of a good interface.
After all a good interface should reduce the number of keystrokes that a user has to enter.
Ideally the user must be able to select the filename from a list of files. At the same time, the interface
provided by us should not be different from the interface provided by other applic ations for such an
activity.
In order to provide standardization in the interface for all windows compliant applications,
Visual Basic has the Common Dialog Control. It allows to deploy the dialog boxes that it provides with
all its applications. The Common Dialog Control used to display the following dialog boxes.
 Open a File
 Save a File
 Set a Color
 Set a Font
 Print a Document
Moreover it does not need any great programming. Simply add the control to the form and call
the method or function that is needed. The Common Dialog Control can display the following dialogs,
using the specified methods.
Method Dialog Displayed
ShowOpen Show Open Dialog Box
ShowSave Show Save As Dialog Box
ShowColor Show Color Dialog Box
ShowFont Show Font Dialog Box
ShowPrinter Show Print or Print Options Dialog Box
Show Help Invokes the Windows Help Engine

Working with the CommonDialog Control:


Add the CommonDialog Control to the toolbox by Right clicking on the toolbox and selecting
‘Components’ from the pop-up menu.
Next select ‘Microsoft Common Dialog Control 6.0’ from the list of components and it will see in the
Toolbox and place it in the Form.
This control does not have an interface that the user will see and work on. During run time it is not
visible. However its method can be invoked during runtime.
Right click on the Common Dialog control and select properties from the pop-up menu. We set the
properties for each of this method by select the control and press F4.

94
Select the control and right click it. In the pop-up menu select the properties. It will display the
following property page.

Example:
Start a new project. Give it an appropriate name. Add the common Dialog control.
In the Form place one text box and five command buttons. The form look like this.

95
The File Open Dialog Box:
To allow the user to open a file and display its contents in the textbox, the ShowOpen method is
used. Add the following code in the Open command button.
CommonDialog1.ShowOpen
Run the program and click the open command button, the following File Open Dialog box is opened.

To get it fully functional there are few more things to do. They are
1. Have to specify the title for this dialog box.
2. If the user does not select a file and clicks on cancel, we must be able to take appropriate action.
3. Having got a handle on the file, we need to open it, read the contents and display the same in the
textbox.
There are two ways to set the title to the dialog box.
 By setting the title at design time.

96
 By setting the title at runtime through code.
Add the following line to the code for the open Command Button.
CommonDialog1.DialogTitle = “Select the File to Open”
CommonDialog1.ShowOpen
If the user clicks the Cancel button, Visual Basic returns an empty string for the filename. This
will cause an error when we try to open such a file. There is a simple method to tackle this. Use ‘On
Error GoTo’ statement and add the necessary statements to exit the procedure without any fuss. The
modified code will look like this.
On Error GoTo ClickedCancel
CommonDialog1.DialogTitle = “Select the file to Open”
CommonDialog1.ShowOpen
ClickedCancel:
Exit Sub
Now to open the file and display its contents, recall the method used to open a file, read and display its
contents in the file processing methods.
Dim FileLen As Integer
Dim sbuffer As String
Dim Filenum As Integer
On Error GoTo Cancel
CommonDialog1.DialogTitle = “Select the File to open”
CommonDialog1.ShowOpen
Filenum = FreeFile ()

Open CommonDialog1.FileName For Input As #Filenum


FileLen = LOF (Filenum)
Sbuffer = Input (FileLen, Filenum)
Text1.Text = sbuffer
Close #Filenum
Cancel:
Exit Sub

Saving File:

The user can open a file of his choice and display its contents. However, the user may also want
to create a new file, add some text and save it in a directory of his choice.
In this case we have to show the File Save Dialog Box. The user can use the ShowSave method
to allow the user to enter the name of the file in which the text entered in the text box has to be saved.
In the ‘Save’ Command Button add the following code.
Dim Filenum As Integer
Dim FileLen As Integer
Dim sbuffer As String
CommonDialog1.DialogTitle = “Enter the name of the file to save”
97
CommonDialog1.Showsave
Filenum = FreeFile()
Open CommonDialog1.FileName For Output As #Filenum
Sbuffer = Text1.Text
Write #Filenum, sbuffer
Close #Filenum
Cancel:
Exit Sub

Changing the Color:

The CommonDialog Control also provides the means to change the color of the text or other
controls on the form. To display the color dialog box the Showcolor method. In the color command
button write the following code.
CommonDialog1.ShowColor
Run the program and click on the ‘Color’ command button. This will display the color Palette. We can
choose the required color. In order to change the color of the text in the text box, we must assign the
color by the user from the Palette to the text in the textbox.
The code will look like this.
CommonDialog1.ShoeColor
Text1.ForeColor = CommonDialog1.Color

Printing a Document:
The Printer dialog box is a great help while building applications for clients or for the other user
departments. It will work on any printer like Laser Printer, Dot Matrix or Line Printer. If the user has
managed to install it then it will work with our applications. In the Print Command Button write the
following code.
CommonDialog1.ShowPrinter
This line will display the Printer Dialog box. There are number of options that we can set so that
the application prints without hiccups. Through the property pages of the CommonDialog control, we
can set options like the number of copies, pages from and pages to, Landscape or Portrait orientation.
These properties can set through the code as well.
In order to print the text entered in the textbox a certain number of times, we can write the code
as follows.
Dim numcopies As Integer
Dim I As Integer
Dim sbuffer As String
CommonDialog1.ShowPrinter
Numcopies = CommonDialog1.Copies
Sbuffer = Text1.Text
98
For I = 1 To numcopies
Printer.Print sbuffer
Next I Printer.EndDoc
CommonDialog1.Min = 0 ‘ to set the minimum number of pages that can be printed.
CommonDialog1.Max = 20 ‘to set the maximum number of pages that can be printed.
CommonDialog1.Orientation = cdlPortrait

RichTextBox Control:
The CommonDialog control made the development of application easier. We were able to
create a new file or open an existing file, add text to it, save the changes and print the contents of the
file as well. We could also make changes to the font size, the color of the text, etc.
However there was one problem that we faced. We could not selectively change the font size,
color or indention. This is necessary when creating our own word processor. Besides we may want to
add pictures to our text file, or even a spreadsheet, just to add some punch to our text. In order to allow
the user to do all this, the conventional textbox would not fit the bill.
The conventional text box will hold only plain text. Microsoft provides one such control
called Rich Text Box Control. It allows the user to enter and edit text with more advanced formatting
features than the conventional TextBox control.
The Rich Text Box control provides a number of properties we can use to apply formatting to a
selected portion of text within the control. Select the portion of the text to be formatted and apply the
necessary changes. We can make text bold or italic, change the color, and create superscripts and
subscripts. We can also adjust paragraph formatting by setting both left and right indents, a well as
hanging indents.

Working with Rich Text Box Control:


 Rich Txt Box is not a part of the Toolbox. To add the control,
 Select the Project/Components menu item.
 Select the controls tab in the Components box.
 Double click on the Microsoft Rich Textbox control item from the list of components. Close the
components box.

 A new component will appear on the toolbox as


 Draw the following controls on the form one rich text box control, six command button
controls.

99
Changing the Font of the Selected Text:

In the case of the Rich Text Box, formatting changes have to be applied to the text after
selecting it. In order to change the font of a portion or all the text in the rich textbox, select the text and
call the font dialog box. Select the font type and click OK. The codes for this are very simple and look
like this.

Private Sub cmdfont_Click ()


CommonDialog1.ShowFont
RichTextBox1.SelFontName = CommonDialog1.FontName
End Sub

Changing the Color of the Selected Text:


To change the color of the selected text or all the text in the rich text box, the procedure is
similar to that for font.
Private Sub cmdColor_Click ()
CommonDialog1.ShowColor
RichTextBox1.SelColor = CommonDialog1.Color
End Sub
 The Rich Text Box also allows indenting the text. We can have a left indent, a right indent or a
hanging indent.
 SelIndent (default is the left indent) specifies the distance between the left edge of the Rich
Text Box control and the left edge of the text is selected or added.

 SelRightIndent specifies the distance between the right edge of the RichTextBox control and
the right edge of the text that is selected or added.

100
 Hanging indent is the extra indent given to a line or lines in a paragraph over and above the
indent given for the first line of the same paragraph.
 The SelHangingIndent specifies the distance between the left edge of the forst line of text in
the selected paragraph, and the left edge of subsequent lines of text in the same paragraph.

Changing the Indent:


In order to change the left indent of the selected text we need to provide the amount of indent
required either at design time. The amount of indent has to be given as an integer.
The Rich Text Box allows we to add .bmps, .gif and other pictures as part of the document. We
can even introduce hyperlinks to create help files and so on. It allows to directly read data from a file
and to save the data entered as on .rtf file. An .rtf file can be read by MS Word.

---------------------------------------------------------------------------------------------------------------------------

CHAPTER – 11

INTRODUCTION TO DATABASES

DATABASES:
A Database is a collection of records that can be manipulated with ease. All databases can be
manipulated using SQL, a simple English like language that user can quickly learn and use.
Example:
We have to maintain details of payment due from all our customers. Therefore we have a file
with details like Customer_Name, Address, Area_Code, Amount_Last_Paid, Last_Payment_Date and
Amount_Due. There is a demand to know the payment due for Area-A. Therefore we create another
file with the above details for all customers of Area-A.
Next, we receive payment from some of our customers. Of these, some belong to Area-A while
the others are form other areas. Now we have to update both the files and send a fresh set of reports too.
If some of the check bounce then we will have to work all over the again.
If the Data were stored on a Database, the job would become much easier. Any report based on
the data can be generated with ease. For example, a statement like “SELECT * FROM Customer
WHERE AREA_CODE =’A’ will display all customers belong to Area-A. We can specify the criteria
for selection, and all records meeting those criteria will be selected and displayed. Besides, changes that
we want to make to the data can be made in one place. This ensures data integrity and reduces work and
associated problems.
The tools available for manipulation of databases are many. Apart from the usual reasons of
data consistency and reduced data redundancy and so on there is another major advantage in using
databases. That is data independence.
Let us consider data stored in flat files. If the data is stored in sequential form, then the program
must take this into account.

101
If the data is stored using the indexed sequential format then the programmer must know the
name of the index and use the same in his program. If due to some reason the index is modified then the
program must be modified to accommodate the new index.
The program will have to be modified to accommodate physical storage of the data. This means
that there is no data independence.
Example:
One user may want to view the data in the decimal format while another user may not see such
a format. This means that two formats of data need to be stored. Using a database is an answer to these
problems.
In the following figure, the different users can have different views of the same data. The User1
from the Accounts Department will be interested only in the amount that has to be paid to the supplier.
Whereas the User2 from the stores department will be interested only in the parts supplied by the
supplier. However both the users will be tapping in to the supplier data. With such an approach we can
have many more views of the same data.
The conceptual view will map into a physical view of the database. The physical view of the
database will map into the way the data is actually stored. This method of separating the physical
storage from the user view will permit data independence. The views of all the users will be used to
develop the conceptual view of the data and any change in the user’s view will be accommodated by
the conceptual view.
Therefore physical storage for the data will be not being affected. Similarly if the physical
storage of the data is changed, it will not cause a change in the way the user views his data. The
database acts as a buffer.

102
Therefore the database is a set of integrated data that can support the requirements of more than
one user. Further the data is stored with minimum redundancy and must be accessible with ease and
must provide for data independence.

DataBase:
A database can be defined as a collection of records stored in tables. It has a set of rules and
tools to manage these records. There are different types of databases, each with its own format.
The most commonly used database types are
 Relational Model
 Network Model
 Hierarchical Model
103
Codd and date conceived the Relational Database model in the 1970s. in a relational model the data is
stored in multiple tables with some ‘relationship’ between the tables in order to reduce data
redundancy.
The relational model of a database is the most commonly used model today, and has the data
stored in tables in a ‘row-column’ arrangement. Each table has a relationship with one or more tables.
The relational model helps reduce redundancy of data and helps maintain data integrity. Each data can
be identified by its (Row-Column) position.

Tables:
A table is a basic repository in which data is stored, and has a specific structure for storing data.
It is made up of one or more than one column. The data is stored in the form of Rows and Columns.
A table may often hold information about one topic. It is considered good practice to keep only
related data in a table.
Example: We can have Customer_Details table, Item_Details table, Invoice_Details etc. A
Customer_Details table may look like this
Sl.no. Customer_Name Area_Code Amount_Due
001 M&N Networks S021 340,460.00
002 Zeba Hardwares S021 9190.00
003 Real Softwares N102 140,553.00
This table has three records (rows) and four fields (columns).
Rows:
A record is one row in a table. The row will span across all the columns of the table, and each
row has one full set of information about one ‘subject’. Every a time a record is added a row is added.

Columns:
Each row ha one or more columns. Every time an attribute of a record is added a column will be
added. An attribute is referred to as a Field, and the Column type will be decided based on the type of
data to be stored. One can set the data type, size, etc of a column. The data types possible are Text,
Date, Integer, Boolean, Memo, Object, etc. Each line is a record, while each column is a field.

The Usage of Relational Databases:


We have to maintain the following details of the Supplier: Name, Address, Items Supplied,
Invoice No, and Amount Due. If you put these details in a flat file or an Excel table, it will look like
this.
R.R Hardware, 12 II Cross St Adyar,- Chennai Tamil Nadu, Mouse, 1,500.
Ashok Systems, 105 Xavier St, Ashok Nagar-Chennai Tamil Nadu, Keyboard, 2,1500
Zeba Enterprises, 139 T.H Road, Triplicane –chennai Tamil Nadu, Wipro PC, 3,35500

104
Name Address Items In- Amount_Due
Supplied No
R.R Hardware 12 II Cross St Adyar,- Chennai Mouse 1 500.
Tamil Nadu
* Ashok Systems 105 Xavier St, Ashok Nagar- Keyboard 2 1500
Chennai Tamil Nadu
Zeba Enterprises 139 T.H Road, Triplicane – Wipro PC 3 35500
chennai Tamil Nadu

Observe that for each item supplied by a supplier, we have to repeat all the details of the supplier like
his name, address, etc. if a supplier supplies 50 items, then we have to repeat his details 50 times. On
the other hand, if we have a file for items details, we have to repeat the item details like Price, Code,
Description etc., for every supplier supplying that item. This redundancy can be avoided if we create
tables in the following form.

Supplier Table Supplier_Item Table Item Table


Supplier Code Supplier Code Item Code
Supplier Name Item Code Item Name
Address Description
Price

The Supplier Table has a relationship with the Supplier_Item Table through the Supplier Code. The
Item Table has a relationship with the Supplier_Item Table through the Item_Code. The relationship
figure is look like the following figure.

Description

Therefore by spreading the data across related tables, one can reduce the data redundancy.
Besides any changes that we want to make to the supplier’s Address for example can be made in one
place and the same change will be reflected wherever the supplier Address is used.

105
The Primary Key:
A Primary key is a unique field or a combination of more than one field that identifies a record.
In the above example, the Supplier Code is a Primary key, since no two records have the same serial
number. The Supplier Code can be the unique field that identifies the Supplier in the Supplier table.

Some credit card companies build a Primary Key using a combination of name and date of birth of the
cardholder.
A relationship between tables is built using Primary keys and or Foreign keys. A Foreign Key
is a column in a Secondary table that refers to a column in a primary table. In our example the supplier
code in the supplier_Item table is Foreign key.
Index:
The reason for storing data in databases is that access to data can be very easy. When data is
entered in the database, it is stored in the order in which it is entered. To locate a customer from a list of
about 2000 customers by scanning the list is very tedious, unless we sort the list in some order.
We can sort the customer based on Area, Name, Code or a combination of one or more fields.
This method of sorting the details in a table is called Indexing. An Index is a list that contains the key
field of the record and a pointer to his physical location in the database. Therefore the database engine
can locate a record quickly.

Selecting Database:
The Jet Database Engine is better to use. It is an application independent engine that is used by
all the Microsoft products like Excel, Word, Access, etc. it is the native database engine that comes
with Visual Basic, and is the natural choice for us to experiment with.

Creating a Table:
We can create our own tables by,
 Using DAO (Data Access Objects)
 Using Microsoft Access
 Using Visual Data Manager that comes with Visual Basic
The table can be created with the help of Visual Data Manager. It makes the job of table
creation and modification very simple. It can work with Access, dBase, Paradox and text files as well.

Working with Visual Data Manager:


 The Visual Data Manager option is available under the Add Ins Menu.

 Click on the Visual Data Manager.

106
 The Menu items available are File, Utility, Window, Help and the NINE Buttons.
 From the File Menu select the option New.

 From the pop-up menu select Access and then select Version 7.0 MDB.
 Choose Access 2.0 if the application is going to work on Window 3.X Access .
 Access 7.0 is for the 32-bit platform only.
 Visual Basic will now present with a save Dialog Box. Enter the name of the file for the
database.

 Now Visual Basic will display two windows, the Database window and the SQL statement
window.
 The Database windows will have an item Properties click on the box with + to see the properties
that have been set or available for this database.

107
Creating a Table:
 Right click the mouse in the database window.
 From the pop-up menu select New tables.
 This will result in another window being displayed with a number of text boxes, checkboxes
etc.
 Enter the name of the table that we want to create.

Note:
 Before to begin the application, decide on the fields that each table will hold.
 Decide on the properties for each of the fields.
 After entering the Table Name, click on the AddField button.
 The AddField Dialog Box will look like this.

108
 Name: Enter the name of the field that we want to add.
 Ordinal Position: Enter the relative position of the field.
 Type: Enter the type of data for this field. Example: Integer, Text, Long etc.
 Validation Text: Message to be displayed in case the user enters invalid data for that field.
 Size: Enter the size of the field.
 Fixed Length: If selected, creates a field with a fixed size.
 Variable Length: Allows the user to modify the size of the field by dragging its borders.
 Validation Rule: Lets you determine what data is valid in a field as it is added.
 Default Value: Enter the default value for the field.
 AutoIncrField: Automatically adds the next field if we are at the end of the table.
 AllowZeroLength: Allows we to have a zero-length string as a valid setting.
 Required: if the checkbox for this is clicked, it means that the table will not be updated if the
field is a Null string. Example: Employee number cannot be null string.
 Add: Appends the current Field definition to the current table.
 Close: Closes the form when we have finished adding fields.

Example:
In order to create a simple table like Employee with three fields such as
EmpNo, EmpName, EmpSalary
The steps to be followed are
 Click on the AddFields Button. In the text box for Name, enter Empno.

109
 Select the Type. From the drop-down list box, select Integer.
 Notice that length is fixed as 2. some of the other options are made unavailable.
 Click on Required. This means that the EmpNo cannot hold Null value.
 Now click on OK. The next two fields are added as the same way.
 Now click on the Build table Button.
 Now to fill the table with data.

 After the table has been built, the Visual Data Manager will display the Database window with
the list of tables that we just created.
 To add data double click on the table.

 Click the Add button on the above form to add data to table. The form look like this.

 After entering the data click on the update button on the above form. Likewise add the required
data to the table.

110
 Optional Information: This button is used to build an Index for the table. The details for this
function are

Name: Enter the Name of the index.


Indexed Fields: Select the fields used to build the index from the Available Fields ListBox that
lists the fields in the current table.
Primary Index: We can specify if the index is to be the primary index. We can have only one
Primary Index.
IgnoreNulls: By clicking the IgnoreNulls check box, we can tell the data manager not to
include Null Values in the index.

Modifying Tables:
It is possible to change the name of the field, the data type, add a field, delete a field or to copy
the structure of a table. All this is possible with the Visual Data Manager.

Modifying The Name of a Field:


We can modify the name of a field by editing it in the Table Structure dialog box. The other
properties that can be modified are
Ordinal Position
Validation Rule
Default Value
Allow Zero Length
Required
The other properties cannot be modified. If however we have to modify the field property any way,
then simply delete that field and create it once again.
Note: if a field is an indexed field, it cannot be deleted or modified. In this case we must delete the
index or relation and then make the necessary changes to that field.

Copying a Table:
We can copy the entire table with the data and structure to another database.
In the database window, right-click on the table that we want to copy.
From the pop-up menu choose ‘Copy Structure’.
Enter the destination database where we want to copy the table.
We can copy the data as well by checking the ‘Copy Data ‘ check box.

111
CHAPTER-12
WORKING WITH THE DATA CONTROL

The Data Control:


A database can be created easily with the help of the Visual Data Manager. The tables can be
populated by simply entering the data in the respective fields. Next we need to create an application to
display the data from the database, and allow the user to add new records or modify existing records.
 To create such an application we have to
 Establish a connection with the database.
 Extract the fields from the relevant tables.
 Display them on the form.
 Accept changes made to the data on the form and update the database.
Visual Basic is meant to reduce the amount of coding and speed up application development for
the windows environment. Developing a database application is considered to be very easy with Visual
Basic. In order to meet these objectives, Visual Basic provides the Data Control that will make the
above job very easy.
The Data Control
1. Establishes a connection to a database.
2. Returns a set of records from the database.
3. Enables you to move from record to record.
4. Enables you to display and manipulate data from the records in bound controls.
All this is done without writing any code. The data from the database from the current record is
displayed in ‘Data-aware’ controls. Any changes made to the data in the ‘Data-aware’ controls are
conveyed to the Data control. The database is updated to reflect these changes automatically once the
Data control moves to the next record. The next record now becomes the current record, and the data is
displayed in the Data-aware controls.
Working of Data Control:
In order for the Data control to deliver the goods, two properties need to be set. These properties
can be set at runtime or design time. The properties are
DatabaseName: This specifies the name of the database that must be opened.
RecordSource: This specifies the name of the tables of the database from which the data has to be
extracted.
When we run the program after setting these properties, Visual Basic connects to the database
specified, and returns a set of records from the tables in the form of a Recordset.
A Recordset is an object that points to the data in the database. It is the set of records returned,
based on the RecordSource property of the Data control. The RecordSource property can be the name
of a table in the database or an SQL statement that selects fields from one or more tables.

Using the Data Control:


The Data Control is part of the standard toolbox. Draw the data control on the form. It looks like
this.
112
MovePrevious

MoveFirst MoveLast

MoveNext

It has buttons for moving from record to record. These buttons are used to move the records
first, next, last and previous records. We can also set the caption property for the Data Control.

Setting the Properties for the Data Control:


BOF Action: Action to be taken when the user reaches the beginning of File.
EOF Action: Action to be taken when the user reaches the End of File
Caption: The text to be displayed on the Data Control’s title bar.
Connect: This tells the Data Control the type of database that will access. It could be FoxPro, dBase,
Paradox, Access, etc. the default is Access.
DatabaseName: Specifies the name of the database that the Data Control will access. Give the name
of the file that contains the database. It can be set at run time.
Recordset Type: This property specifies the type of Recordset object the control will use to access the
database. There are three options: 1. Table, 2. Dynaset, 3. Snapshot.
RecordSource: the RecordSource property specifies the source of the records accessible through
bound controls on the form. If we set the RecordSource property to the name of an existing table in the
database, all of the fields in that table are visible to the bound controls attached to the Data control.

Example:
Let as create a program that will display the records in a database.
Creating the Form
 Start a new project.
 Add the Data control to the Form.
 Add two Text Box controls.
 Add two CommandButton.
 Add Two LabelBox controls.
 The form will look like this.

113
Setting the Properties:
Click on the Data Control and bring up the Properties Window.

 Click on Name: Let us call it Customerdata. We will be referring to the Data control with this
name.
 Click on BOFAction: Set it to MoveFirst. When the beginning of the file is reached, the Data
Control must be told to point to the First Record.
 Click on Caption: Set it to customers. This will be the title of the Data control. The default is
Data1.
 Click on the Connect Property: Select Access. Access is the default. This tells Visual Basic the
type of database that will be used. Visual Basic can work with a number of other databases.
 Click on DatabaseName Property: here mention the name of the MDB file that must be opened
by the Data Control. That is Select the path name here.
 Click on EOFAction: Set it to MoveLast. This tells the Data control to point to the last record
when the user reaches the End of File.
 Click on Recordset Type Property: Select 0-Table type. A Recordset Type property determines
the type of object that will be created by the Data control. The options are
 Table Type where an editable Recordset is created based on data from a single table.
 Dynaset, where an editable Recordset is created based on data from one or more tables.
 Snapshot, where a non-editable Recordset is created based on data from one or more table.
 Click on RecordSource Property. Set it to Customer_Data. In this property we tell the Data
Control the table or query that must be used while creating the Recordset.
The Bound Controls:
 Some of the controls can be ‘Bound’ to the Data control. Each bound control is bound to
one field of the Recordset.
 They display the fields from the current record of the Recordset.
 Depending on their properties, they may also allow the user to edit the data displayed and
pass the edited data back to the Data control.
The following controls are all data-aware and can be bound to a single field of a Recordset managed by
the Data control.
Label Image
TextBox ListBox
CheckBox Picture

114
OLE ComboBox

The following controls are all capable of managing set of records when bound to a data control. All of
these controls permit several records to be displayed or manipulated at once.
 DBList
 DBCombo
 DBGrid
Binding the Bound Controls:
We can make a control Data-aware by setting its properties. On order ro make the TextBox, Data-
aware, we need to bind it to the Data control.
Example:
 Open a new project and place two text box and one command button.
 Select Text1. Bring up the properties.
 Click on DataSource Property. Set it to Data1. This is the name of the Data control.
 Click on DataField. A list of fields available will drop down. Select the Customer_Name.
 This TextBox is now bound to the column Customer_Name. It will display the current record of
the Recordset.
 When the user moves from record to record using the navigation buttons of the Data control, it
will display the Customer_Name column of the current record.
 Next select Text2. Set the following properties.
DataSource: Customerdata
DataField: Amount_Due.
 For the command1 click event, add the statement End in order to terminate the program. Run
the program.
 Click on the next, previous, last, first buttons on the Data Control and the data is moved
according to the buttons.
 Make changes to the data in the textbox and check if the changes are updated in the database.
Caution:
 The Data control automatically handles record navigation, it can accept changes and also update
the changes made to the data.
 The Data control cannot handle some of the problems that are likely to occur in the real life
applications.
 The Data control is initialized before the initial Form_Load event for the form on which it is
placed.
 If any errors occur during the initialization step, a non-trappable error results.
 If the .mdb is missing or has been renamed, the program will not be able to trap this simple
error.
 Therefore we must use code to solve this problem.
Example for using Data Control:
Open a new project. Add the following controls to the form.
1. Two LabelBox controls.
2. Four TextBox controls.
115
3. Six CommandButtons.

Setting the properties.


 For the Data control set the following properties:
Name Customerdata
BOFAction 0 – Move First
Caption Customer Data
Connect Access
DatabaseName C:\Path

EOFAction 0 – Move Last


Recordset Type 1- Dynaset
RecordSource Customer_Data

 For the TextBox controls set the following properties


Name C_Code/C_Name/Amt_Due
DataSource Customerdata
DataField Customer_Code/Customer_Name/Amount_Due
 For the Fourth text box change the name as FindTxt.
 For the command buttons give the following captions,
Add, Modify, Delete, Update and Find.
 The form will look like this,

Coding: Adding a New Record:


 To add a new record we must invoke the ‘AddNew’ method, which will create a blank record in
the memory.
 This blank record becomes the current record.

116
 After we entered the data we can add the new record to the database by either of the following
methods.
o Moving to another record.
o Invoking the ‘Update’ method.
Add the following code to the Add button.
Private Sub CmdAdd_Click( )
Customerdata.Recordset.AddNew
Ccode.SetFocus
End Sub
The AddNew method adds a new record at the end of the file, and clears the contents of the textboxes
and set the focus on the textbox Ccode.
Deleting a Record:
o To delete a record we must invoke the ‘Delete’ method.
o The current record that is displayed will get deleted.
o Once this record is deleted, we must move the record pointer to the next record.
o This is because the record pointer will continue pointing to non-existing record once the current
record has been deleted.
o Although the record is deleted in the database, the data will be still visible to the user.
o When the user clicks on the delete button second time an error will occur.
o To avoid this the code must look like below.
Private Sub CmdDelete_Click( )
Customerdata.Recordset.Delete
Customerdata.Recordset.MoveNext
End Sub
o To avoid the problem when deleting the last record, the code will look like this.

Private Sub CmdDelete_Click( )


Customerdata.Recordset.Delete
If Not Customerdata.Recordset.EOF then
Customerdata.Recordset.MoveNext
Else
Customerdata.Recordset.MoveLast
End Sub
Updating the Database:
 The data control itself handles the task of updating the database with the changes made to the
current record, when we move the record pointer to another record.
 To do it explicitly, call the update routine as follows.
Private Sub CmdUpdate_Click()
Customerdata.UpdateRecord
Customerdata.Recordset.Bookmark = Customerdata.Recordset.LastModified
‘ This line is added so that the control returns to the record that has just been
updated. Otherwise the control returns to the first record’.

117
End Sub
UpdateRecord and UpdateControls Method:
 These methods are special to the data control.
 The updateRecord method allows the user to save the changes to the current record and
continue editing.
 This will be great use when the number of fields to be edited on the form is large.
 The UpdateControl method does the reverse of the UpdateRecord method.
 This method will be of use when the user wants to roll back the editing changes to the current
record before updating.
Finding a Record:
 The Find method works only when the Recordset type is a Dynaset or snapshot.
 If the Recordset type is set to Table type, then we must use Seek method.
Private Sub CmdFind_Click()
Customerdata.Recordset.FindFirst “Customer_Name= ‘“& Trim(Text4.Text) & “
’“
End Sub
 The FindFirst method looks for the first record where the Name column matches the text
entered in the FindTxt Textbox.
 The record that contains the matching text will become the current record.
 If no matching Name is found, the data control will remain silent.
 Run the application.

The DBGrid Control:


 The DBGrid control displays fields from a Recordset object as a series of rows and columns and
enables manipulating of this data.
 The data-aware DBGrid control is like an enhanced Grid control.
 Once the properties are set, it gets populated automatically with the data from the Recordset
object.
 We only need to fix the number of columns.
 The total number of rows is indeterminate.
 A DBGrid control can have as many rows as the system resources can support and about 1700
columns.
Example:
 Start a new project.
 Add the following controls on the form
o One DBGrid control
o One Data Control
The DBGrid control can be selected as follows.
 Right click on the ToolBox.
 Select the components from the poop-up menu and click on DBGrid control and press OK.
Set the properties for the controls as follows.

118
Data Control
DataSource: C:\VB\Biblio.mdb
RecordSource: Publishers
DBGrid Control
DataSource: Data1.
Now run the program.

CHAPTER-13
DATA ACCESS OBJECTS
The Jet Database Engine:
 Microsoft Access 1.0 was released in 1992 as a database for the windows platform.
 The Jet Database Engine was the genie doing all the hard work behind Microsoft
Access.
 Access has wizards, which made it easier for beginners to learn and use.
 Jet 1.0 could handle the functions that were expected of a database engine.
 Apart from the standard DDL, DML, maintenance and security features, it could gather
data from different sources at the same time and introduced the concept of Dynaset.
 These features can be used only with the Microsoft Access.
 The Jet 1.1 could be controlled programmatically using Data Access Objects ( DAO).
 A Database Engine provides the link between the data and the application.
 The Jet Database Engine 1.1 could be used with all the Microsoft products, from MS
Excel to Visual C++.
 It worked as the data manager in a data access application built using other products like
Visual Basic or Visual C++.
 DAO 1.1 allowed users to use the DDL to control the Jet engine.
 The next version of Jet implemented a better hierarchical model and allowed the user to
control all its capabilities through the DAO.

DAO, Hierarchical Model

Application

119
It is now 32-bit implementation and provides
o Referential Integrity
o Cascading Updates and Deletes
o Replication and Synchronization
o Replication over the Internet
o The Jet database engine can read and write data stored in other database formats
o It can read data stored in
 Spreadsheets
 Text files
 HTML tables and lists
 ODBC databases.
 The DAO has an extensive set of properties and methods and can provide data access
services to various applications from MS word to visual C++.
 ADO is the current technology offered by Microsoft, replacing DAO.
 Over a period of time, Jet and DAO have evolved into fairly complete and complex products, jet
as a database engine that could provide various services and DAO allowing the programmer
access and control to these services.

Functions of the Jet Database Engine:


Microsoft Jet provides the seven basic functions of a DBMS. They are,
 Data definition and integrity: It allows the user to create and modify structures for
holding data, such as tables and fields. It also ensures that rules are applied to data
operations to prevent data corruption from invalid entries or operations.
 Data Manipulation: It allows the users to add new data, modify or delete existing data
from the system.
 Data Storage: It holds data as per the structures and stores it in the file system.
 Data Retrieval: It allows the users to retrieve and view the data from the system.
 Database Maintenance: Compact, repair and convert data and database objects.
 Security: Control user’s access to database objects and data, thereby protecting objects
and data against unauthorized use.
 Data Sharing: It allows more than one user to access the data in a multi-user
environment.
Data Definition (DDL) and Data Manipulation (DML) Language:
 Data Definition Language (DDL) deals with the structure of the data with creating tables,
adding fields, creating indexes etc.
 The activity carried out by the Visual Data Manager comes under this.
 Once the structures are defined they are stored in a single file.

120
 The data definition as well as data is stored in one file.
 DAO methods are used to create these structures.
 Data Manipulation deals with the content of the database with allowing the user access
to the data in the database.
 We can create view, or select some of the data through queries.
 We can access the data using SQL statements or by using DAO.
 DAO is most suitable for DDL functions and SQL is suitable for DML functions.
Storage:
 The Jet Database is stored as a single file with the .MDB (Microsoft Access Database)
extension.
 The .mdb files are stored in the ISAM format. The records are stored as per their index
or as per the order of entry in the table if the Index is not specified.
 The records are stored in a variable-length format, on pages that are 2K in length.
 One record cannot span two pages.
 The file size of a .mdb file will increase disproportionately if there is a lot of data-entry,
deletion and addition of records.
Retrieval:
 Data can be retrieved from the database, either through SQL statements or through
DAO.
 Data retrieval is normally through ‘Queries’ that are instructions to the database to
present the data in a certain format, based on a certain criteria.
Relationships:
 Jet is an RDBMS, and hence the tables are built in such a way that one table will have a
relationship with one or more tables in the database.
 The data is spread across more than one table in order to reduce the redundancy of data
and allow easy access to data.
 The below figure gives the concept of relationships:

Customer
Customer_Invoice Invoice_Details Product_Details
Customer_Code
Customer_Code Invoice_No Product_Code
Customer_Name
Invoice_No Product_Code Product_Name
Customer_Address
Customer_Balance Quantity Price
Quantity

 Jet allows building relationships and ensuring referential integrity.


 In the above figure, we cannot have invoice details in the ‘Invoice_Details’, table
without an invoice number being present in the ‘Customer_Invoice’ table.
 We can build relationships and indexes at design time or through queries.
121
Multi-user Environment:
 Jet allows more than one user to access the database.
 It is a remote multi-user implementation. The data resides on a sigle server, and the
database engine resides on each of the workstations.
 It cannot handle more than a few dozen user, unlike the other databases like Oracle or
SQL Server.
 In Oracle, the entire database runs in an exclusive environment of its own.
SQL:
 SQL is a database programming language. The earliest version was called Sequel.
 The ANSI has set a certain standard that is used by relational databases.
 SQL is an industry-standard database interface and the knowledge of SQL command
allows accessing and manipulating a wide variety of database products from many
different vendors.
 In SQL terms, a row is a record and a column is a field. A file is a table.

The SELECT statement:


 The SELECT statement fetches the data from the databases as a set of records.
 It does not change the information in the table, and is usually the first word in an SQL
statement.
 It displays the data in the order in which it has been entered.
 The syntax for SELECT statement must include
o The criteria for selection.
o The source of data from where the data to be selected.
Syntax:
SELECT [predicate] { * | table.* | [table.] field1 [AS alias1] [, [ table.] field2 [AS alias2]
[, …]]} FROM tableexpression [, …] [IN externaldatabase]
[WHERE …]
[GROUP Y …]
[HAVING …]
[ORDER BY …]
[WITH OWNERACCESS OPTION]
 The SELECT specifies what is required and From where.
 The SELECT statement has three parts:
 Predicate: The limiting criteria for the selection of information.
Example: ALL, DISTINCT, TOP etc. the Default is ALL. It is represented by “*”.
 Table: The source from where the information must be selected.
 Selected columns: We can also select the columns that we want listed. This can be done
by giving the column head as part of the syntax.

122
 Alias: The alternative name for columns headers. The column headings in a table can be
cryptic.
 Table expression: The name of the table or tables containing the data we want to
retrieve.
 External Database: The name of the database containing the tables in table expression,
if they are not in the current database.

Example:
SELECT * From Titles.
 It will display all the fields from the table Titles.
SELECT PubID, Name from Publishers.
 This statement will select only the PubID and Name fields from the table Publishers.
 In Visual Basic to build an SQL statement such as
SELECT * FROM Tables
 We need to write the following code.
DIM SQLStr As String
SQLStr = “SELECT * FROM Tables”
 After building the SQL statement, it must be assigned to the RecordSource property.
 If the Data Control is called as Data1, then the statement
Data1.RecordSource = SQLStr
 Will assign the value of the SELECT statement to the RecordSource property of Data1.

Example:
 Start a new project
 On the form create the following
o One DBGrid control
o One Data control
o Two Command Button controls
 Set the following properties
o DBGrid Control
o DataSource: Data1
 The other necessary properties will be set at run time.
 Add the following code in the respective controls.
Private sub Form_Load ()
Data1.DatabaseName = C:\VB\Biblio.mdb
End Sub
 This statement sets the DatabaseName property for the Data1 control.
Private Sub Command1_Click ()
Data1.Recordset = Select * From Titles
123
Data1.Referesh
End Sub
 The first statement assigns the SQL statement to the RecordSource Property of the Data1
control.
 The second statement will fill the Data1 control with data from the table.
Private Sub Command3_Click ()
End
End sub
 It is used to end the application. Now run the application.
 In order to select all titles that were published in the year 1988, we would build the
SELECT statement as follows:
Data1.RecordSource = SELECT * From Titles WHERE [Year Published] =1988
 In order to select only those publishers whose names start with S, we can construct the
query as follows:
Data1.RecordSource = SELECT * From Publishers WHERE [Company Name] LIKE _[s]*

The DAO Object Model:


 When data is stored in a relational database, it must be stored in fields that make up the
rows and columns.
 These rows and columns in turn will make up a table.
 One or more such tables make up the database.
 Therefore each item, such as a field or a table is an object.
 It is this hierarchy of the various objects of a database that make up the DAO
hierarchical model.
 The model includes much more than fields and tables and illustrated as follows:

124
The DAO Object Model

Understanding the DAO Object Model:

 The DAO object model models the structure of a relational database systems. With the properties
and methods provided by DAO objects, we can accomplish a number of tasks.
 This includes creating databases, defining tables, fields and indexes, establishing relations between
tables, and navigating and querying the database.
 The jet database engine executes the commands of the DAO on the actual database.
 There are 15 objects in the DAO object model, as listed here:
1. DBEngine Object:
 This DAO object holds all other objects and maintains engine options. It contains and
controls all other objects in the hierarchy of DAO objects.
 We can have only one DBEngine object, and the DBEngine object doesn’t belong to any
collection.
2. Workspace Object:
 Defines and manages the current user session.
 It contains information on open databases, and provides mechanism for simultaneous
transaction for a user.
 Each user has his own workspace.
125
 It is non-persistent object that defines how the application interacts with data- either by using
the Microsoft Jet database engine, or ODBC Direct to access eternal data.
 Use the Workspace object to manage the current session, or to start an additional session.
3. Database Object:
 Represents a database with at least one open connection.
 This can be a Microsoft Jet database or an external data source.
 We can use the Database object and its methods and properties to manipulate an open
database.
 In any type of database, we can use the OpenRecordset method to execute a query and create
a Recordset object.
 We can also create tables, relations, modify tables. We can use the CreateTableDef and
CreateRelation methods to create tables and relations.
4. TableDef Object:
 Contains both Field and Index objects to describe database tables.
 A TableDef is the stored definition of a ‘Base’ table or a ‘linked’ table.
 By using this properties we can set Validation rules, return information about linked tables
etc,.
5. QueryDef Object:
 Represents a stored SQL query statement with zero or more parameters, maintained in a
Microsoft Jet database.
6. Recordset Object:
 A Recordset object represents a set of records in a table, or the records returned by a query.
 We can use Recordset object to manipulate data in a database at the record level.
 DAO has five types of Recordset objects: Table, Dynaset, Snapshot, Forward-only and
Dynamic.
7. Container Object:
 It represents a particular set of objects in a database for which we can assign permissions in a
secure workgroup.
 An application may define its own Container objects such as saved forms, modules, reports,
or script macros.
8. Relation Object:
 It represents a relationship between fields in tables and queries.
 It is used to create, delete, or change the type of relationship and determine which tables
supply the fields that participate, whether to enforce referential integrity, and whether to
perform cascading updates and deletes.
9. Field Object:
 It represents a field in a table, query, index, relation, or Recordset.
 A Field object represents a column of data with a common data-type and a common set of
properties.
 A Field object contains data, and we can use it to read data from a record or write data to a
record.
10. Index Object:
126
 It represents an index on a table in the database.

11. Parameter Object:


 It represents a value associated with a QueryDef Object.
 Query parameters can be input, output or both.

12. Document Object:


 It contains information about individual objects in the database such as tables, queries, or
relationships.
13. User Object:
 It represents a user account with particular access permissions.
14. Group Object:
 It represents a group of user accounts that have common access permissions in a particular
workspace.
15. Error Object:
 It contains information about error that occurred during a DAO operation.
 Any operation involving DAO can generate one or more errors.
 For example, a call to an ODBS server might result in an error from the database server, an
error from ODBC and a DAO error.
 As each such error occurs, an Error object is placed in the Errors collection of the DBEngine
object.
 A single event can therefore result in several Error objects appearing in the Errors colletion.

Putting DAO to work:


After all this about Jet and DAO. Let us put DAO to work. We will first take up the DDL functions of
DAO.
Start a New Project:
In the Project Reference we have specified one of the DAO libraries. If you plan to develop your
applications for the 16-Bit platform as well as the 32-bit platform then choose the 2.5/3.51
compatibility library. If your application is meant only for the 32-bit platform, select the Microsoft
DAO 3.51 Object library.
Opening a Database:
 Let us create a simple application that will open a database. The user must supply the name of
the database.
 Create a form as follows. This form will have only one textbox and one CommandButton to
start with. As we experiment further, we will add more controls.
 The user must enter the name of the database to be opened in the textbox. When he clicks on the
CommandButton, the program must pop-up a message box with the name of the database that
has been opened.
 To open a database, we have to use the OpenDatabase method. This method opens a specified
database in a Workspace object and return a reference to the database object that represents it.

127
Syntax:
Setdatabase = workspace.OpenDatabase (dbname, options, read-only, connect)
The OpenDatabase method syntax has these parts.
Database: an object variable representing the Database object that you want to open. This is the
variable that you have declared.
Workspace: Optional. An object variable that represents the existing Workspace object that will
contain the database. The default workspace is workspace (0). If workspace is not included,
OpenDatabase uses the default workspace.
Dbname: The name of an existing Jet database. Or the data source name (DSN) of an ODBC Data
Source.
Options: Optional. A variant that sets various options for the database, as specified in Settings.
read-only: You can specify if you want to open the database with or without Read/Write access. If you
say True, then it means read-only. False means Read/Write access.
Connect: Connection, including passwords.
 First declare the variable. In the General declarations section, add the line below
Dim db As Database
Dim wrk As Workspace
 Now we need to accept the name of the database file in the textbox. Based on the name, we
have to open the database.
 Add the following line to the code window of the CommandButton.
‘Declare a variable to hold the text from the textbox.
Dim strdbname As String
Strdbname = Text1.Text
Set db = wrk.OpenDatabase (strbname)
MsgBox db.Name
 Run the program. Give the name of the database that you have created.
 There is another way to get the name of the database that has been opened. Open the immediate
Window and enter the following.
?db.Name
C:\azam\Invoice.mdb
 This displays the name of the database that has been opened.
Creating a Database:
 We have opened the database with great ease. Now let us see how we can create a database. In
order to create a database, we have to use the CreateDatabase method.
 The CreateDatabase method Creates a new Database object, saves the database to disk, and
returns an opened Database object.
Syntax:
Set database = workspace. CreateDatabase (name, locale, options)
The CreateDatabas method syntax has these parts.
128
Database: An object variable that represents the database object that you want to create. This is the
variable that you have declared/

Workspace: optional. An object variable that represents the existing Workspace object that will
contain the database. The default workspace is workspace (0). If workspace is not included,
CreateDatabase uses the default workspace.
Name: A sting up to 255 characters long that is the name of the database file that you’re creating. It
can be the full path and file name, such as “C:\emsquare\invoice.mdb”. if you don’t supply a file name
extension, .mdb is appended. If your network supports it, you can also specify a network path, such as
\\server1\share1\dir1\db1. you can only create .mdb database files with this method.
Locale: this argument is necessary. A string that specifies a collecting order for creating the database,
as specified in Settings. You can also create a password for the new database object by concatenating
the password string (Starting with “;pwd=”) with a constant in the locale argument, like this:
dbLangSpanish & “ ;pwd = NewPassword”
 If you want to use the default locale, but specify a password, simply enter a password string for the
locale argument:
“;pwd = NewPassworpwd = NewPassword”
 Let us see how we can create a database.
 Add one CommandButton to the existing form. Give it a caption like ‘CreateDatabase’. In the code
area for this button, add the following code.
Dim strdbname As String
strdbname = Text1.Text
Set wrk = DBEngine .Workspaces(0)
Set db1 = CreateDatabase(strdbname, dbLangGeneral)
Creating a Table:
 Now that we have created a database, let us create some tables in it.
 In order to create a table in an existing database, you have the CreateTable method. This method
cretes a new TableDef object.
Syntax:
Set tabledef = database.CreateTableDef (name,attributes,source,connect)
The CreateTableDef method syntax has these parts.
Tabledef: The name of the TableDef object you want to create.
Database: The name of the database object you want to use to create the new TableDef object.
Name: A unique name for the new table.
Attributes: Optional. A constant or combination of constants that indicates one or more characteristics
of the new TableDef object.
Connect: Optional. A variant containing information about the source of an open database.
To your form add another CommandButton. Change its caption as ‘CreateTable’. When the user clicks
this button, your program must create a table in the database(that has been opened).
Declare variables for the TableDef object in the declaration section. Your declaration section
will look like this:
Dim db As Database
129
Dim tabldf As TableDef
Dim fld As Field
To the click_event of this CommandButton, add the following code
Dim strtablename As String
Strtablename = Text1.Text
Set tabldf = db.CreateTableDef (strtablename)
‘Create two fields in the new table and append them.
With tabldf
.Fields.Append .CreateField(“Bill_no”, dbText)
.Fields.Append .CreateField(“Bill_date”, dbText)
End With
‘Append the table to the database.
Db.TableDefs.Append tabldf
Note:
Some of the optional arguments have not been used. These can be set right by appropriate statements
before appending the table to the database.
If the table name given by us is invalid or a table by that name exists in that database, an error will
occur.
We must define at least one field for the TableDef object before we append it to the TableDefs
collection.
To remove a TableDef object from the collection, use the delete method on the collection.

Creating Fields in the Database:


In order to create a field in one of the tables, we must use the CreateField method.
We can use the CreateField method to create a new field, as well as specify the name, data type,
and size of the field. Following is the syntax.
Syntax:
Set field = object.CreateField (name, type, size)
The CreateField method syntax has these parts.

Part Description

field : A variable that represents the field object you want to create.
Object : An object variable that represents the Index, Relation, or TableDef object
for which you want to create the new Field object.
Name: Optional. A variant that uniquely names the new Field object.
Type : Optional. A constant that determines the data type of the new Field object.
Size : Optional. A variant that indicates the maximum size in bytes of a Field
object that contains text. This argument is ignored for numeric and fixed-width
fields.

130
To your form, add another CommandButton. Change its caption to “CreateField”. When the
user clicks on this button, your program should create a field with the name given in the
textbox.
Modify your declaration. Add the following lines.

Dim newfield As Field


Dim strfieldname As String
Dim strdbname As String
Strdbname = Text1.Text

In the click event of the Commandbutton, add the following code


Strfieldname = Text2.Text
‘We assume that the database opened has a table called “ Supplier”
Set tdf = db.TableDefs (“Supplier”)
“The following statement creates a new field.
Set newfield = tdf.CreateField(strfieldname, dbText’
‘append the field to the table.
tdf.Fields.Append newfield

Example:
Let us create a program that will
 Allow the user to view details of a supplier.
 Allow the user to Add, Modify and Delete supplier details.
 Display list of items supplied by the supplier.
 Allow the user to search for a particular supplier.
o Start a new project.
o Select the appropriate reference for the DAO library.
o Add five text box control to display the following details.
Supplier ID
Supplier Name
Supplier Address
Supplier City
Search Criteria
Add four Command/Button that will allow the user to navigate the database. The buttons
can be labeled as “First”, Previous, Next and Last.
They can have a suitable symbol or icon. The form will look like below:

Arranging your code:

We can write the code for each activity in the click event of each of the
CommandButtons. In this case, a good part of the code will get repeated. If we need to make
changes to the code, then you will have to make the changes at every place. Instead of this we

131
can write the code as functions and call the function wherever necessary. You will understand
this better as we write the code for navigating the database.

 Click on project and Select ‘Add Module’. This module will hold only the code that you will
write for this program. In this module you can write your own functions and procedures and
call them from another form. Any changes that you want to make can be made in one location.
 Save the module. Give it an appropriate name, for example ’DaoModulel.bas’.

Let us first declare the variables. Declare these variables in the General Declaration section of the
DaoMoodule1.bas.
Dim db As Database
Dim rs As Recordset

Let us write a procedure for opening the database and selecting the fields from the table.
The name of the database is invoice.mdb in the Emsquare directory. Do not hard code the name of the
file. You can use the ‘App.Path’ syntax to specify the name of the file.
Sub opendata()
Set db = OpenDatabase (“C:\azam\invoice.mdb”)
Set rs=db.OpenRecordset(“select * from Supplier”, dbopenDynaset)
Rs.Movefirst
End Sub
 We can create a procedure by entering ‘sub”, followed by the name of the procedure. A pair of
brackets should follow this. Visual Basic’s editor will automatically add the line ‘End Sub’.
You should enter your piece of code between the opening line and the last line.
 The above procedure ‘Opendata ()’ will open the database “invoice.mdb” and create a recordset
in the textboxes. We need to write another procedure to display the text.
 Now that the database has been opened, we need to display the records from the Recordset in
the textboxes. We need to write another procedure to display the text.

132
 We will call this procedure “showfields”. This procedure will link each of the textboxes to a
field from the Recordset.

Sub showfields()
Form1.Text5.Text = rs.Suppli_ID
Form1.Text1.Text = rs.fields(1)
Form1.Text2.Text = rs.Supplier_Address_1
Form1.Text3.Text = rs.Supplier_City
End sub
 Now let us put these two procedures to work in our application.
 In the form_Load event , add the following lines
Call opendata
Call showfields
 The above lines will call the two procedures.
Run the application and see if it is working.
You will see that only the first record is displayed. We need to display the other records too,
when we click buttons like Next, Previous, etc. This means that we need to add more functions.
Let us write a function to display the next record. The procedure will be very similar to
that we wrote when we worked with the Data control. We will cal this function “mnext” the
function will be as follows.

Sub mnext()
Rs.MoveNext
If rs.EOF then
Rs.MovePrevious
End if
‘ display the fields of the next record
showfields
End Sub

 Observe that we are calling the function “showfields” in the “mnext” function. We do not have
to repeat the entire code here.
 Now call the “mnext” function from the click event of the Next button on your form. A single
line of code will make up the code for the click event of this button.
Call mnext()

Adding a Record:
 Now let us turn our attention to other functions of our applications. Our application
must allow users to ADD, Delete and edit records. Let us write the function to add a
new record.

133
 In order to allow the user to enter a new record we must first clear the textboxes. Once
the textboxes are empty, invoke the Add New method to add a new record. This is again
similar to the procedure followed when we worked with the Data control. The following
lines will do that, start a new procedure and call it “ add record”.

Sub addrecord()
Form1.Text5.Text=” “
Form1.Text1.Text=” “
Form1.Text2.Text=” “
Form1.Text3.Text=” “
Form1.Text5.Text.SetFocus
Rs.AddNew
End sub
Updating the Record
The data entered by the user will remain in the ‘copy buffer’ till such time it is updated to the
database using the Update method. If the user clicks on the Add button again, the textboxes
will be cleared, and so will the ‘copy buffer’. Therefore, once the user has added the data for
the new record, he must be forced to push the Update button.
We can ensure that the user cannot push buttons other than the Update button by setting
the Enabled property of the other buttons to false.
When the user clicks on the Update button we need to carry out the reversed of what we did in
the case of the showfields function. The “Updaterecord” function will look like this.
Sub updaterecord ()
rs.Supplier_ID = Form1.Text5.Text
rs.Supplier_Name = Form1.Text1.Text
rs.Supplier_Address_1 = Form1.Text2.Text
rs.Supplier_City = Form1.Text3.Text
rs.Update
End Sub

Editing a Record:
The record that you want to Edit must be made the current record. Then invoke Edit method.
The Edit method works like the AddNew method. It places the contents of the current record in the
‘copy buffer’. Once the user has made the changes to the data, the contents of the ‘copy buffer’ must be
moved to the database.
Calling the Update method is necessary. Please remember that the data entered by the user is
now placed in the ‘copy buffer’. In order to update the database, call the Update method before moving
the record pointer. If the record pointer is moved before using the Update method, the changes made to
the record are lost. However, the originals data will not be lost.

134
Create a procedure called “Editrecord”. The procedure will look kike this.
Sub Editrecord()
MsgBox “ You can change the data now ”
rs.Edit
End Sub
Call this procedure from the click event of the Modify button on your form.

Recordset types:
There are five types of recordsets.
Table type
Dynaset type
Snapshot type
Forward only snapshot type
Dynamic type
Table type: This represents the data of a base table, and changes made to this type of Recordset are
reflected in the base table. The table-type recordset can hold records from only one table, and is based
directly on the table rather than on a query. Any change made to the underlaying table is immediately
visible. You do not need to ‘refresh’ the record set. A table type Record set allows you create indexes
to perform a quick search for a record, or for changing the order of presentation of the records.
The disadvantage of this type of Recordset is that you cannot limit the number of records that
populate the recordset.
Moreover, you cannot use the find method. The seek method will stop with finding the first
record that meets the search criteria. You have to write code to search for the previous or next
occurrence of a record that meets the search criteria.
Dynaset type:
This is a dynamic set of updateable records that are the result of a query. You can use the
dynaset type of Recordset to add, change, or delete records from an underlying database table or tables.
A Dynaset-type recordset object can contain fields from one or more tables in a database.
A Dynaset is dynamic set of records. However, the number of records is fixed. Now records
that meet the selection criteria after the dynaset-type Records has been created are not added to the
recordset. This includes records that other users add. A dynaset is a recordset that reflects application
scrolls to a changed record; a new copy is retrieved, bringing it up to date. This behavior is ideal fro
situations in which its is important to be completely up to date.
The disadvantages of this type of Records are that you have to recreate or refresh the recordset
to reflect the addition or deletion of records to the table after the recordset was first created.
You cannot use Indexed to changes the order of presentation.
Snapshot type:
As the name implies, it is the state of records in one or more table at point of time. This type of
recordset is ideally used to find a record or generate reports. A snapshot-type recordset object can
contain fields from one or more tables in a database, but can’t be updated. The advantages of the
Snapshot type recordset are similar to those of the dynaset, except that it is a static picture of the
tables(s) at a point of time
135
Forward Only type
This is just like the snapshot type recordset. In this case we cannot scroll backwards. This
improves performance in situations where you only need to make a single pass through a result set.
Dynamic Type:
This type of recordset is created only when we use ODBCDirect. This is like the Dynaset type
Recordset, with the additional functionality that the records updated by the other user in a multi-user
environment are also displayed in your Recordset. It is a query result set from one or more base tables
in which we can add, change, or delete records from a row-returning query.

Creating different types of recordsets:


The following line will create a Dyanset type Recordset.
Set rs=db.OpenRecordset(“Select * from supplier”, dbOpenDyanmic)
The following line will create a Talbe type Recordset.
Set rs=db.OpenRecordset(“Supplier”,, dbOpenTable)
The following line will create a Snapshot type Recordset.
Set rs=db.OpenRecordset(“Supplier”,, dbOpen Snapshot)
The Find Method:
Let us get back to our application and add the functionality that will enable the user to
find a record based on a criterion. Let us say that the user wants to locate a record based on the
city to which the supplier belongs. We need to create a dynaset type Recordset.
We must get the criteria from the user, in order to use the FindFirst method.
The Find First method finds the first record from the TOP of the Recordset that meets the
search criteria.
The code segment for the search will look like this.
Sub search1()
Dim strBookmark As String
Dim Strscriteria As string
Strscriterea=Form1.Text4.Text
Strscriteria= “supplier_city = “ “ & Strcriteria & “ “
‘ this statement will find the first record that meets the search criteria.
Rs.FindFirst Styrscriteria
If rs.NoMatch Then
MsBox “ID not found!”
‘in case the search is not successful, the record pointer must be brought back to
the record where it was before invoking the search.
Rs.Bookmark = strBookmar
‘Exit the search procedure if search is not successful
Exit Sub
End if

136
“Display the record that meets the search criteria.
Showfields
End Sub

The other Find methods are


FindNext: Find the next record DOWN the Recordset from the current location that meets the
search criteria.
FindPrevious: Find the next record UP the Recordset from the current location that meets the
search criteria.
FindLast: Find the first record from the bottom of the Recordset that meets the search criteria.

Using multiple tables:


Our application displays the Supplier details. It allows the user to view and modify the data.
However, if the user wants to see the list of items that a supplier supplies, as well as his address
etc, then the current application is not good enough.
We need to open the Suppler_Item table and select the items that the Supplier. The
selection will be based on the Supplier_ID. All items must be selected based on the
Sipplier_ID matching the Supplier_ID of the supplier whose record is displayed.

Supplier

Supplier_Code
Supplier_Name Item_Name
Address Supplier_Item

Supplier_Code
Item_Code

Add a ListBox to the form. Your Form will look like below:

The ListBox must be populated with the item list. The code required will look like this
Sub populate_ItemList ()
Form1.ItemLis.Clear
‘This statement will select those Items from the Supplier_Item table where the Supplier
ID of this table matches with the Supplier_ID displayed on the form.
Set rs1= db.OpenRecordset (“select distinct itemed from SupplierItem where SupplierID
=” “ & _ Trim(Form1.Text5.Text) & “ “, dbOpenDynaset)
‘ The ListBox is populated here.
137
With rs1

Do Until rs1. EOF


Form1.ItemList.AddItem rs1. ItemID
Rs1.MoveNExt
Loop
End With
End Sub
====================x=================x=================x=======

Chapter : 14

ActiveX Data Objects


ADO is meant to replace DAO, RDO and ODBC, which means that today’s access
requirements are not limited to handling only relational data. We need to access data from other
sources as well, such as mail, Internet content directory data from other machines and others.

138
What we need is a simple, consistent application programming interface (API) that
enables applications to gain access to and modify a wide variety of data sources. A data source
may be a database, a text file, a spreadsheet, a graphics application, a cluster of heterogeneous
databases, or something yet to be invented.

OLE DB
OLE DB, a set of Component Object Model (COM) interfaces that provide uniform access to

data stored in diverse information sources. It is defined as a general- purpose set of interfaces designed

to let developers build data access tools as components using the Component Object Model (COM).

OLE DB enables applications to have uniform access to data stored in DBMS and non- DBMS

information containers, while continuing to take advantage of the benefits of database technology

without having to transfer data from its place of origin to a DBMS.

OLE DB has what it calls ‘providers’ which let you access the different data sources. For

different data sources you have different data providers.

1. A Cursor Service. A cursor is defined as a temporary, read-only table that saves the results

of a query with an assigned name. The cursor is available for browsing, reporting, or other

uses until it is closed .

2. A service to perform batch updates.

3. A shape service to build the data in the form of a hierarchy.

4. A remote data service provider for managing data in multi-tier environments over connected

or disconnected networks.

The ADO acts like the intermediary between the application and the OLE DB.

139
ADO
“ADO’s primary benefits are ease of use high speed, low memory overheads, and a

small disk footprint. ADO supports key features for building client/server and Web-based

applications.

The ADO features an object model like the DAO and the RDO but it is much flatter.

The ADO programming model illustrated below allows you do all this more.

The goal of ADO is to gain access, to edit, and update data sources. It provides classes and
objects to perform each of the following activities:
Connection Make a connection to a data source.
Command Create on object to represent an SQL command.
Parameter Specify columns, tables, and values in the SQL command as
variable parameters.
Recordset Execute the command and store the result, if the command is row returning, in a
cache. Allow the user to sort, view or edit the data. If necessary, update the data source.

Connection You can access a data source using the Connection object. Unless a connection is

made, data cannot be exchanged between the data source and the application. The connection

140
object specifies the name of the data source, the provider that will be used to access the data,

and other parameters.

Command Once a connection has been established with the data source, the data has to be

extracted. This is done using the Command object. The command adds, deletes and updates

data in the data source, or retrieves data in the form of rows in a table.

Parameter The command to retrieve data can be qualified using parameters. Parameters are

arguments to a command that alter the result of the execution of the command. Parameters are

especially useful for executing commands that behave like functions.

Recordset Although ADO allows you to access any type of data, our discussion here is limited

to data from a database. The command object when executed will return a set of rows from

one or more tables. This set of rows is called a Recordset.

The Recordset is the primary means of examining and modifying data in the rows.

 Specify which rows are available for examination

 Traverse the rows

 Specify the order in which the rows may be traversed

 Add, change, or delete rows

 Update the data source with changed rows

 Manage the overall state of the Recordset.

Field A row of a Reckordset consists of one or more fields. If you envision the Recordset as a

two dimensional grid, the fields line up to form columns. Each field (column) has among its

attributes a name, a data type, and a value.

141
Error Errors can occur at any time in your application, due to the data source being corrupted

or renamed by somebody, or the Password being changed.

Property There are two types of properties: built-in and dynamic. Built- in properties are parts

of the ADO object, and are always available. Dynamic properties are added to the ADO

object’s Properties collection by the underlying data provider.

Collection The objects in the collection can be retrieved with a collection method, either by

name, as a text string, or by ordinal as an integer number.

The command object has the Parameters collection, which contains all Parameter objects

that apply to that Command object.

The Recordset object has the Fields collection, which contains all Field objects that

define the columns of that Recordset object.

The connection, Command, Recordset, and Field objects all have a Properties collection,

which contain all the Property objects that apply to their respective containing objects.

Events

ADO 2.0 introduces the concept of events to the programming model. Events are

notifications that certain operations are about to occur, or have already occurred.

Connection Events:

Events are issued when transactions on a connection begin, are committed, or rolled

back, when Commands execute, and when Connections start or end.

Recordset Events:

142
Events are issued to report the progress of data retrieval in the following cases. When

you navigate through the rows of a Recordset object, when you change a field in a row of a

Recordset, change a row in a Recordset, or make any change in the entire Recordset.

Establishing a Reference

To use ADO in your project, you have to make a reference to it. This is done just as we

made the reference to DAO. Click on Projects, and from the menu Select References. From the

list displayed in the reference dialog box, select Microsoft Active X Data Objects 2.0 Library

and the Microsoft Active X Data Objects Recordset 2.0 Library. Now you can use ADO in your

project.

The ODBC Data Source Administrator

ODBC is defined as “a standard protocol for database servers. ODBC has drivers for

various databases that enable applications to connect to the databases and access their data.”

The condition is that these databases must have SQL as the standard for data access. From the

Control Panel, double click on the ODBC icon. This will bring up the ODBC Data Source

Administrator dialog box. Click on the Add button to add a data source. Another dialog box

will be displayed, asking you to select the driver.

Select Microsoft Access driver (*.mdb) since we are going to work on our Invoice. mdb.

Click on Finish. The next dialog box displayed will ask you to specify the name of the

database.

Click on Select to choose the name of the .mdb file. After selecting the .mdb file, enter

the name of the data source. You will be using this name as the DSN (Data Source Name).

Click OK and exit from the ODBC administrator.

143
Using the Data Source Name in Our Project

In the General declaration, add the following lines of code

Dim adocon As New ADODB. Connection

Dim rs As Recordset

Dim strconnect As string

The first line declares and sets ‘adocon’ as an ADODB connection object. You cam

declare the above as follows

Dim adocon as ADODB. Connection

In the Form-Load event you can say

Set adocon As New ADODB. Connection

We have declared the connection object. Now to set the connection to a data source.

Creating the command We can create a command object and assign the command string as

the commandText as follows.

Dim comd As New ADODB. Command

Comd. CommandText = “SELECT * from customer”

The command object must be linked to the connection object using the following line.

comd.ActiveConnection = adocon

Executing the command The command can be executed by either using the command object,

or by using the Recordset object.

Add the following lines to your code

set rs = comd.Execute

MsgBox rs.Fields (1)

Manipulating the records in the recordset

Add a command button to your form. Add the following lines of code to its click-event.
144
Private Sub Command1-Click( )

rs. MoveFirst

Do While Not rs. EFO

Debug. Print rs. Fields (0) & “ “; rs. Fields (1)

rs. MoveNext

Loop

End Sub

This segment of code will display the first two fields of the Recordset. Remember that

this Recordset returns all the fields from the Customer Table of the invoice.mdb. We are

viewing only the first two fields of the Recordset. The Move First method moves the record

pointer to the first record. The MoveNext method moves the record pointer to the next record.

USING THE ADO DATA CONTROL

We can display the data from a Recordset (data source) using ADO code, or with the
help of the ADO Data Control. In order to use the ADO Data, we need to add the control to the
form. The ADO Data works just like the Data control that we worked on earlier. However the
Data control cannot work with ADO, so we need add the ADO Data control.
Right click on the ToolBox, and from the pop-up menu select Components. From

this dialog box click on Microsoft ADO Data Control 6.0 (OLEDB). The ADO Data control

gets added to your Tool Box. Draw the ADO data control on your form and set the properties.

Right Click on the ADO Data control and select ADODC Properties from the menu. The

Property Pages dialog box will look like this.

145
The Property Pages of ADODC contain four tabs. They allow you to set the various

properties of the ADODC. They are

General In this tab you specify how the ADODC should connect to a data source. There are

three options.

Use data links file You will need this option if you are going to link a textbox or a grid or

some such control to an application like. Excel or Word via DDE.

Use ODBC data source name You can mention the name of the DSN that we created using

the ODBC Data Source Administrator. The DSNs already created will be displayed in a drop-

down ListBox. You can select the one you need to work with, or you can build a new DSN.

Use connection string You can build the connection string here by clicking on the ‘Build’

button. This will bring up a Wizard and guide you along.

Authentication This lets you enter Authentication information like the User Name and

Password.

146
RecordSource Here you can specify the method of creating the Recordset. That is, you can

indicate the Command Type (adCmdUnknown or adCmdText or adCmdTable, or

adCmdStoredProc)

Updating the data in the Data Source

There are two approaches that ADO uses to add or modify the data in the database

1. Changes made to the data or the rows are made in the ‘copy buffer’ and not directly to the

Recordset. If the changes are acceptable then they are applied to the Recordset.

2. Changes are made directly to the data source either immediately or in a batch mode. These

modes are governed by the CursorLocation and LockType properties. Changes will made

to the data source in the immediate mode as soon as soon as you confirm an update.

If your application has transactions that update more than one table it is a good idea to use

‘transaction’ method.

There are three transaction methods are involved. They are,

BeginTrans : To be invoked when you start working on the Recordset. This method

begins a new transaction. Once the BeginTrans method has been invoked, the OLEDB

provider will not continuously commit the changes made to the data source unless you call

CommitTrans/RollbackTrans.

CommitTrans : To be invoked when you want to commit the changes to the data source.

It saves any changes made to the Recordset and ends the current transactions.

RollbackTrans : To be invoked to cancel any changes made within the current

transactions. This method also ends the current transaction.

The CommitTrans and RollbackTrans may also start a new transaction.

147
What is a Cursor?

It is a pointer that point to the data. A temporary, read-only table that saves the results of

the query with an assigned name. The cursor is like a result set, but the actual data is on

the server. You can create a cursor by copying the data from the server to the client. The

cursor is available for browsing, reporting or other uses until it is closed.

Chapter : 15

Crystal and Data Reports

Crystal Reports Crystal Reports is a third party product developed by Seagate of

Singapore. It has been bundled with various data access tools. It can work with Visual Basic on

your PC.

Prerequisites for working with Crystal reports

Hardware A printer must be installed. It need not be physically connected though. This is
because Crystal Reports builds the reports based on the properties of the printer.

Application You can access Crystal Reports only through the VB IDE. If Crystal report has not
been installed then follow the steps given below. Prepare a pencil copy of the report structure
that you want to create.

Installation So, Crystal Reports has been installed and you have a rough ‘copy’ of the report
that you want.

148
Creating a Report through a Wizard

You are presented with the Create New Report Wizard that will allow you to create

new reports. You can choose the report style. For this exercise, click on Standard.

The wizard in the dialog box will ask you to select the database(s) that you will be using

to generate the report. Let us select Nwind.mdb for a change. (You will be generating your own

reports using the Invoice.mdb). Upon selecting the Nwind.mdb, all the tables and stored

queries/view will get added to the ListBox. After you have added all the databases that you

want to work on click on ‘Done’.

If you think there are too many tables and views and you do not need all of them, then

you can delete some of them. Click on the button ‘Back’.

You can select the items that you do not need and click on remove to remove them one

by one. When you are sure you have only those tables that you need click Next to continue.

You will see the figure with the selected tables and their relationship. Click Next to continue.

You can add the fields that you wish to include in your report. The fields that you select

here will appear on the report. However the selection criteria for the selected records need not

149
depend on these fields alone. When you have selected the fields and added them one by one in

the ‘Report fields’ ListBox. Click on Next to continue.

You can choose the fields on which the report is to be sorted out. For example, you can

sort all the details based on the City, or the Product that a customer uses, or the Turnover of the

company, etc. Select the fields on which the criteria are to be built and then select the sort

order. For example, you can sort the details in the ascending order or descending order. When

you are through with this click Next to continue.

Select the fields on which you have to perform calculations like group total, sub-total,

etc. For example if you want to know the number of customers in a particular city, then select

Customer-City and add it to the “Total Fields’ ListBox. Here you can also choose if you want

to total the number of customers for a city or if you want to the add the figures for a particular

column. For our example choose Count. Then Click Next to continue.

Choose the fields based on which the records must be selected from the database. In the

Report Fields ListBox you are presented with the fields that you have selected for the report. If

none of these fields meet your requirements to determine the selection criteria, you can scroll

down further and select from the fields that have not been included in the report. Build your

selection criteria and click Next to continue.

Select the layout of the report. Select the report layout style that you think suits you best.

The selection of the style will depend upon the type of data that you are likely to have on the

report. Next you preview the report.

Data Reports:
The Data Report Designer is not part of your toolbox. To add it to your toolbox, right click on
the toolbox and select Components form the pop-up menu. On the Component dialog box, click on the
‘Designers’ tab and select ‘Data Report’. Close this dialog box.

150
The Data Report Designer is the form on which you design the layout of the
report. The DataReport object is the programmable object that represents the Data Report
Designer.
Click on ‘Projects’ In this menu you will see a new item ‘Add Data Report’. Select this
item to add a Data Report Designer to your IDE. Please remember that this designer will not be
placed on your form. The Data Report Designer is a separate from by itself. Open the Project
Explorer abd you will see another item called DataReport along with the Form1. Also notice
that your toolbox has acquired a tab called DataReport with its own set of tools.

Parts of the Data Report :


The Data Report consists of three main components.
* Data Report object
* Section object
* Data Report Controls.
You need a form or the area where you arrange the carious field that you want to display. This
is the Visual Designer component of the DataReport object. The designer component can be
controlled programmatically using the DataReport object.
The Data Report Designer consists of a number of Sections like the header, footer, and
details sections. Each of these Section objects can be configured at design time or controlled
through code at run time. Each section has a set of propertie4s that can be manipulated.
Finally you have the DataReport controls, which are special control tht you can create on the
Data Report designer. These tools are placed under a separate tab on your toolbox.

The default Data Report designer contains these Sections


 Report Header : Your give the title of the report in this section. If the first page if the
report should contain only the title, then set its ForcePageBreak property to
rptPageBreakAfter.
 Page Header : You give the page heading here.
 Group Header/Footer : You give the heading for every group here. For Example your
report can contain details of Customer for each city here. So the Group Header can be
the name of the city. A group header must also have a group Footer.
 Details : this section contains the actual data. The records are displayed in this section.
 Page Footer: You give the page footer here. This can be the page number or any
relevant text like the date of report, etc.
 Report Footer: You give the summary for the reporting this section. This can contain
the address, the bibliography, contact address, etc. the Report Footer appears between
the last Page Header and Page Footer.

151
Data Report Controls:
Following are the new set of controls that are the placed under the Data Report tab on your
toolbox.
 TextBox Control (RptTextBox)- To Display text or other formatted data.
 Label Control (RptLabel)-To display the labels on the report to identify fields or
sections.
 Image Control (RptImage)-to display pictures on the report. This control cannot be tied
to data field.
 Line Control (RptShape)-To draw lines on the report.
 Shape Control (RptShape)-To draw rectangles, Circles, etc on the report.
 Function Control (RptFunction)-This is a special text box that calculates values as the
report is generated.
Extracting the Data:
We saw earlier in this session that we must first create a data source using ADO. Let us
do that now. We will use our Invoice.mdb. Let us create list that consist of CustomerName,
Customer_City and Order_Value. We need to work with two tables
Dim adcon As ADODB.Connectiion
Dim adors As ADODB.Recordset
In the above code fragment we have declared ADO connection and an ADO Recordset object.
In the Form load event add code to create the connection and then to create recordset.
The following lines of coed will do trick
Set adocon = New ADOB.Connection
Adocon.Open “DSN=Invoice”
In the form load event itself you can populate the recordset. But this is no such a good
idea. If you are not going to view/display the report then recordset is unnecessarily taking up
memory. In order to avoid this add a button to your form. Let the caption be “Display”. In the
code window of this CommonButtuon, event the following code.
Set adors = adocon.Execute (“Select distinct row Customer_data.customer_name,
Customer_data.address2, order_data.ordervalue from Customer_data, orders_data where
Customer_data.Customer_code = orders_data.customercode”)

The above code segment will populate the Recordset.


We now have data readily available. The Recordset will have all the fields from both the
tables. Next we have to display the fields that the user is supposed to view.
Working with the Data Report :
In the details section of the Data Report designer, add three of the RprTextBox controls.
Notice that it is just like adding ordinary textbox controls. Also observe that these textboxes
contain a caption called ‘Unbound’. This means that these RptTextBox controls are not button
to any data source to data field.

152
Building the RptTextBox to a data field: Bring up the Properties window of the
RptTextBox by pressing F4. Enter the name of the field that you want to display against the
Data Field property.
For our example, the three RptTextBox controls will display the “Customer Name”,
“Customer City”, “Order Value”. Enter these field names as they are in the database, if they are
wrongly spelt you will get an error message.
Your Data Report designer will look like the figure in the next page.
Displaying the report :
We are now ready to display the data. We have created the recordset. We have assigned
the fields in the Data Report Designer. We need to link the recordsource to the Data Report.
Then we must call the Show method of the Data Report. The following lines have to be added
to the “Display” command button.
Set DataReport1.DataSource = adors
DataReport1.Show
Run the Program now.
Add headers to the report using the RptLabelBox controls so that the report looks meaningful.

153
Creating Multiple Reports:
The users of your application are not going to be happy with just one report. They will
want the data presented in many and every combination. We can cater to this as well. There are
to ways of handling the ‘multiple reports, situation. For every report that the user wants, we can
create a DaraReport or we can display different data using only one or a few DataReport forms.
Both the approaches have their merits and demerits. We have already created one report using
one DataReport. Creating more reports using the same method should not be very difficult.
However displaying more than one report using only one DataReport involves a little work.
Details like Caption, Page Headers, Footers, etc for each of the reports must be
determined. The heading for the data must also be determined. The data and the source of the
data must also be worked out. Depending upon the number of reports that you may need to
display on a form, you have to work out if it is feasible to create a recordset of a number of
recordsets for all the reports. Creating a recordset every time the user asks for a report may not
be a good idea especially in a multi- user environment. At the same time creating a large umber
of records and locking up resources will not be right thing to do.
Let us use the DataReport1 to create another report. In this report we will display the
Customer Name, Customer Address and the Order Value. Add another button to the form. We
can give an appropriate caption. In the code window of the button, add the following code.
‘Creating the Recordset
set adors = adcon.Execute(“Select distinctrow Customer_data.customer_name,
Customer_data.address2, orders_data.ordervalue from Customer_data, orders_data where
Customer_data.Customer_code = orders_data.customerid”)
set DataReport1.DataSource = adors
‘ Assigning the captions for the labelbox controls. These will be the column headers.
DataReport1.Sections(2).Controls(“Label2”).Caption = “Customer Name”
DataReport1.Sections(2).Controls(“Label3”).Caption = “Address”
DataReport1.Sections(2).Controls(“Label4”).Caption = “Order Value”
‘Assigning the values to the textbox controls in the details section.
DataReport1.Sections(3).Controls(“Text3”).DataField= “OrderValue”
DataReport1.Sections(3).Controls(“Text2”).DataField= “address2”
DataReport1.Sections(3).Controls(“Text1”).DataField= “Customer_name”
‘The Function1 will add the total of ordervalue.
DataReport1.Sections(5).Controls(“Function1”).DataField= “OrderValue”
DataReport1.Show
The value for column headers are given during runtime. The data has to be displayed is
also specified at runtime. In this way we can create multiple reports using one DataReport
designer.

154
Chapter : 16
ActiveX
What is ActiveX?
Why ActiveX?
The concept of ActiveX was developed for very simple reasons.
To be able to make changes in the imported data such that the data in the parent
application was also updated.
To be able to place different types of data or ‘objects’ in one document.
The technology was DDE or Dynamic Data Exchange.
This technology allowed application to exchange data.
It also allowed one application to send commands to the other application.
Next came OLE, an acronym for Object Linking and Embedding.
Under this technology, one document could display an object from different
applications.
The advantage of this technology was that no conversion of data was done from one
application to another.
Programmers who work in the C language are very found of using the term ‘function’.
OLE 2. The Next Step
OLE 1.0 did not succeed because of various limitations.
The need was for a document to load and save an object that it did not know about.
The application should provide an interface to edit objects that it contains.
To support drag-and-drop of objects that it does not know about.
To execute commands on objects belonging to unknown applications.

Microsoft came up with some specifications on Objects and how they should be
handled. The specifications are as under, and are COM specifications. COM stands for
Component Object Model, the new buzzword in computers.
1. A common method for applications to exchange objects.
2. A method to identify an object and relate an object with applications that can manipulate
it.
3. A standard set of error codes and an error-reporting and responding system.
4. A system to invoke an object. Check if it is in use, and delete it if it is not in use. This
ensures that memory resources are not blocked.
5. A set of rules for applications to access and manipulate objects.
An application that accepts or requests an object is called as the client or container.
The application that provides an object is called the Server.
Rule 1: Word must know how to accept the spreadsheet from Excel.

155
Rule 2: If the user double-click on the spreadsheet, Word (or the system)
must be able to identify the object and invoke Excel.

Rule 3: In case of an error like Excel being corrupted or “This


Application has performed….’ Error, both the applications must
be notified. A copy of the FIR is to be sent to the MLA!
Rule 4: Once the modifications have been completed on the object, the
instance of Excel must be closed. This will ensure that resources
are not blocked.
Rule 5: This ensure that the spreadsheet is presented as a spreadsheet,
and that the rules for presenting spreadsheet data are followed.
Let us take a look at some of the properties of ActiveX controls.
Any control or object has
Properties : Like BackColour, Font, Resize, Paint, etc.
Events : Click, MouseMove, KeyPress, LostFocus, etc.
Methods : The code associated with the control.

ActiveX and Web Pages


ActiveX and Internet
ActiveX Documents go well with the Microsoft’s strategy for the internet.
The internet is a collection of computers that are wired together and talk in TCP/IP.
The World Wide Web is a collection of documents that are linked together. The documents are
viewed by the users in the form of Pages. The Pages will have topics that are linked to other
topics and so forth. These pages are read by what is called as Internet Browsers. The browsers
understand a language called HTML’ or HyperText Markup Language.
All pages that have to be placed on the web have to be created using this language.
ActiveX Controls can be added to Web Pages to improve the functionality of the Page. An
ActiveX control can be loaded on the page to play a movie clip .avi file or to present a form.
Microsoft has provided a new tool to simplify the addition of ActiveX controls to a Page. This
tool is called Microsoft ActiveX Control Pad.
An HTML page begins with a tag <HTML>. This tag tells the browser that the file is
an HTML file, and hence must be treated with respect.
An HTML page can contain text with different styles. Each style for the sake of (our)
convenience can be called a Para. Each Para is preceded by a tag and ends with a tag. A tag is a
bit of text that tells the browser how the following text has to be read and displayed.
The ending tag for a Para will tell the browser that the Para has come to an end the
next definition if any will begin with the next tag. The HEAD section includes the tile pf the

156
page and the name of the creator of this page, etc. The BODY section is where most of the
action is. You can add text here or pictures, or other controls.

Some definitions are here for you:


HTTP: Hypertext Transfer Protocol. This protocol is used to transfer pages
from the server to the client.
Server: The computer that has the pages that you requested.
Client: Your computer that has made the requested.
URL: Uniform Resource Locator. This contains the information needed to locate the page
that you want. An URL has
 The Protocol
 The Server name
 The Pathname of the file in the server’s directory
 Page Name, the name of the file that has the page
 Page Number#, the page number which hold the text that you want.
ActiveX Documents
An ActiveX document is Visual Basic Program (with the various controls) that can be
read and displayed by a browser.
Now how do we go about creating an ActiveX Document?
Start Visual Basic.
Select ActiveX Document Exe from the opening menu.
You will see a form called the UserDocument1. It will look similar to the regular Visual
Basic form.
From the Toolbox paste the controls to arrive the following picture.
You are welcome to make it look different.
Add the following code to User Document_ Initialize ( )
Private Sub UserDocument _ Initialize( )
Dim db As Database
Dim db As Recordset
‘open the database
Set db = OpenDatabase (App.Path & “\ Car Finance.mdb”)
Set datal = db. OpenRecordset (‘Schemes”)
‘the following code will populate the grid
Gridl.Rows = 11
Gridl.Cols = 7
Gridl . Colwidth (0) = Gridl . Width * 0.14
Gridl . ColWidth (1) = Gridl . Width * 0.163

157
Gridl . ColWidth (2) = Gridl . Width * 0.16
Gridl . ColWidth (3) = Gridl . Width * 0.16
Gridl . ColWidth (4) = Gridl . Width * 0.17
Gridl . ColWidth (5) = Gridl . Width * 0.07
Gridl . ColWidth (6) = Gridl . Width * 0.1
If datal . RecordCount > 0 Then datal . MoveFirst
i=1
Do While Not datal . EOF
Grid1.Row = i
Grid1.TextMatrix(i,0) = data1!carname
Grid1.TextMatrix(i,1) = data1!company
Grid1.TextMatrix(i,2) = Format(data1!sellingprice,
”###, ###, ##0.00”) & “ Rs.”
Grid1.TextMatrix(i,3) = Format(data1!inipayment,
”###, ###, ###0.00”) & “ Rs.”
Grid1.TextMatrix(i,4) = Format(data1!ms,
”###, ###, ##0.00”) & “ Rs.”
Grid1.TextMatrix(i,5) = data1!months
Grid1.TextMatrix(i,6) = data1!interest & “%P.A.”
Data1.MoveNext
i = i+1
Loop
If data1.RecordCount > 0 Then data1. MoveFirst
Combo1. Clear
Do While Not data1.EOF
If Not IsNull(data1.carname) Then Combo1.AddItem data1!carname
data1.MoveNext
Loop
Data1.Close
Db. Close
SSFrame1.visible = False
End Sub
In the Click Event of the Application Form Command Button add the following code:
Private Sub SSCommand3_Click()
SSFrame1.visible = False
End Sub

The Application Form Document


Create the document using SSFrame and Paste it in the same document.
158
In the Click Event accept Command Button Add the Following Code
Private Sub SSCommand2_Click( )
Dim db As Database
Dim datal As Recordset
Set db = OpenDatabase (App.path & “\CarFinance.mdb”)
Set datal = db . OpenRecordset (“ ApplicationForm”)

‘Storing the information in to our database


datal . Index = “AppIndex”
datal . Seek “=”, Trim (Textl (1) . Text)
If Not datal . NoMatch Then
Datal. Edit
Else
datal . Edit
Else
Datal . AddNew End If
datal ! ClientName = Text1 (1) . Text
datal ! address = Text1(2) . Text
datal ! phone = Text1(3) . Text
datal ! schemewanted = Text (4) . Text
datal ! schemewanted = Trim ( Combol . Text)
datal . Update
datal . Close
db . Close
End Sub.

In the Home Command Button, add the following code:


Private Sub SSCommand3_ Click ( )
SSFramel . Visible = False
End Sub

====================================================================

159

You might also like