Visual Programming 1
Visual Programming 1
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).
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
10
FORMAT MENU DEBUG 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
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.
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.
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:
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)
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:
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.
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,
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.
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.
(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.
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
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.
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.
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.
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.
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.
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
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,
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.
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
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.
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
Example
ChDrive “A”
This will change the drive to “A”
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”.
Example
MkDir “C: \ EMSQUARE\ Expermnt”
This will create a directory ‘expermnt’ under ‘c:\ EMSQUARE’.
Example
RmDir “C: \ Temp\ Temp1”
This will delete the directory ‘Temp1’ which is a sub-directory of ‘c:\ Temp’’.
Example
Kill “testdoc” -- to delete the file ‘testdoc’.
Kill “*.Doc” -- to delete all the “*.Doc” files in the current directory.
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.
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:
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:
(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.
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’
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.
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
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.
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
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.
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.
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.
81
(4) To control the program, always refer to the active form and maintain the information on the
child form.
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.
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.
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
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
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.
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
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
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 ()
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
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.
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.
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.
---------------------------------------------------------------------------------------------------------------------------
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.
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.
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.
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
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.
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
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.
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.
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.
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.
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.
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
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]*
124
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.
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.
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.
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:
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.
136
“Display the record that meets the search criteria.
Showfields
End Sub
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
Chapter : 14
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
OLE DB has what it calls ‘providers’ which let you access the different data sources. For
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
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,
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
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
The Recordset is the primary means of examining and modifying data in the rows.
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
141
Error Errors can occur at any time in your application, due to the data source being corrupted
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
Collection The objects in the collection can be retrieved with a collection method, either by
The command object has the Parameters collection, which contains all Parameter objects
The Recordset object has the Fields collection, which contains all Field objects that
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
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.
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
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).
143
Using the Data Source Name in Our Project
Dim rs As Recordset
The first line declares and sets ‘adocon’ as an ADODB connection object. You cam
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 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,
set rs = comd.Execute
Add a command button to your form. Add the following lines of code to its click-event.
144
Private Sub Command1-Click( )
rs. MoveFirst
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.
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
145
The Property Pages of ADODC contain four tabs. They allow you to set the various
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
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’
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
adCmdStoredProc)
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.
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.
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
Chapter : 15
Singapore. It has been bundled with various data access tools. It can work with Visual Basic on
your PC.
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
If you think there are too many tables and views and you do not need all of them, then
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
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
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
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
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.
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”)
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.
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.
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
====================================================================
159