Вы находитесь на странице: 1из 112

VISUAL BASIC

VISUAL BASIC
1. INTRODUCTION TO VISUAL BASIC................................................................ 3
1.1 What is Visual Basic? ............................................................................................................... 3
1.2 Working With Visual Basic....................................................................................................... 5
1.3 Starting Visual Basic................................................................................................................. 5
1.4 Designing an Effective USER interface ..................................................................................... 9
1.5 Defining properties ................................................................................................................. 10

2. PROGARMMING IN VB ....................................................................................14
2.1 General Terms used in VB ...................................................................................................... 14
2.2 Variables ................................................................................................................................ 15
2.3 Programming Fundamentals.................................................................................................... 15
2.4 Working with Procedures........................................................................................................ 17
2.5 Setting and Retrieving Properties ............................................................................................ 20
2.6 Controls on Other Forms......................................................................................................... 21

3. INTRODUCTION TO BOUND CONTROLS ......................................................23


3.1 Introduction ............................................................................................................................ 23
3.2 Data Control ........................................................................................................................... 23
3.3 TYPES OF CONTROL........................................................................................................... 23

4. DATABASE CONNECTIONS ............................................................................31


4.1 Database ................................................................................................................................. 31
4.2 Creating Recordsets ................................................................................................................ 32
4.3 Selecting Records ................................................................................................................... 34
4.4 Positioning the Current Record in a Recordset ......................................................................... 34
4.5 Using Recordsets to Manipulate Data ...................................................................................... 36
4.6 Using QueryDef Variables ...................................................................................................... 36
4.7 Data Control and Bound Controls............................................................................................ 37
4.8 Programming with the Data Control ........................................................................................ 38
4.9 Using SQL.............................................................................................................................. 42

5. QUERIES.............................................................................................................46
5.1 Select Queries........................................................................................................................ 46
5.2 Cross Tab Queries................................................................................................................... 48
5.3 Action Queries........................................................................................................................ 48
5.4 SQL Queries ........................................................................................................................... 50
5.5 Relationships .......................................................................................................................... 51
5.6 Querying a Database ............................................................................................................... 52

6. MENUS AND DIALOG BOXES .........................................................................54


6.1 Menus .................................................................................................................................... 54
6.2 Dialog boxes........................................................................................................................... 58

7. VISUAL BASIC REPORT ...................................................................................60


7.1 Definition ............................................................................................................................... 60
7.2 Using Crystal reports .............................................................................................................. 60
7.3 VB code by using Printer object & Print form method. .......................................................... 69
7.4 Sample Programs and reports .................................................................................................. 79

8. ADVANCED PROGRAMMING IN VISUAL BASIC.........................................82


8.1 Multiple Document Interface................................................................................................... 82
8.2 Object Linking/ Embedding (OLE) ......................................................................................... 86
8.3 Active X Designers................................................................................................................. 89
8.4 Debugging and Error Handling................................................................................................ 92

9. ADVANCED TOOLS IN VB...............................................................................98


9.1 Active X Control..................................................................................................................... 98
9.2 Using The MSCHART Control ............................................................................................... 98

VISUAL BASIC
9.3 Using The Multimedia MCI Control...................................................................................... 102
9.4 Using Animation Control ...................................................................................................... 105
9.5 Using Status Bar Control....................................................................................................... 106

10. VB EXERCISE ................................................................................................111

VISUAL BASIC

1.

INTRODUCTION TO VISUAL BASIC

1.1 What is Visual Basic?


Microsoft Visual Basic is the fastest and easiest way to create applications for Microsoft Windows.
Whether you are an experienced professional or brand new to Windows programming, Visual Basic
provides you with a complete set of tools to simplify rapid application development.
The "Visual" part refers to the method used to create the graphical user interface (GUI). Rather than
writing numerous lines of code to describe the appearance and location of interface elements, you
simply drag and drop prebuilt objects into place on screen. If you've ever used a drawing program such
as Paint, you already have most of the skills necessary to create an effective user interface.
The "Basic" part refers to the BASIC (Beginners All-Purpose Symbolic Instruction Code) 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 now contains several hundred statements,
functions, and keywords, many of which relate directly to the Windows GUI. Beginners can create
useful applications by learning just a few of the keywords, yet the power of the language allows
professionals to accomplish anything that can be accomplished using any other Windows programming
language.

1.1.1 Visual Basic Versions


Visual Basic is available in three versions, each geared to meet a specific set of development
requirements.

The Visual Basic Learning edition allows programmers to easily create powerful applications
for Microsoft Windows 95 and Windows NT. It includes all intrinsic controls, plus 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..

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.
Before you install Visual Basic, make sure that your computer meets the minimum requirements, and
read the Readme file, located at the root directory on your installation disk.

1.1.2 Hardware and System Requirements


To run Visual Basic, you must have certain hardware and software installed on your computer. The
system requirements include:
Microsoft Windows NT 3.51 or later, or Microsoft Windows 95.
80486 or higher microprocessor.
A hard disk with a minimum of 50 megabytes available space for a full installation.
A CD-ROM disc drive.
VGA or higher-resolution screen supported by Microsoft Windows.
16 MB of RAM.
A mouse or other suitable pointing device.

1.1.3 Structure of a VB project


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 you set. This information is updated every time you save the
project. All of the files and objects can be shared by other projects as well.

VISUAL BASIC
When you have completed all the files for a project, you can convert the project into an executable file
(.exe): From the File menu, choose the Make project.exe command.
Each time you save a project, Visual Basic updates the project file (.vbp). A project file contains the
same list of files that appears in the Project Explorer window.
You can open an existing project file by double-clicking its icon, by choosing the Open Project
command from the File menu, or by dragging the file and dropping it on the Project Explorer window.
A project consists of:
One project file that keeps track of all the components (.vbp).
One file for each form (.frm).
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.
Optionally, one file for each class module (.cls).
Optionally, one file for each standard module (.bas).
Optionally, one or more files containing ActiveX controls (.ocx).
Optionally, a single resource file (.res).
As you create, add, or remove editable files from a project, Visual Basic reflects your changes in the
Project Explorer window, which contains a current list of the files in the project. The Project Explorer
window in Figure 1.3 shows some of the types of files you can include in a Visual Basic project.

Figure 1.3 The Project Explorer window


The following sections describe the different types of files and objects that you can include in a
project.
Form Modules
Form modules (.frm file name extension) can contain textual descriptions of the form and its controls,
including their property settings. They can also contain form-level declarations of constants, variables,
and external procedures; event procedures; and general procedures.
Class Modules
Class modules (.cls file name extension) are similar to form modules, except that they have no visible
user interface. You can use class modules to create your own objects, including code for methods and
properties.
Standard Modules
Standard modules (.bas file name extension) can contain public or module-level declarations of types,
constants, variables, external procedures, and public procedures.

VISUAL BASIC
1.1.4 Resource Files
Resource files (.res file name extension) contain bitmaps, text strings, and other data that you can
change without having to re-edit your code. For example, if you plan to localize your application in a
foreign language, you can keep all of the user-interface text strings and bitmaps in a resource file,
which you can then localize instead of the entire application. A project can contain no more than one
resource file.

1.1.5 Components
In addition to files and modules, several other types of components can be added to the project.
ActiveX Controls
ActiveX controls (.ocx file name extension) are optional controls which can be added to the toolbox
and used on forms. When you install Visual Basic, the files containing the controls included with
Visual Basic are copied to a common directory (the \Windows\System subdirectory under Windows
95). Additional ActiveX controls are available from a wide variety of sources. You can also create your
own controls using the Professional or Enterprise editions of Visual Basic.
Insertable Objects
Insertable objects, such as a Microsoft Excel Worksheet object, are components you can use as
building blocks to build integrated solutions. An integrated solution can contable of tain data in
different formats, such as spreadsheets, bitmaps, and text, which were all created by different
applications.

1.2 Working With Visual Basic


The working environment in Visual Basic is often referred to as the integrated development
environment or IDE because it integrates many different functions such as design, editing, compiling,
and debugging within a common environment. In most traditional development tools, each of these
functions would operate as a separate program, each with its own interface.

1.3 Starting Visual Basic


Visual Basic can be started either from the start menu or by creating a short cut to Visual Basic on the
desk top. When you run the Visual Basic Setup program, it allows you to place the program items in an
existing program group or create a new program group and new program items for Visual Basic in
Windows. You are then ready to start Visual Basic from Windows.

1.3.1 Starting Screen


To start Visual Basic from Windows
1.
Click Start on the Task bar
2.
Select Programs, and then Visual Basic 5.0.

or

Click Start on the Task bar.


Select Programs.
Use the Windows Explorer to find the Visual Basic executable file (VB5.exe).
Double-click the Visual Basic icon.
3.
You can also create a shortcut to Visual Basic, and double-click the shortcut.
When you first start Visual Basic, you see the interface of the integrated development environment, as
shown in Figure 2.1.
Figure 2.1 The Visual Basic integrated development environment

VISUAL BASIC

Once you start the Visual Basic, the development environment includes a variety of overlapping
windows. At the top of the screen is the title bar.

1.3.2 Creating the Interface


Forms are the foundation for creating the interface of an application. You can use forms to add
windows and dialog boxes to your application. You can also use them as containers for items that are
not a visible part of the application's interface. For example, you might have a form in your application
that serves as a container for graphics that you plan to display in other forms.
There are three main steps to creating an application in Visual Basic:
1. Create the interface.
2. Set properties.
3. Write code.

1.3.3 Menu Bar


The menu bar is a a row of buttons that make up the toolbar. They are designed to give ways to
perform specific operations. The position and size indicators are designed to help the user in arranging
the objects of a project.
The first step in building a Visual Basic application is to create the forms that will be the basis for your
application's interface. Then you draw the objects that make up the interface on the forms you create.
For this first application, you'll use two controls from the Toolbox.

VISUAL BASIC

1.3.4 Tool Box


Tool box is a collection of buttons, representing the controls that can be included in the

programs. The number of controls displayed in the tool box depends on the version of Visual Basic.
But the most commonly used controls are Label, Text box, Picture box, list box, combo box, check
button, radio button etc.,

CheckBox
A CheckBox control displays an X when selected; the X disappears when the CheckBox is cleared. Use
this control to give the user a True/False or Yes/No option. You can use CheckBox controls in
groups to display multiple choices from which the user can select one or more. You can also set
the value of a CheckBox programmatically with the Value property.
ComboBox
A ComboBox control combines the features of a TextBox control and a ListBox controlusers can
enter information in the text box portion or select an item from the list box portion of the control.
CommandButton
Use a CommandButton control to begin, interrupt, or end a process. When chosen, a CommandButton
appears pushed in and so is sometimes called a push button.

Data control
Provides access to data stored in databases using any one of three types of Recordset objects. The
Data control enables you to move from record to record and to display and manipulate data from
the records in bound controls. Without a Data control or an equivalent data source control like the
RemoteData control, data-aware (bound) controls on a form can't automatically access data.
DirListBox
A DirListBox control displays directories and paths at run time. Use this control to display a
hierarchical list of directories. You can create dialog boxes that, for example, enable a user to open
a file from a list of files in all available directories.

VISUAL BASIC
DriveListBox
A DriveListBox control enables a user to select a valid disk drive at run time. Use this control to
display a list of all the valid drives in a user's system. You can create dialog boxes that enable the
user to open a file from a list of files on a disk in any available drive.
FileListBox
A FileListBox control locates and lists files in the directory specified by the Path property at run
time. Use this control to display a list of files selected by file type. You can create dialog boxes in
your application that, for example, enable the user to select a file or group of files.
Frame
A Frame control provides an identifiable grouping for controls. You can also use a Frame to
subdivide a form functionallyfor example, to separate groups of OptionButton controls.
Scroll bars
Scroll bars provide easy navigation through a long list of items or a large amount of information.
They can also provide an analog representation of current position. You can use a scroll bar as an
input device or indicator of speed or quantityfor example, to control the volume of a computer
game or to view the time elapsed in a timed process.
Image control
Use the Image control to display a graphic. An Image control can display a graphic from a bitmap,
icon, or metafile, as well as enhanced metafile, JPEG, or GIF files.
Label control
A Label control is a graphical control you can use to display text that a user can't change directly.
Line control
A Line control is a graphical control displayed as a horizontal, vertical, or diagonal line.
ListBox
A ListBox control displays a list of items from which the user can select one or more. If the
number of items exceeds the number that can be displayed, a scroll bar is automatically added to
the ListBox control.
If no item is selected, the ListIndex property value is -1. The first item in the list is ListIndex 0,
and the value of the ListCount property is always one more than the largest ListIndex value.
Menu control
A Menu control displays a custom menu for your application. A menu can include commands,
submenus, and separator bars. Each menu you create can have up to four levels of submenus.
OptionButton control
An OptionButton control displays an option that can be turned on or off.
PictureBox control
A PictureBox control can display a graphic from a bitmap, icon, or metafile, as well as enhanced
metafile, JPEG, or GIF files. It clips the graphic if the control isn't large enough to display the
entire image
Shape control
The Shape control is a graphical control displayed as a rectangle, square, oval, circle, rounded
rectangle, or rounded square.
TextBox control

VISUAL BASIC
A TextBox control, sometimes called an edit field or edit control, displays information entered at
design time, entered by the user, or assigned to the control in code at run time.
Timer control
A Timer control can execute code at regular intervals by causing a Timer event to occur.

1.3.5 Forms in a Project


Placing Control on a form
Controls can be placed in a form by selecting controls from the tool box and by positioning it on the
appropriate position in the form.
Running a Program
Once a form is created, you can execute it even before writing the program by clicking the start button
or by the Start command in the Run menu. This helps the user in exploring the behavior of the controls
placed in the form.
Properties Window
After the controls were placed in the required order, user can set the properties of these controls by
selecting the Properties icon from the tool bar or by selecting the properties from the view menu.
Properties determine the appearance and behavior of individual controls and forms in the applications.
In the properties window, the column on the left contains the names of all the properties that applies to
a selected object, and the right column shows the setting for each property.
Project window
The Project window provides a list of the files in the current program/application. Each program
contains one project window, which is sorted on disk with a default extension name of MAK/VBP
depending on the version of VB. To view the project window user can click on the Project icon in the
tool bar or select from the menu. The forms in a project are saved as FRM files. There can be more
than one FRM files in a project. There will also be Module file (.BAS) and control files (VBX) in a
Project file created in VB.
Writing Code
The event procedures for the controls on a particular form is saved as part of the FRM file (Form file)
for writing the code, user an either double click on the controls in a form or view it in the Code view.

1.4 Designing an Effective USER interface


An interface includes all the visual objects and procedural techniques that define a programs
interaction with the user. In the VB environment user can create programs interface by dragging the
controls into a form and arranging them in place. The Tool Box provides an assortment of controls that
meet particular requirements in a programs design. These controls are designed so that a user can
learn to operate them almost without any instruction.

1.4.1 Adding Controls to the form


The first step in creating the program window is to reposition and resize the form window itself to suit
the programs design. User may decrease or increase the dimensions of the form and appropriately
centre it o the desktop. Once the form window is set to the required dimensions, user may add controls
to it by selecting from the tool box and dragging it to the form.

1.4.2 Adjusting the form design grid


Visual Basics standard form grid can be changed by setting the values of grid width, height etc., in the
Options/Environment menu. To make the grid visible select yes for Show Grid option.

VISUAL BASIC

1.5 Defining properties


All controls, command button, text box, label, option button has its own list of properties that apply
specifically to the objects design. The properties determine how the program behaves in run time, and
its quality of interaction with the user. These properties include keyboard shortcut sequences for
command button, order of items arranged in a list, focus in response to tab keys, a control is active or
inactive, visible or not etc.. Some of the properties used by forms and controls are listed below:
Appearance property
Returns or sets the paint style of controls on an MDIForm or Form object at design time. Readonly at run time.
BackColor, ForeColor Properties
BackColor returns or sets the background color of an object.
ForeColor returns or sets the foreground color used to display text and graphics in an object.
Container Property
Returns or sets the container of a control on a Form. Not available at design time.
DataChanged Property
Returns or sets a value indicating that the data in the bound control has been changed by some
process other than that of retrieving data from the current record. Not available at design time.
DataField Property
Returns or sets a value that binds a control to a field in the current record
DragIcon Property
Returns or sets the icon to be displayed as the pointer in a drag-and-drop operation.

DragMode Property
Returns or sets a value that determines whether manual or automatic drag mode is used for a dragand-drop operation.

Enabled Property
Returns or sets a value that determines whether a form or control can respond to user-generated
events.
Font Property
Returns a Font object.
FontBold, FontItalic, FontStrikethru, FontUnderline Properties
Return or set font styles in the following formats: Bold, Italic, Strikethru, and Underline
FontName Property

10

VISUAL BASIC
Returns or sets the font used to display text in a control or in a run-time drawing or printing
operation.

Note The FontName property is included for use with the CommonDialog control and for
compatibility with earlier versions of Visual Basic. For additional functionality, use the new Font
object properties (not available for the CommonDialog control).

FontSize Property
Returns or sets the size of the font to be used for text displayed in a control or in a run-time
drawing or printing operation.

Note
The FontSize property is included for use with the CommonDialog control and for
compatibility with earlier versions of Visual Basic. For additional functionality, use the new Font
object properties (not available for the CommonDialog control).

Height, Width Properties


Return or set the dimensions of an object or the width of the Columns object of a DBGrid control.
For the Printer and Screen objects, not available at design time.

HelpContextID Property
Returns or sets an associated context number for an object. Used to provide context-sensitive Help
for your application.

hWnd Property
Returns a handle to a form or control.

Note This property is not supported for the OLE container control.

Index Property (Control Array)


Returns or sets the number that uniquely identifies a control in a control array. Available only if
the control is part of a control array.

IntegralHeight Property
Returns or sets a value indicating if the control displays partial items. Read-only at run time.
ItemData Property
Returns or sets a specific number for each item in a ComboBox or ListBox control.

11

VISUAL BASIC
Left, Top Properties
Left returns or sets the distance between the internal left edge of an object and the left edge of
its container.
Top returns or sets the distance between the internal top edge of an object and the top edge of
its container.
List Property
Returns or sets the items contained in a control's list portion. The list is a string array in which each
element is a list item. Available at design time for ListBox and ComboBox controls through the
property browser; read-only at run time for DirListBox, DriveListBox, and FileListBox controls;
read/write at run time for ComboBox and ListBox controls.

ListCount Property
Returns the number of items in the list portion of a control.

Locked Property
Returns or sets a value indicating whether a control can be edited.
MouseIcon Property
Returns or sets a custom mouse icon.
MousePointer Property
Returns or sets a value indicating the type of mouse pointer displayed when the mouse is over a
particular part of an object at run time.
Name Property
Returns the name used in code to identify a form, control, or data access object. Read-only at run
time.
Returns or sets the name of a font object.
NewIndex Property
Returns the index of the item most recently added to a ComboBox or ListBox control. Read only at
run time.

Sorted Property
Returns a value indicating whether the elements of a control are automatically sorted
alphabetically.
Style Property

12

VISUAL BASIC
Returns or sets a value indicating the display type and behavior of the control. Read only at run
time.
TabIndex Property
Returns or sets the tab order of most objects within their parent form.
TabStop Property
Returns or sets a value indicating whether a user can use the TAB key to give the focus to an
object.
Tag Property
Returns or sets an expression that stores any extra data needed for your program. Unlike other
properties, the value of the Tag property isn't used by Visual Basic; you can use this property to
identify objects.
Text Property
ComboBox control (Style property set to 0 [Dropdown Combo] or to 1 [Simple Combo]) and
TextBox control returns or sets the text contained in the edit area.
ComboBox control (Style property set to 2 [Dropdown List]) and ListBox control returns the
selected item in the list box; the value returned is always equivalent to the value returned by the
expression List(ListIndex). Read-only at design time; read-only at run time.
Visible Property
Returns or sets a value indicating whether an object is visible or hidden.

13

VISUAL BASIC

2. PROGARMMING IN VB
2.1 General Terms used in VB
Application

A collection of code and visual elements that work together as a single program.
Developers can build and run applications within the development environment, while
users usually run applications as executable files outside the development
environment.
procedure
A sequence of code statements executed as a unit. The term procedure refers to both
Sub and Function procedures.
procedure level
The location of statements within a Sub or Function procedure.
variable
A named storage location capable of containing a certain type of data that can be
modified during program execution. Each variable has a unique name that identifies
it within its level of scope. Variable names must be limited to 40 characters, must
begin with an alpha character, cannot contain an embedded period, and cannot have
the same scope as a procedure name.
Variable declarations in Visual basic take the form of Dim statements. In one
of its simplest forms, a Dim declaration appears as
Dim variableName As dataType
For Example, the following statements
module variable
A variable declared outside of a procedure (using the Dim statement) and visible in all
procedures in the module.
type-declaration character
A character appended to a variable name indicating the variable's data type. By
default, variables are of type Variant unless a corresponding Deftype statement is
present in the module.
Character
%
&
!
#
@
$

Data Type

Integer
Long
Single
Double
Currency
String

event

14

VISUAL BASIC

An action recognized by an object, such as clicking the mouse or pressing a key, and
for which you can write code to respond. Events can occur as a result of user action
or program code, or they can be triggered by the system.
event procedure
A procedure automatically invoked in response to an event initiated by the user,
program code, or triggered by the system.
2.2 Variables
Data Structures
In a programming language, the word structure has several important meanings. A
structured language encourages a modular approach to writing code, where programs
are organised in to small, self-contained tasks. Visual Basic has all the elements of a
well-structured-language, including a productive variety of data structures and
control structures. These are the topics of this section.
A data structure gives you convenient ways to organise and store information in a
program. Two commonly used data structure in Visual Basic are arrays and userdefined types. A variable belonging to a user-defined type is sometimes known as a
record variable:

An array is a list, a table, or another multidimensional arrangement of data items,


all represented by a single variable name. In programs that works with large
amounts of interrelated information, arrays are an indispensable way of organising
data.
A user-defined type enables you to create record variables that represent multiple
values of different types. This type of structure is ideal for use in database
applications.
A programming language also has control structures that you can use to define the
direction and flow of your program. Control structures include procedures, loops, and
decisions:
procedures allow you to divide your code into small, cogent, usable blocks of
code that are easy to understand and revise if necessary. A sub procedure in
Visual Basic performs a discrete well defined tasks; a functional
2.3 Programming Fundamentals
Visual Basic is a complete programming language that supports the structured
programming constructs found in most other modern programming language. This
section introduces the essential components of the Visual Basic Language.
2.3.1 Structure of a Visual Basic Application
Your application can contain form modules (.FRM) and code modules (.BAS),
as well as custom controls (.VBX). A form module contains the visual elements of a
form, including all the controls on the form and the Basic code. You must have at
least one code or form module. By default, your project contains a single form
module, but you can add additional form and code modules.
15

VISUAL BASIC

How an Event-Driven Application Works

An event is an action recognised by a form or control. Event-driven applications


execute Basic code in response to an event. Each form and control in Visual Basic
has a predefined set of events. If one of these events occurs, Visual Basic invokes the
code in the associated events procedure.
Modules

Simple applications can consist of just a single form, and all of the code in the
application resides in that form module. As your applications get larger and more
sophisticated, you add additional forms. Eventually you find that there is common
code you want to execute in several forms. You cannot invoke procedures in one form
from another, and you dont want to duplicate the code in both forms. So you create a
separate code module containing a procedure that implements the common code, and
then invoke the procedure from each form module.
Each code and form module can contain:

Declarations: You can place constant, type, variable, and DLL procedure
declarations at the module level of form or code modules.

Event procedures: These are Sub procedures that are executed in response to a
user or system event. Event procedures occur only in form modules.

General procedures: These are procedure that are not directly associated with
an event. General procedures in a form module are local to that module; they cant
be invoked from other modules. All the procedures in a code module are general
procedures, and they can be invoked from any code or form module in the
application. General procedures can be either Sub procedure ( procedure that do
not return a value) or Function procedures (procedures that return a value).

Event Procedures

When an object in Visual Basic recognises that an event has occurred, it automatically
invokes that event procedure with the name that corresponds to the event. Because the
name establishes an association between the object and the code, event procedures are
said to be attached to forms and controls.
An event procedure for a control combines the controls actual name
(specified in the Name property), an underscore (_), and the event name. For instance,
if you want a command button named MyButton to invoke an event procedure when it
is clicked, use the procedure MyButton_Click.
An event procedure for a form combines the word Form an underscore, and the
event name. If you want a form to invoke an event procedure when it is clicked, use
the procedure Form_click.
All event procedures use the same general syntax.
Syntax for control event

Syntax for form event

16

VISUAL BASIC

Sub controlname_eventname()
statementblock
End Sub

Sub Form_eventname()
statementblock
End Sub

The words Sub and End Sub mark the beginning and end of the procedure. The
words following Sub are the procedures name, and statementblock is the code you
want executed when the event occurs.
General Procedures

Event procedures are invoked when a particular event occurs on a form or control.
Those event procedures can in turn invoke other procedures. A procedure that is not
invoked when an event occurs is called a general procedure. A general procedure is
not invoked until another part of the application explicitly calls it.
Why create general procedures ? One reason is that several different event procedures
may need the same actions performed. A good programming strategy is to put
common statements in a separate procedure ( a general procedure) and have event
procedures call it. This eliminates the need to duplicate code and also makes
application easier to maintain.
Once you have defined a general procedure in a form module, you can call it from any
of the vent procedure in that form. If you want a general procedure that can be called
from anywhere in your application, you must place it in a code module.
2.4 Working with Procedures
To create a new general procedure, make a Code window the active window. Then
choose New Procedure from the View menu. Another technique is to type a procedure
heading in the Code window and press ENTER. The procedure heading can be as
simple as Sub or Function followed by a name. For example, you can enter either of
the following:
Sub UpdateForm()
Function GetCoord()
Visual Basic responds by clearing the Code window and displaying a template for the
new procedure.
To edit an existing general procedure, select (general) from the Object box in the
Code window, and then select the procedure in the Procedure box.
2.4.1 Procedures
Procedures can be either Sub procedure or Function procedures. Sub procedures do
not return a value, so a call to a Sub procedure is a complete statement. Function
procedures return a value, so a call to a Function procedure is part of an expression.
Event procedures are always Sub procedures, never Function procedures.

17

VISUAL BASIC
2.4.2 Sub Procedures
The syntax for a Sub procedure is:
Sub procedurename (arglist)
statements
End Sub
The arglist is a list of argument names, separated by commas if there is more than
one. Each argument looks like a variable declaration and acts like a variable in the
procedure.
The syntax of each argument is:
[ByVal] variablename [( )] [As type]
ByVal Indicates the argument is passed by value rather than by reference. The ByVal
reserved word cannot be used with a variable of a user-defined type, an object type, or
a variable that is an array.
Variablename Name of the variable to pass as an argument. For array variables, use
the parentheses but omit the number of dimensions. As type Declares the data type of
variable. The type may be Integer, Long, Single, Double, Currency, String (variablelength strings only), Variant, a user-defined type, or an object type. Use a separate As
type clause for each argument.
Each time the procedure is called, the statements between Sub and End Sub are
executed. Visual Basic (VB) substitutes each reference to an item in the argument list
with the corresponding argument. When VB calls your event procedures, it supplies a
value for each argument. When you call your own general procedures, you must
supply values for each argument. For example, suppose you have defined the
MultiBeep general procedure as:
Sub MultiBeep (nBeeps)
Dim I
For I = 1 to nBeeps
Beep
Next I
End Sub
The following statement calls MultiBeep with the argument 3:
MultiBeep 3
The procedure substitutes 3 for nBeeps (the name that appears in the argument list).
The procedure therefore beeps three times.
Normally, calls to VB Sub procedure do not use parentheses around the argument list.
If you call a Sub with optional Call statement, however, you must surround the
argument list with parentheses:

18

VISUAL BASIC

Call MultiBeep(3)
2.4.3 Function Procedures
The syntax for a Function procedure is:
Function procedurename (arguments) [As type]
statements
End Function
The arguments for a Function procedure work in exactly the same way as the
arguments for a Sub procedure. Aside from the Function keyword, there are3 three
difference between Sub and Function procedures:

You always use parentheses with each Function call (You cannot use the Call
statement to call a Function procedure)

Function procedures have data types, just as variables do. This determines the
type of the return value. ( In the absence of as As clause, the type is the default
Variant type unless he procedurename has a type-declaration character).

You return a value by assigning it to the procedurename itself. When the


Function procedure returns a value, this value is then used as part of a larger
expression.

For example, you could write a function that calculates the third side, or hypotenuse,
of a triangle given the other two sides:
Function Hypotenuse (A,B)
Hypotenuse = Sqr( A ^ 2 + b ^ 2 )
End Function
You call a Function procedure the same way you call any of the built-in functions in
Visual Basic:
Label1.Caption = Hypotenuse ( Val(Text1.txt), Val(Text2.Text))
x = Hypotenuse(Width, Height)
2.4.4 Public and Private Procedures
The procedures in a form are private to that form; you can call them from within the
form, but the code in other form or code modules cannot call them. The procedures in
a code module are public; they can be called from anywhere else your application.
Because the procedures in a form are private, you can have procedures with the same
name in different forms. This is why each form can have form event procedures with
the same name (such as Form_Load). The public procedures in code modules must be
unique across all code modules.

19

VISUAL BASIC

You can create a procedure in a form module with the same name as a private
procedure in another module. In this situation, VB uses two rules to decide which
procedure to invoke.

VB first looks in the current form or code module.


If the procedure name is not found, VB scans all modules (but not forms) for the
procedure

2.4.5 Private Procedures in Modules


Sometimes you may want to create procedures in a module that are private to that
module. You can create private procedures by declaring them with the Private
keyword:
Private Sub someSub()
.
.
.
End Sub
Private Function someFunction()
.
.
.
End Function
You can declare procedures in a form with the Private keyword, but this has no effect
because the procedures in a form are always private anyway. There is no way to make
the procedure in a form public. If you want to call a general procedure in a form, you
should move it to a code module.
2.5 Setting and Retrieving Properties
Assignment statement assigns a value to a variable or to a property reference by
copying data from one place to another. The syntax uses an equal sign (=):
destination = source
The statements tells the application, Copy information from source to destination.
The destination must be a variable or reference to a property. The source can be any
valid VB expression and may involve calculations.
Assignment statement in VB generally do one of three things:

Set value of a property


Retrieve the value of a property
Store or retrieve data in a variable.

20

VISUAL BASIC
2.5.1 Setting the Value of a Property
To set the value of a property at run time , place a reference to the property
(object.property) on the left side of an assignment statement. For example:
Text1.Text = Your name here.
Text1.BackColor = 0
When you are referring to a form property in the code for that from, you can omit the
name of the form:
Sub Form_click ()
Set the Caption property of the form
Caption = You clicked me!
End Sub
The Text property is a string of characters that specifies the contents of a text box, list
box, or combo box. While you generally assign text strings to text properties, you can
assign numbers or mix numbers with text:
Text1.Text = 60
Text2.Text = The amount is & 60
In these statements, as a result of the Variant data type, Visual Basic automatically
converts the number into a string before assigning it to the text property.
2.5.2 Retrieving the Value of a Property
To retrieve the value of a property and store it in a variable or another property, place
a reference to the property on the right side of an assignment statement. For example:
Text2.Text = text1.Text
MyString = Text1.Text
Properties on Other Forms
When you have several forms or code modules in your application, youll find you
need to refer to the properties and controls on one form from the code in another form
or code module. You must specify the form when you are referring to a form property
from another form or code module:
Form1.Caption = A new caption for the form
Form1.BackColor = 0
2.6 Controls on Other Forms
When you are referring to a control on one form from code in another form or code
module, you must specify the form that contains the control. You separate the form
and control references with the ! operator:
Form1!Text1.Text = Your name here
Form1!Text1.BackColor = 0

21

VISUAL BASIC

Form1!Text1.Move 0,0
2.6.1 Using the Value of a Control
All controls have a property that you can use for storing or retrieving values just by
referring to the control , without using the property name. This is called the value of
the control and is usually the most important or most commonly used property for that
kind of control. Table 1 lists the property that is considered to be the value for each
kind of control.
Table 1. Controls and the Properties That Are Their Values
Control
Property
Check box
Value
Combo box
text
Command button
Value
Common dialog
Action
Data
Caption
Directory list box
Path
Drive list box
Drive
File list box
FileName
Frame
Caption
Grid
Text
Horizontal scroll bar
Value
Image
Picture
Label
Caption
Line
Visible
List box
Text
Menu
Enabled
Option button
Value
Picture box
Picture
Shape
Shape
Text box
Text
Timer
Enabled
Vertical scroll bar
Value
Whenever you want to refer to a property on a control that happens to be the value of
that control, you can do so without specifying the property name in your code. For
example, this line sets the value of the Text property of a text box control:
Text1 = this text is assigned to the Text property of Text
In this example, the Caption property of Lable1 is set to the FileName property of
File1 whenever the user clicks a file in the file list box:
Sub File1_Click ()
Label1 = File1
End Sub

22

VISUAL BASIC

3. INTRODUCTION TO BOUND CONTROLS


3.1 Introduction
Bound controls provide access to specific data in your database. Bound controls that manage a single
field typically display the value of a specific field in the current record. Data-bound controls are the
data-aware controls through which you access information in a database. When a control is bound to
the data control, Visual Basic applies field values from the current database record to that control. In
turn, the control displays data to you and accepts your changes. If you change data in a bound control,
those changes can be automatically written to the database as you move to another record.
Visual Basic supports several built-in controls that you can bind to the data control. Other data-aware
controls are available from third parties and in the Professional and Enterprise editions of Visual Basic.
The DataSource property of a bound control specifies a valid Data control name, and the DataField
property specifies a valid field name in the Recordset object created by the Data control. Together,
these properties specify what data appears in the bound control. DataField sets a value that binds a
control to a field in the current record
Visual Basic supports several built-in (intrinsic) controls that you can bind to the data control, as well
as several data-bound ActiveX (.ocx) controls (formerly called custom or OLE controls). Many other
data-aware controls are available from third parties and in the Professional and Enterprise editions of
Visual Basic.

3.2 Data Control


Data Control Provides access to data stored in databases using any one of three types of Recordset
objects. The Data control enables you to move from record to record and to display and manipulate
data from the records in bound controls. Without a Data control or an equivalent data source control
like the RemoteData control, data-aware (bound) controls on a form cant automatically access data.
The data control is used to create simple database applications without writing any code. It can also be
used to create more full-featured applications that give you a high degree of control over your data.
Figure shows a data control
Figure 2 Data Control
The data-bound list, data-bound combo, data-bound grid, and Microsoft FlexGrid controls are all
capable of managing sets of records when bound to a data control. All of these controls permit several
records to be displayed or manipulated at once. You can perform most data access operations using the
Data control without writing any code at all. Data-aware controls bound to a Data control automatically
display data from one or more fields for the current record or, in some cases, for a set of records on
either side of the current record. The Data control performs all operations on the current record. If the
Data control is instructed to move to a different record, all bound controls automatically pass any
changes to the Data control to be saved in the database. The Data control then moves to the requested
record and passes back data from the current record to the bound controls where its displayed.
The intrinsic picture, label, text box, check box, image, OLE container, list box and combo box
controls are also data-aware and can be bound to a single field of a Recordset managed by the data
control.

3.3 TYPES OF CONTROL


3.3.1 Intrinsic Controls
The standard bound controls that you can use with the data control include the following:

Check box

Image

Label

23

VISUAL BASIC

Picture box
Text box
List box
Combo box
OLE container control

Check Box
The check box control displays a check mark when it is selected. It is commonly used to present a
Yes/No or True/False selection to the user. You can use check box controls in groups to display
multiple choices from which the user can select one or more.
The check box control is similar to the option button control in that each is used to indicate a selection
that is made by the user. They differ in that only one option button in a group can be selected at a time.
With the check box control, however, any number of check boxes may be selected.
A check box indicates whether a particular condition is on or off. You use check boxes in an
application to give users true/false or yes/no options. Because check boxes work independently of each
other, a user can select any number of check boxes at the same time. For example in Figure Male and
Married can both be checked which can be bound to a data filed which stores the information in
Boolean fields .
The Click event for the check box occurs as soon as you click the box. This
event procedure tests to see whether the check box has been selected (that is,
if its Value = vbChecked).
Figure 3.1.1 Check boxes
Image Controls
The image control is used to display graphics. Image controls can display graphics in the following
formats: bitmap, icon, metafile, enhanced metafile, or as JPEG or GIF files.
Figure 3.1.2 The image control
In addition, image controls respond to the Click event and can be used as a substitute for command
buttons, as items in a toolbar, or to create simple animations. The Image control uses fewer system
resources and repaints faster than a PictureBox control, but it supports only a subset of the PictureBox
properties, events, and methods.
Picture Box
The primary use for the picture box control is to display a picture to the user. The actual picture that is
displayed is determined by the Picture property. The Picture property contains the file name (and
optional path) for the picture file that you wish to display.
Figure 3.1.3 The Picture Box control
The picture box control can also be used as a container for other controls. Like the frame control, you
can draw other controls on top of the picture box. The contained controls move with the picture box
and their Top and Left properties will be relative to the picture box rather than the form.
A common use for the picture box container is as a toolbar or status bar. You can place image controls
on it to act as buttons, or add labels to display status messages.
Label Control
Label controls are used to display text and cannot be edited by the user. They are used to identify
objects on a form provide a description of what a certain control will do if clicked, for example
or at run time, they can display information in response to an event or process in your application.
Figure 3.1.4 Label Control
Labels are used in many instances, for many different purposes. Most commonly, they are used to label
controls that don't have their own Caption properties. For example, you can use the label control to add
descriptive labels to text boxes, list boxes, combo boxes and so on. They can also be used to add
descriptive text to a form, for example, to provide the user with Help information.

24

VISUAL BASIC
You can also write code that changes the text displayed by a label control in response to events at run
time. For example, if your application takes a few minutes to process a change, you can display a
processing-status message in a label.
Text Box
Label and text box controls are used to display or enter text. Use labels when you want your application
to display text on a form, and text boxes when you want to allow the user to enter text. Labels contain
text that can only be read, while text boxes contain text that can be edited.
Text boxes are versatile controls that can be used to get input from the user or to display text. Text
boxes should not be used to display text that you don't want the user to change, unless you've set the
Locked property to True.
The actual text displayed in a text box is controlled by the Text property. It can be set in three different
ways: at design time in the Property window, at run time by setting it in code, or by input from the user
at run time. The current contents of a text box can be retrieved at run time by reading the Text property.
Setting MultiLine to True enables a text box to accept or display multiple lines of text at run time. A
multiple-line text box automatically manages word wrap as long as there is no horizontal scroll bar.
The ScrollBars property is set to 0-None by default. Automatic word wrap saves the user the trouble of
inserting line breaks at the end of lines. When a line of text is longer than what can be displayed on a
line, the text box wraps the text to the next line.
Line breaks cannot be entered in the Properties window at design time. Within a procedure, you create
a line break by inserting a carriage return followed by a linefeed (ANSI characters 13 and 10). You can
also use the constant vbCrLf to insert a carriage return/linefeed combination.
The text box control is used to display information entered by the user at run time, or assigned to the
Text property of the control at design or run time.A TextBox control, sometimes called an edit field or
edit control, displays information entered at design time, entered by the user, or assigned to the control
in code at run time.

Figure 3.1.5 The Text Box control


In general, the text box control should be used for editable text, although you can make it read-only by
setting its Locked property to True. Text boxes also allow you to display multiple lines, to wrap text to
the size of the control, and to add basic formatting.Text entered into the text box control is contained in
the Text property. By default, you can enter up to 2048 characters in a text box. If you set the
MultiLine property of the control to True, you can enter up to 32K of text.
Multiple-Line Text Boxes and Word Wrap
By default, a text box displays a single line of text and does not display scroll bars. If the text is longer
than the available space, only part of the text will be visible. The look and behavior of a text box can be
changed by setting two properties, MultiLine and ScrollBars, which are available only at design time.
List Box
A list box control displays a list of items from which the user can select one or more.

Figure 3.1.6 The list box control


List boxes present a list of choices to the user. By default, the choices are displayed vertically in a
single column, although you can set up multiple columns as well. If the number of items exceeds what
can be displayed in the list box, scroll bars automatically appear on the control. The user can then scroll
up and down, or left to right through the list.
Visual Basic includes both standard and data-bound versions of the list box control. While both
versions of the list box control allow you to display, edit, and update information from most standard
types of databases, the data-bound list provides more advanced data access features. The data-bound
list box control also supports a different set of properties and methods than the standard list box
control.
Combo Box

25

VISUAL BASIC
A combo box control combines the features of a text box and a list box. This control allows the user to
select an item either by typing text into the combo box, or by selecting it from the list.
Figure 3.1.7 The Combo Box control
Combo boxes present a list of choices to the user. If the number of items exceeds what can be displayed
in the combo box, scroll bars will automatically appear on the control. The user can then scroll up and
down or left to right through the list.
When to Use a Combo Box Instead of a List Box
Generally, a combo box is appropriate when there is a list of suggested choices, and a list box is
appropriate when you want to limit input to what is on the list. A combo box contains an edit field, so
choices not on the list can be typed in this field.
Combo Box Styles
There are three combo box styles. Each style can be set at either design or run time and uses values, or
equivalent Visual Basic constants, to set the style of the combo box.
Style
Drop-down combo box
Simple combo box
Drop-down list box

Value
0
1
2

Constant
vbComboDropDown
vbComboSimple
vbComboDropDownList

In addition, combo boxes save space on a form. Because the full list is not displayed until the user
clicks the down arrow (except for Style 1, which is always dropped down), a combo box can easily fit
in a small space where a list box would not fit.
You can also use the data-bound list box and data-bound combo box controls with a single data control.
To do this, set both the DataSource and RowSource properties to the same data control, and set the
DataField and BoundColumn properties to the same field in the data controls recordset. In this case,
the list will be filled with ListField values from the same recordset that is updated. If a ListField
property is specified, but no BoundColumn property is set, BoundColumn will automatically be set to
the ListField field.
A common use of these controls is to build a list of items based on a database query from which a user
can select or enter a value, or in the case of data-bound combo box, to edit the selected field. When an
item in the list is selected, its associated BoundColumn property value is made available to the data
control specified by the DataSource property. Once the data control moves to another record or is
otherwise updated, the recordset is updated with the selected or edited text.
OLE control
You can link or embed any object that supports Automation (formerly called OLE Automation) into the
OLE container control. Using this control, your Visual Basic application can display and manipulate
data from other Windowsbased applications, such as Microsoft Excel and Microsoft Word for
Windows.

Figure 3.1.8 The OLE container control


The OLE container control enables you to add insertable objects to the forms in your Visual Basic
applications. With the OLE container control, you can:

Create a placeholder in your application for an insertable object. At run time you can create
the object that is displayed within the OLE container control or change an object you placed within the
OLE container control at design time.

Create a linked object in your application.

Bind the OLE container control to a database using the Data control.
You can bind the OLE container control to data stored in the Microsoft Jet database engine or
Microsoft Access database. You may want to do this, for example, if you have a database with a table
of employee pictures. If the pictures are stored as objects, you can bind them to the OLE container
control and display them on a form as each record is accessed with the data control. To bind data to one
of these databases, specify the source of data (recordset name) in the DataSource property and the field
name from that data source in the DataField property of the OLE container control. When displaying an

26

VISUAL BASIC
object from a database, the OLE container control allows the user to activate, edit, and update the
object. As with any bound control, the updated object is automatically written back to the database
when the record position is changed.

3.3.2 ActiveX Controls


In addition to the intrinsic bound controls, Visual Basic also provides the following ActiveX controls
that can be added to your project:

Data-bound list box

Data-bound combo box

MSFlexGrid

Apex Data-Bound Grid (DBGrid)


For complex interfaces, several of these ActiveX controls provide added functionality to let you display
whole groups of records, such as lists, tables, or entire recordsets. These include the list box, combo
box, and MSFlexGrid controls.
In addition, three special controls allow you to accomplish complex database display and updating
tasks with multiple recordsets and fields. These are the data-bound list and combo box controls and the
DBGrid control.
Data Access Controls
Basically, you can use Remote Data Objects similarly to the way you use the Microsoft Jet database
engine Data Access Objects (DAO), and the RemoteData control is similar to the Data control. With
RDO, you can submit queries, create a result set or cursor, and process the results from the query using
database-independent object-oriented code.
Using the RemoteData control, you can create a form containing the same bound controls recognized
by the Data control and process a result set with little or no code. You can take your existing
applications that use DAO and the Data control and convert them to use RDO and the RemoteData
control with a few changes. There are some differences, however, because RDO is implemented and
designed for use with strictly relational databases. RDO has no query processor of its own; it depends
on the data source to process all queries and create the result sets. The data objects themselves are built
from the result sets and cursors returned by the ODBC driver.

The data control is used to connect to a database. Think of it as a pipeline between the
database and the other controls on your form. Its properties, methods, and events allow you to navigate
and manipulate external data from within your own application.

The DBList control is similar to the list box control. When used in conjunction with a data
control, it can be automatically filled with a list of data from a field in an external database.

The DBCombo control is like a combination of the DBList and a text box. The selected text in
the text box portion can be edited, with the changes appearing in the underlying database.

The DBGrid control displays data in a grid or table. When used in conjunction with a data
control, it presents fully editable data from multiple fields in an external database.

The MSFlexGrid control is a unique control for presenting multiple views of data. Think of it
as a combination of a grid and a tree or outline control. At run time, the user can rearrange columns and
rows to provide different views of the data.
Most bound controls are characterized by three data-aware properties: DataChanged, DataField, and
DataSource.
PropertyDescription
DataChanged
Indicates whether a value displayed in a bound control has changed.
DataField
Specifies the name of a field in the recordset created by the data control.
DataSource
Specifies the name of the data control to which the control is bound.
The steps in adding bound controls to your application are:
Draw the bound control on the same form as the data control to which it will be bound.
1.
Set the DataSource property to specify the data control to which it will be bound.
2.
Set the DataField property to a valid field in the data controls recordset.
3.
If the database is available at design time, a list of valid fields will be displayed in the DataField
Settings box in the Properties window. If the database is not available at design time, youll need to
provide a valid field name at run time before data values will be posted to the control from the
database.

27

VISUAL BASIC
You can have more than one bound control for a particular field, but you do not need to provide a
bound control for each field in the table. Neither the data control nor the bound controls need to be
made visible, so you can incorporate data access capabilities into any form you design, manipulating
the data control behind the scenes with Visual Basic code.
When you run your application, the data control works together with the database to give you access to
the current set of records, or recordset, with which you are working. Using the arrow buttons on the
data control, you can move from record to record, and using the bound controls, you can view or edit
the data displayed from each field. Whenever you click a button on the data control, Visual Basic
automatically updates any changes youve made to the recordset.
DBList Control
The DBList control is a data bound list box which is automatically populated from a field in an
attached Data control, and optionally updates a field in a related table of another Data control.
Figure 3.2.2 DB List
The DBList control differs from the standard ListBox control. While the ListBox control list is filled
using the AddItem method, the DBList control is automatically filled with data from a field in the
Recordset object of a Data control to which it is attached. The standard ListBox control must be
populated manually by using the AddItem method. In addition, the DBList control has the ability to
update a field within a related Recordset object which may reside in a different Data control.
The DBList control also supports an automated search mode that can quickly locate items in the list
without additional code.
Shown below is a list of the properties you use to fill and manage the list, and bind the selected data to
a Data control.
Property
DataSource
DataField
RowSource
ListField
BoundColumn

BoundText

Text
MatchEntry
SelectedItem
property.
VisibleCount
VisibleItems

Specifies
Name of Data control that is updated once a selection is made.
Name of a field that is updated in the Recordset specified by the DataSource
property.
Name of Data control used as a source of items for the list portion of the control.
Name of a field in the Recordset specified by RowSource that is used to fill the list.
DBList does not support fields of LongBinary type for the ListField property.
Name of a field in the Recordset specified by RowSource that is passed back to the
DataField once a selection is made. DBList does not support fields of LongBinary
type for the BoundColumn.
Text value of the BoundColumn field. Once a selection is made, this value is passed
back to update the Recordset object specified by the DataSource and DataField
properties.
Text value of the selected item in the list.
How the list is searched as the user types characters at run time.
The bookmark of the selected item in the Recordset specified by the RowSource
The number of items visible in the list (fully or partially).
An array of bookmarks with a maximum number of items equal to the VisibleCount
property.

The DBList control will automatically highlight an item in the list if the BoundText property becomes
equal to the value of the field specified by the DataSource and DataField properties, such as when
using a Data control to change the current record.
DBCombo Control
The DBCombo control is a data bound combo box with a drop-down list box which is automatically
populated from a field in an attached Data control, and optionally updates a field in a related table of
another Data control. The text box portion of DBCombo can be used to edit the selected field.
Figure 3.2.3 DBCombo Control

28

VISUAL BASIC
The DBCombo control differs from the standard ComboBox control. While the ComboBox control list
is filled using the AddItem method, the DBCombo control is automatically filled with data from a field
in the Recordset object of a Data control to which it is attached. The standard ComboBox control must
be populated manually by using the AddItem method. In addition, the DBCombo control has the ability
to update a field within a related Recordset object which may reside in a different Data control.
The DBCombo control also supports an automated search mode that can quickly locate items in the list
without additional code.
The following example uses the data-bound combo box control to create a data entry screen for the
Titles table of the Biblio.mdb sample database(This MDB is supplied with Access/VB). It lets the user
enter new titles and assign them to existing publishers by providing a lookup table of all the publishers
names. When users get to the Publisher field in the entry form, they can choose a publisher from a list
box. When they select a publisher, that publishers PubID field is copied into the PubID field of the
Titles table.
To create a lookup table with the data-bound combo box control
1.
Add a data-bound combo box control and two data controls to your form.
2.
In the Properties window, set the first data control (Data1) properties to create a table-type
recordset against the Titles table.
3.
Set the second data control (Data2) properties to a create a snapshot-type Recordset object
against the Publishers table, using the following SQL Query:
SELECT PubID, Name FROM Publishers ORDER BY PubID
4.
Set the DataSource property for the data-bound combo box to the first data control (Data1).
The DataField property should be set to the PubID field of the Titles table. This binds the
data-bound combo box control to update the Titles recordset.
5.
Set the RowSource property for the data-bound combo box to the second data control
(Data2).
6.
Set the BoundColumn property for the data-bound combo box to the PubID field of the
Publishers table. This sets the data-bound combo box control to use the PubID field of the
second data controls recordset (Publishers) when it updates the DataField of the first data
controls recordset (Titles).
7.
Set the ListField property to the Name field of the Publishers table. Note that the ListField
property pull-down menu is derived from the data control specified by the RowSource property. This
specifies that the Name field will be used to fill the data-bound combo boxs list.
The DataField and the BoundColumn fields should be identical, but in different tables; that is, these
fields should reflect a relation between the two tables.
DBGrid Control
You can use the Apex Data-Bound Grid (DBGrid) control to quickly and easily display and browse
through all the records in a database table. This can be accomplished in minutes without writing code.
The Apex Data-Bound Grid (DBGrid) control displays records from the underlying Recordset object at
run time. There is always a single current record in the DBGrid control, even if multiple rows in the
control are selected. The current record corresponds to the data controls current record and can be set
or retrieved with the DBGrid controls Bookmark property.
As with other data-bound controls, when you change a record (or any field in a record) in the DBGrid,
the underlying recordset is updated when you move to a new record (row), assuming that it is updatable
and the DBGrid controls AllowUpdate property is set to True.
Before using the DBGrid, you must make sure the control is available to the project. If necessary, add it
on the Controls tab in the Components dialog box, available from the Project menu.
To use DBGrid to display and browse through an existing database table, follow these steps:
1.
Add a data control to a new form, and set its DatabaseName and RecordSource properties to
the database and table you want to display.
2.
Add a DBGrid control to the form, and set its DataSource property to the data control you just
created.
3.
Run the application.
When your program runs, the database table you specified is displayed in the DBGrid, complete with
column headers (from the data controls recordset) and scroll bars. You can immediately scroll through

29

VISUAL BASIC
all the records and fields of the table. In addition, you can edit any cell in the table, and it will
automatically be updated when you move to a new row (assuming that the underlying recordset is
updatable and the DBGrid controls AllowUpdate property is set to True). With the AllowAddNew and
AllowDelete properties set to True, you can delete records by selecting and deleting the entire row.
Displays and enables data manipulation of a series of rows and columns representing records and fields
from a Recordset object. The data-aware DBGrid control appears similar to the Grid control; however,
you can set the DBGrid control's DataSource property to a Data control so that the control is
automatically filled and its column headers set automatically from a Data control's Recordset object.
The DBGrid control is really a fixed collection of columns, each with an indeterminate number of
rows.
Figure 3.2.4 DBGrid Control
Each cell of a DBGrid control can hold text values, but not linked or embedded objects. You can
specify the current cell in code, or the user can change it at run time using the mouse or the arrow keys.
Cells can be edited interactively, by typing into the cell, or programmatically. Cells can be selected
individually or by row.
If a cell's text is too long to be displayed in the cell, the text wraps to the next line within the same cell.
To display the wrapped text, you must increase the cell's Column object's Width property and/or the
DBGrid control's RowHeight property. At design time, you can change the column width interactively
by resizing the column or by changing the column's width in the Column object's property page.
Use the DBGrid control's Columns collection's Count property and the Recordset object's RecordCount
property to determine the number of columns and rows in the control. A DBGrid control can have as
many rows as the system resources can support and about 1700 columns.When you select a cell, the
ColIndex property is set, thus selecting one of the Column objects in the DBGrid object's Columns
collection. The Text and Value properties of the Column object reference the contents of the current
cell. The data in the current row can be accessed using the Bookmark property, which provides access
to the underlying Recordset object's record. Each column of the DBGrid control has its own font,
border, word wrap, color and other attributes that can be set without regard to other columns. At design
time, you can set the column width and row height and establish columns that are not visible to the
user. You can also prevent users from changing the formatting at run time.
The DataMode property controls how the data is handled for the DBGrid control. In unbound mode,
you are responsible for maintaining data and supplying the DBGrid control with the appropriate data
when requested through the unbound events. In bound mode, the data is retrieved and updated
automatically using the Data control's Recordset. Normally, the unbound mode of the DBGrid control
is used when displaying data that is not stored in a database accessible by the Microsoft Jet Database
Engine. You can use the unbound mode for whatever type of data you have available. For example, you
can use the unbound mode of the DBGrid control to display data from a proprietary database format or
use it to manage data that you keep track of in a text file.

30

VISUAL BASIC

4. DATABASE CONNECTIONS
4.1 Database
Relational Database Objects
Visual Basic provides a relational interface to database files. Basically a relational database is
one that stores data of tables, made up of columns and rows of data. In Visual Basic, columns are
referred to as fields, and rows are referred to as records.
A Visual Basic database is a collection of information defined and organized by a set of
relational tables, regardless of its database file format. This means that when you use data from external
databases (like Foxpro, Paradox dBASE, or Btrieve), you can use the same relational terms.
Working with Database Structure

There are two categories of databases that the data control recognizes:
Microsoft Access-format databases. These database files can be created with Microsoft Access and
manipulated with Microsoft Access and Visual Basic.
External databases. This category includes database formats such as dBASE, Paradax, FoxPro, and
Btrieve.

The Database Object


The controls Database property can be represented by a Database object that describes the current
database. It maintains information about the name of the database and its structure. For example, the
database structure describes the tables in the database and the fields in each table.
Collections
A collection is a set of related objects. The objects in a collection are referred to as a members of the
collection. In Visual Basic, each member of a collection has a unique name so its easy to identify. You
can use the Count property to determine the number of members in a collection. Collections are
managed like the items in a list box. Each member of the collection can also be referenced by its
number, which starts with 0.
For example, to print the names of tables in your database you can examine the TableDefs collection:
Dim I as Integer
For I=0 To Data1.Database.TableDefs.Count -1
Print Data1.Database.TableDefs(I).Name
Next I
Because a database can have several tables, and tables can have several fields, Visual Basic groups the
definition for these objects in collections.
A Database object can have one or many tables. The description of each table is maintained in a
TableDef object. There is one TableDef for each table in the selected database. Each TableDef object
contains the name of the table, a collection of Fields.

4.1.1 Opening a Database


You can use two different methods to open a database in Visual Basic:
Use the data control.
Use the OpenDatabase function.
Using the data control can significantly reduce the amount of code you need to open and manipulate a
database.
The other way to open a database is to use the OpenDatabase function to create a Database object.
The OpenDatabase function syntax is:

31

VISUAL BASIC

OpenDatabase(databasename [,exclusive [,readonly[,connect]]])


In the following example, the OpenDatabase function is used in its simplest form to open a shared,
read/write, Microsoft Access-format database named Currency.MDB, located in the current directory:
Dim db as Database
Set db = Opendatabase(Currency.MDB)
Using the Exclusive Part of OpenDatabase:
If you want to share your database with other users, set the exclusive part of the function to False. If the
database is already opened by another user, you will not be able to open it with the exclusive part set to
True. Once you database is opened in exclusive mode, no other users will be able to open it until you
close it. The exclusive part of the function defaults to False.
Using Readonly Part of OpenDatabase:
If you want to open a database as read-only part of the function to True. When a database is opened as
read-only, Visual Basic does not have to spend as much time dealing with read/write issues, which
gives you faster access to the data.
Using Connect Part of Opendatabase:
The databasename and connect parts of the OpenDatabase function work in tandem to identify the
source and format of the data. The source of your database can be on your workstation, on a shared
network server, or on an ODBC server.
Databasename provides Visual Basic with the named source for the data.
Connect provides Visual Basic with the type of database and the optional paramaters that may be
needed to gain access to the database.

4.2 Creating Recordsets


One of the easiest ways to manipulate information in your database is to use a recordset variable. A
recordset variable refers to an object such as a Table, Dynaset, or Snapshot. You use recordset
variables to access and manipulate data in an object. For example, you can use recordset variables to
change the order of data returned to your application, select records, or make changes to data. The
following table lists the recordset variables and their different capabilities.

Recordset
Variable
Table
Dynaset
Snapshot

Membership
Can change
Fixed
Fixed

Records
Can add, change, delete
Can add, change, delete
Fixed

Result of a query
No
Yes
Yes

The membership refers to those records that become part of the recordset when it is created. In the case
of Table variables, the changes, additions, and deletions that other users make appear immediately as
you move through the records. In the case of Dynaset or Snapshot variables, the additions and deletions
that other users make do not appear in your Dynaset or Snapshot.
Your database provides the source of data for recordset variables. Visual Basic works with your
database to define its information in terms of three basic data structures:

Tables
A table is a set of related information stored in a database.
Records A record is a container in a table that stores information about an individual item. A set of
records (or recordset) is a group of records that all have similar characteristics.

32

VISUAL BASIC

Queries
A query is a temporary set of records defined by a question posed in terms of a SQL
statement. When you create a recordset, the data in a query is presented to your application as if it
were a table. Queries have fields and records just like tables; however they are only a temporary
representation of the data from one or more base tables.

Creating Table Variables


You can declare a Table variable and then use it to access the data in a base table in a database. To do
this, you use the OpenTable method on an existing Database variable and assign the result to your
Table variable:
Dim db as Database, TableVar as Table
Set db = OpenDatabase(Currency.MDB)
Set TableVar = db.OpenTable(dbCurrency)
The syntax for the OpenTable method is:
OpenTable (tablename[,options])
The options part controls parameters such as read/write privileges, table update procedures, and SQL
query processing.
Creating Dynaset Variables
Dynaset provide more flexibility than Table object variables. Using the data control or a Database
variable created with the OpenDatabase function, you can create a Dynaset on any table, including an
attached table, or on the result of any query. The query can extract data from more than one table,
including attached tables. In this way you can use a Dynaset to combine or join data from more than
one database.
You create a Dynaset variable on a table in the same way that you create a Table variable:
Dim db as database, dsomedata as Dynaset
Set db = OpenDatabase(Currency.MDB)
Set dsomedate = db.CreateDynaset(dbCurrency)
The syntax for the CreateDynaset method is
CreateDynaset (source [,options])
The source for a Dynaset can be a table name, QueryDef object name, or SQL query in the form of a
string. The options part controls parameters such as read/write privileges, table update procedures, and
SQL query processing.
In the following example, the code creates a Dynaset using an SQL query that joins data from tables in
the BIBLIO database
Dim db as database, dsomedata as Dynaset, SQLQ as string
Set db = OpenDatabase(BIBLIO.MDB)
SQLQ = Select Titles.Title, Publishers.Name
SQLQ = SQLQ & From Titles, Publishers
SQLQ = SQLQ & Where Titles.PubID = Publishers.PubID
Set dsomedate = db.CreateDynaset(SQLQ)
Adding, Changing and Deleting Dynaset Records
When you add records to a Dynaset, the records are always added to the end of the Dynaset, regardless
of the sort order you originally requested.
When you delete records from your Dynase, Visual Basic deletes them from the database as well. If
other users have created Dynasets that share the records you delete, the users will not be notified unless
they try to move to or edit one of the deleted records.
If you change records in your Dynaset, the changed records are updated in-place. That is, the changed
record remains in the Dynaset in its original order---even if the index field that determined the Dynaset
order was affected by the change.
Creating Snapshot Variables
rating a Snapshot variable is similar to creating a Dynaset variable. You can create a Snapshot from a
table or a query in the database:
Dim db as database, snapdata as Snapshot
Set db = OpenDatabase(Currency.MDB)
Set snapdata = db.CreateSnapshot(dbCurrency)

33

VISUAL BASIC

The syntax for the CreateSnapshot method is:


CreateSnapshot (source [, option])
The source for a Snapshot can be a table name, an attached table name, QyeryDef object name, or SQL
statement expressed as a string. The options part controls parameters such as read/write privileges,
table update procedures, and SQL query processing.
You can create a Snapshot variable on any table, on the result of any query, on any Dynaset, or on
another Snapshot. You cannot execute the Edit, AddNew, or Update methods against Snapshot.

4.3 Selecting Records


When you want to further limit the scope of records returned by a Dynaset or Snapshot you can:
Create a new Dynaset or Snapshot after having set the Filter property on an existing Dynaset or
Snapshop.
Include an SQL query that limits the records as the argument to a CreateDynaset or
CreateSnapshot method executed against an existing Dynaset or Snapshot.
For example, the following code filters the Titles table to produce a Dynaset that contains only Titles
that have the string SQL embedded in the Name, and then sorts the titles by the Date Published and
the first letter of the Name:
Dim db as database, somedata as Dynaset, sortdata as dynaset
Set db = OpenDatabase(BIBLIO.MDB)
Set somedata = db.CreateDynaset(Titles)
somedata.Filter = [Name] LIKE *SQL*
somedata.Sort = [Date Published], left([Name], 1)
Set sortdata = somedata.CreateDynaset()
You cant set a Filter on a Table variable. If you want to restrict the records in a Table, you must create
a Dynaset or Snapshot variable on the table.
Closing Recordset Variables
To close a recordset variable, you use the close method. Visual Basic automatically closes a Table,
Dynaset, or Snapshot if you destroy the associated variable.

4.4 Positioning the Current Record in a Recordset


A recordset can have from zero to any number of records, Visual Basic makes only one recordset
record available at a time. This record is the current record; you must make a record current before you
can access its data. To make a specific record current, you need to use Seek method or one of the Move
or Find methods.
The current record will become undefined and unusable when the current record is positioned as
follows:
Ahead of the first record, when the BOF property is True.
Behind the last record, when the EOF property is True.
Over a record that has been deleted, by not using a Move method or bookmark after records are
deleted or by positioning to a record that another user deleted.
When using Seek or one of the Find methods and no records could be found that match the
criterion or key value. If the NoMatch property is True after using one of these methods, you may
be positioned to a valid record, but there is no guarantee of that. It is best to save the valid current
record in a bookmark and restore the current record to the bookmark value after one of these
methods fails.
In a recordset where there are no records. This applies Whether you create a recordset variable
with no records or delete all records in a table.
Using the Move Methods
Visual Basic provides four Move methods for changing the current record.
Mehtod
MoveFirst

Purpose
Makes the first record the current record

34

VISUAL BASIC
MoveLast
MoveNext
MovePrevious

Makes the last record the current record


Makes the next record the current record
Makes the previous record the current record

Using the Find Methods


Rather than looping through all the records in a Dynaset or Snapshot, you can make your code more
effeicient by finding only those records that match given criteria. In most cases, you should use a query
to select a general subset of records for a Dynaset or Snapshot, then use the Find methods to search
within that subset. Each method takes a criterion argument and searches through the Dynaset or
Snapshot for matches. The find methods cannot be used on Table objects.
Method
What it finds
Starting part
First record matching criteria
First record in recordset.
FindFirst criteria
Last record matching criteria
Last record in recordset.
FindLast criteria
Next record matching criteria
Current record.
FindNext criteria
Previous record matching criteria
Current record.
FindPrevious criteria
Use the Seek method
The Seek method provides a dramatically faster way of finding records in an indexed Table variable.
The Seek method finds data in a Table object using the current index, as defined by the Index property
of the Table variable. If there is no suitable index to use, you must create one in order to use the Seek
method. The Seek method takes a variable number of arguments, the first of which always a
comparison string that indicates the kind of comparison that will be performed.
Comparison string
Find first record
=
Equal to the key values.
>
Greater than the key values.
>=
Greater than or equal to the key values.
<
Less than the key values.
<=
Less than or equal to the key values.
For example, the following code finds the first publisher with name that begins with the letter U or
higher in the alphabet:
Dim db as database, pubs as table
set db = OpenDatabase(BIBLIO.MDB)
set pubs = db.OpenTable(Publishers)
pubs.Index = Name
pubs.Seek >=, M
If pubs.NoMatch then
msgbox not found
else
msgbox pubs(Name) & & pubs(Zip)
endif
pubs.close
db.close
Using Bookmarks
The Bookmark property of a recordset object enables you to mark your place in a recordset so you can
return to it later. For example, you can keep a pointer to the current record by saving a bookmark
before you use Seek or one of the Find methods to move to another record.
Function ShowPublisher()
Dim ds as Dynaset, MyBookmark
Set ds = data1.Recordset
MyBookmark = ds.Bookmark
ds.FindFirst [Publisher] = ds.PubId
If ds.Nomatch then
MsgBox No such publisher
ds.Bookmark = MyBookmark
End IF
End Function

35

VISUAL BASIC

4.5 Using Recordsets to Manipulate Data


Once youve defined a recordset variable, you can access its data.
Changing Records
Once youve found a record, you can change its contents. Changing the value of a record with code is a
three-step process.
Use the Edit method to prepare the current record for editing.
Assign new values to the fields you want to change in the current record.
Use the Update method to save the changes to the current record.
Deleting Records
To delete a record, you use the Delete method.
Syntax is:
Recordsetvariable.Delete
Adding New Records
You can append or insert new records in an updatable Table or Dynaset. As with updating records,
adding a new record is a three-step process:
Use the AddNew method to create a new record. The current record pointer is saved.
Assign new values to the fields in the new record.
Use the Update method to save the new record.
Locking Data
When multiple users are attempting to change the same data, there is an obvious conflict-which user
actually updates the data? The solution to this conflict, common to all multiuser database management
systems, is locking. By locking data thats being changed by one user, the database can ensure that no
other user simultaneously changes that same data.
You can do Lock Database by setting exclusive part of the OpenDatabase function to True:

4.6 Using QueryDef Variables


A QueryDef is an object variable that contains an SQL statement that describes a query. You can use a
QueryDef to save a predefined query in the database. QueryDef do not store data - they store the
definition of query used to retrieve data.
You declare a QueryDef the same way you declare other object variables:
Dim Q as QueryDef
You can run the query by creating a Dynaset variable on the QueryDef variable or by using the Execute
method.
Creating a New Query
To create a new QueryDef, you use the CreateQueryDef method to create a query within the specified
database, then assign it to a declared QueryDef variable:
Dim db as Database, Q as QueryDef
Set db = OpenDatabase(Currency.MDB)
Set Q = db.CreateQueryDef(New Query)
To define the query, you assign a valid SQL string to the SQL property of the QueryDef variable:
Q.SQL = SELECT Country FROM dbCurrency;
You can also create and define the query in a single step by providing the SQL string when you create
the query:
Set Q=db.CreateQueryDef(New Query, SELECT Country FROM dbCurrency;)
Running a Query
Once youve defined a query with a valid SQL string, you can run the query by creating a Dynaset on
the QueryDef variable:
Set DataRecs = Q.CreateDynaset()
Closing a Query
When youre finished with a QueryDef variable, its good programming practice to close it:
Q.Close
Deleting a Query
To delete a query, you use following code:
db.DeleteQueryDef New Query

36

VISUAL BASIC

4.7 Data Control and Bound Controls


With the data control, you can create applications to display, edit, and update information from many
types of existing databases. To use the data control in a Visual Basic program, you add an instance of
the control to a form and then set three essential properties that define a specific database connection

The connect property indicates the type of database youll attach to the program; Access is the
default.
The DatabaseName property is the file name of the database on disk.
The RecordSource property is the name of a table in the database.

Once youve defined the properties of the data control, you next begin adding bound controls to the
same form. Each bound control is designated to represent a field from the table youve selected as the
RecordSource property of the data control. For example, you can add bound labels to display field data,
or bound text boxes to allow editing of fields. Two important properties define a bound controls:

The DataSource property is the name of the data control to which the control will be bound. In
other words, the bound control will display a field from the data controls RecordSource table.
The DataField property is the name of the field that the bound control will represent.

In addition to the label and text box, you can use the list box, combo box, picture box, image and check
box as bound controls. Once youve designed a form that contains a data control and one or more
bound controls, your program is ready to run. When you start the program, the bound controls display
field information from the first record in the designated table. The data control provides buttons for
scrolling from one record to the next in the database. The operations you can perform on the database
depend on the types of bound controls youve added to your form. Some bound controls, such as
labels, simply display field data; others, such as text boxes, provide both read and write capabilities.

Adding a data control to a form.


In the following exercise youll use this approach to create the Currency Input program as a tool for
entering and revising records in the Exchange table of the Currency.MDB database. As youll see , the
program consists of a form containing a data control, three bound text boxes, and three labels. The
program contains no code. To develop the project, you simply add the controls to a form and set the
appropriate properties:
1.
2.
3.

Start a new project in Visual Basic. Open a new form.


Press F4 to activate the Properties window.
Pull down the File menu and choose Save File As. Enter CurrInDB as the file name for the name
for the form, and click save; as usual, Visual Basic adds FRM as the extension.
4. Double-click the data control in the Toolbox. An instance of the data control appears on the form.
5. Press F4 and enter Currency.MDB as the controls Caption property.
6. Select the DatabaseName property for the data control, giving you the opportunity to select an
Access database file to connect to your program.
7. Select the Name property and enter dbCurrency as the name of the data control.
8. Scroll to the RecordSource property. Enter the table name.
9. Add three labels and three text boxes to the form.
10. Select the first of the three text boxes in the form and pressF4 to activate the Properties window.
Scroll up to the DataSource property, and enter the name of the data control youve added to this
form, dbCurrency.
11. Select the DataField property, and enter the names of the three fields in the Exchange table Country, Currency, and InDollars.

37

VISUAL BASIC
12. Your program is complete. Save the Project.
Now youre ready to run the program and use it to append records to the Exchange table of the
Currency.MDB database. The program connects to the database and, displays the record that youve
already entered into the table.

To add a new record, click the Next Record button. The program presents a set of blank fields in which
you can enter the information for a new record

When you finish entering the last record, click the Close button (X) at the upper-right corner of the
window to end the program performance.

4.8 Programming with the Data Control


During runtime, a data control is associated with a Recordset object, which represents all the records in
the corresponding database table. In code, you use the data controls Recordset property to refer to this
object:
Data1.Recordset

38

VISUAL BASIC
The Recordset object has properties and methods that you program can use to scroll through the table,
to locate specific records, and to read fields of information:

The Move methods (MoveNext, MovePrevious, MoveFirst, MoveLast) change the current record
in the database
The Find methods (FindNext, FindPrevious, FindFirst, FindLast) look for a record that matches a
particular search criterion. When a matching record is found, it becomes the current record.
The EOF property indicates whether the program has moved past the last record in the database
table.
The Fields property represents the collection of all the fields in the table. You can use the Fields
(fieldName) notation to identify a specific field. The Value property of a field provides access to
a data item stored in the current record.

Create a new form that includes Combo box, two Option buttons, text box and command buttons.
Give the Name of the form is frmCurrExc.

4.8.1 Stepping through the Database Records


Dim db As database, dt As table
The Form_Load procedure begins its work by declaring variables as database and table.
Set db = OpenDatabase("c:\temp\currency.mdb")
This statement is used to Open a Database Currency.MDB
Set dt = db.OpenTable("dbCurrency")
This statement is used to Open a Table dbCurrency
dt.MoveFirst
This statement is used to move to the First record of the table.
Do Until dt.EOF
combo1.AddItem dt.Fields("Country").Value
dt.MoveNext
Loop
The main task of the Form_Load procedure is to read the Country field from each record of the
Recordset and to copy the field to the drop-down list of the combo box. This takes place in a Do loop
that steps through the database table from the first record to the last: The While loop continues reading
as long as the Recordsets EOF property is False. The Fields(Country).Value notation supplies the
data item stored in the Country field of the current record. There are actually several ways to refer to
this value. The complete reference is
dbCurrency.Recordset.Fields(Country).Value
But you can abbreviate this reference in the following ways:
dbCurrency.Recordset.Fields(Country)
or
dbCurrency.Recordset(Country)
Then the record pointer needs to be moved down to the next record in the database table. A call to the
MoveNext method performs this task:
.MoveNext

4.8.2 Searching for a Database Record


When the user pulls down the Country list and choose the name of a country, the event
procedure named combobox_click takes control. This procedures fist job is to find the record
corresponding to the users selection from the list. Then it reads the three fields of that record, and uses
the field data to display specific information in the application window.

39

VISUAL BASIC
The procedure calls the Recordset.FindFirst method to perform the search. FindFirst steps
through a database table, starting from the first record, and searches for a record that meets a specific
search criterion. The Country field of the target record should have the same value as Combobox.Text that is, the country that the user has selected from the list.
Here is how the procedure expresses this search criterion in the call to FindFirst method:
data1.Recordset.FindFirst "Country= " & "'" & combo1.Text & "'"
The search criterion in this example is a concatenation of three strings. For example, suppose the user
pulls down the Country list and chooses France from the list; in effect, the FindFirst method works like
this:
data1.Recordset.FindFirst Country = France
The record that meets the criterion becomes the current record in the database table.

4.8.3 Using bound controls at Run Time


Adding a New Record
To add a new record, you use the data control Recordset objects AddNew method. The code looks like
this
Data1.Recordset.AddNew
The following code adds a new title to the Titles table of the Currency.MDB database.
Data1.Databaseame = Currency.MDB
Data1.RecordSource = dbCurrency
Data1.Refresh
Data1.Recordset.AddNew
Data1.Recordset(Country) = India
Data1.Recordset(Currency)= Rupees
Data1.Recordset(Value in Currency) = 37
Data1.Recordset.Update
Editing the Current Record
To change data in your database, you must first make the record you want to edit the current record. To
save your changes, simply move the current record pointer to another record, or use the Update
methodas shown in the preceding code example.
Data1.Databaseame = Currency.MDB
Data1.RecordSource = dbCurrency
Data1.Refresh

40

VISUAL BASIC
Data1.Recordset(Value in Currency) = 35
Data1.Recordset.Update
Saving Data with the Update Method
After you edit a record, you need to save the changed information to the database by using the Update
method on the recordset. You can also use the Update method after using the AddNew method, instead
of using one of the Move buttons on the data control. Your attempt to add or change a record may fail
if:
Your table has a unique index and this record is already in the table
One of the index key fields in your record is Null.
You do not have permission to write to the table or database.
The table is not updatable.
The record is on a page that is locked.
The contents of the bound control do not match the Field definition in the database.
Data1.Recordset.Update
Deleting Record
You can delete a record by using the Delete method. To do this, you first move the data control to the
record you want to delete, and then execute the Delete method. The delete method deletes the current
record from the database and makes the current record invalid. At this point, you must move to another
record in your recordset.
Data1.Recordset.Delete
Data1.Recordset.MoveNext
For example, the following code will delete from the Titles table in the BIBLIO database every record
whose Year Published field is less than 1889:
Data1.Databaseame = BIBLIO.MDB
Data1.RecordSource = Select * from Titles where [Year Published] < 1889;
Data1.Refresh
Do While Data1.Recordset.EOF = False\
Print Deleting title:; Data1.Recordset(Title)
Data1.Recordset.Delete
Data1.Recordset.MoveNext
Loop
Using a Bookmark to Move to a Specific Record
Bookmarks allow you to save a current record pointer and reposition directly to a specific record. The
Bookmark property contains a pointer to a record you specify; you can jump to that record by setting
the Bookmark equal to the value of that pointer. This value can be saved in a Variant or String variable.
The following code repositions the current record to a previously saved Bookmark:
Dim MyBookMark as Variant
MyBookMark = Data1.Recordset.Bookmark
Save current record pointer
Data1.Recordset.MoveFirst
Move off the record
Data1.Recordseet.Bookmark = MyBookmark
Move back to saved location.
If you dont know the physical order number or Bookmark of the record you want to access, you can
search for it by starting with the first record and loop through the recordset, comparing data from each
record with the item you want to find.
Caution:
If more than one user is accessing the database, the record order can change when you use the Refresh
method to rebuilt the recordset. If you depend on the record number to locate records, you will find that
this number will not consistently bring you back to the same record. Bookmark save a pointer to the
record that can be used to retrieve a specific record as long as that record remains in the recordset and
you do not Refresh the recordset. If you or some other user deletes the record, the Bookmark becomes
invalid, and Visual Basic generates a trappable error.

41

VISUAL BASIC
The RecordSource Property
The RecordSource property indicates where in the database the data will be found. You can use the
RecordSource property to specify one of three different sources:
The name of a database table.
The name of a Microsoft Access database query.
The text of a SQL query.
At design time you can choose from a list of database tables and queries by first specifying the
DatabaseName and (if required) Connect properties. At run time, you can specify a table name or a
query name, or you can use the RecordSource property to specify a SQL query that will return a set of
records from your database. For example, the following SQL query returns all of the columns in the
Currency database for the Country is Germany:
Data1.Databaseame = Currency.MDB
Data1.RecordSource = Select * from dbCurrency where Country = Germany
Data1.Refresh
Closing a Recordset
The Close method closes the recordset and frees the resources allocated to it.
Data1.Recordset.Close
Databases and their respective recordsets are closed when:
You use the Close method against a specific recordset.
The form containing the data control is unloaded.
The program executes an End statement.

4.9 Using SQL


SQL (Structured Query Language) is a common idiom for working with relational data bases. You can
use SQL statements in many places in Visual Basic where you can enter the name of a table, query, or
field.
For example, you can enter an SQL statement as the setting for the RecordSource property of a data
control to produce a list of items. Here is how you might use SQL in the Combobox_click procedure
instead of the call to the FindFirst method:
Data1.RecordSource = "select * from dbCurrency where Country =" & "'" & Combo1.Text &
"'"
Data1.Refresh
This code uses Select statement to change the setting of the RecordSource property. Then a call to the
Refresh method rebuilds the Recordset.
SQL Statements
SELECT fieldlist
FROM tablenames IN databasename
WHERE searchconditions
GROUP BY fieldlist
HAVING searchconditions
ORDER BY fieldlist
SELECT CLAUSE
SELECT specifies which fields you want to retrieve. You use the FROM clause to indicate which
tables contain those fields. You use the WHERE clause to indicate which records are to be retrieved.
Example: Selects the Last Name and First Name fields of all records in the Employees table.
SELECT [Last Name], [First Name]
FROM Employees

42

VISUAL BASIC
FROM CLAUSE
FROM specifies the tables or queries that contain the fields listed in the SELECT statement.
Example: Selects the Last Name and First Name fields of all records in the Employees table.
SELECT [Last Name], [First Name]
FROM Employees
WHERE CLAUSE
You can use WHERE to determine which records from the tables listed in the FROM clause will
appear in the results of the SELECT statement. Records are selected according to the conditions listed
in the WHERE clause.
Example: Selects the Last Name and First Name fields of each record in which the last name is King.
SELECT [Last Name], [First Name]
FROM Employees
WHERE [Last Name] = 'King';
GROUP BY CLAUSE
GROUP BY combines records with identical values in the specified field list into a single record. A
summary value is created for each record if you include an aggregate function, such as Sum or Count,
in the SELECT statement. If the SQL statement includes a WHERE clause, records are grouped after
applying the WHERE conditions to the records.
Example: Creates a list of unique department names and the number of employees in each of those
departments
SELECT Dept, Count(Dept) AS Tally
FROM Employees GROUP BY Dept;
HAVING CLAUSE
Use HAVING to specify which grouped records are displayed. Once GROUP BY combines records,
HAVING displays all records grouped by the GROUP BY clause that satisfy the conditions of the
HAVING clause.
Example: Displays the job titles in the Production department assigned to more than 50 employees
SELECT Title, Count(Title)
FROM Employees
WHERE Department = 'Production'
GROUP BY Title HAVING Count(Title) > 50;
ORDER BY CLAUSE
ORDER BY sorts the displayed data in the order specified in the clause.
/*Sorts the records by last name in descending order (Z-A)*/
SELECT [Last Name], [First Name]
FROM Employees
ORDER BY [Last Name] DESC
DELETE CLAUSE
You can use DELETE in an action query to create a delete query that removes records listed in the
DELETE statement and from the tables listed in the FROM clause.
Example: Deletes all records for employees whose title is Trainee. When the FROM clause includes
only one table, you don't have to list the table name in the DELETE statement.
DELETE FROM Employees
WHERE Title = 'Trainee';

43

VISUAL BASIC
IN CLAUSE
Use the IN clause to retrieve data stored in more than one database, such as a dBASE or Paradox
database or in another Visual Basic database. For example, you can use the IN clause to select all
customers in a dBASE or Paradox table whose Customer ID has "A" as the first letter.
SELECT Customers.[Customer ID],
FROM Customers,
IN MYDATA.MDB
WHERE Customers.[Customer ID] Like "A*"
comment:MYDATA.MDB is the name of a Microsoft Access database containing the Customers table.
SELECT INTO
You can use SELECT...INTO to create a make-table query. Use make-table queries to archive records,
make backup copies of your tables, or make copies to export to another database or use as a basis for
reports that display data from a particular point in time. For example, you might produce a Monthly
Sales by Region report by running the same make-table query each month.
Example: Creates a new table that contains only employee records that have the title Trainee.
SELECT Employees.*
INTO Trainees
FROM Employees
WHERE Title = 'Trainee';
UPDATE
You can use UPDATE in an action query to create an update query that changes records in the tables
listed in the FROM clause. You can use expressions to make the change.
Example: Changes values in the Reports To field to 5 for all employee records that currently have
Reports To values of 2.
UPDATE Employees
SET [Reports To] = 5
WHERE [Reports To] = 2;
SQL Aggregate Functions
Using the SQL aggregate functions in an SQL statement, you can determine various statistics on sets of
values. You can use these functions only in SQL statements.
Avg Function
Count Function
First, Last Functions
Min, Max Functions
StDev, StDevP Functions
Sum Function
Var, VarP Functions
To work with the data in a database, you can use queries to manipulate or extract data. A query either
asks the database for a set of records matching specified criteria (a SELECT query), or tells the
database to perform a specified operation on a set of records that match specified criteria (an action
query).
You can use a data control's RecordSource property to query the database, or you can use one of the
Find methods with a data control's Recordset property.
Querying a Database
Using an SQL query with a data control

Design your query so the database returns only the records you want.
Enter the SQL statement in the RecordSource property. You can do this at design time or run

44

VISUAL BASIC
time. At run time, you can use this code:
Data1.RecordSource = "SELECT * FROM Publishers WHERE State = 'NY'"

At run time, use the Refresh method to recreate the underlying Dynaset in the data control:
Data1.Recordset.Refresh

Using an existing QueryDef in the RecordSource property

Enter the name of the QueryDef in the RecordSource property. You can do this at design time or
run time. At run time, you can use this code:
Data1.RecordSource = "Full Name"
At run time, use the Refresh method to recreate the underlying Dynaset in the data control:
Data1.Recordset.Refresh

45

VISUAL BASIC

5. QUERIES
Query is a language in which a user requests information from the database. We can use queries to
View, Change and Analyze data in different ways. There are four different types of Queries.
1.
2.
3.
4.

Select Queries
Crosstab Queries
Action Queries
SQL Queries

5.1 Select Queries


A select query is the most common type of query. It retrieves data from one or more tables
and displays the results in a datasheet where you can update the records (with some restrictions). You
can also use a select query to group records and calculate sums, counts, averages, and other types of
totals.
Syntax:
SELECT [ALL | DISTINCT | DISTINCTROW | [TOP n [PERCENT]]]
FROM table
The following two examples are equivalent and return all records from the Employees table:
SELECT * FROM Employees:
Omits records that contain duplicate data in the selected fields. To be included in the results of
the query, the values for each field listed in the SELECT statement must be unique. For example,
several employees listed in an Employees table may have the same last name. If two records contain
Smith in the Last Name field, the following SQL statement returns only one record that contains Smith
SELECT DISTINCT LastName FROM Employees;
If you omit DISTINCT, this query returns both Smith records. If the SELECT clause contains
more than one field, the combination of values from all fields must be unique for a given record to be
included in the results. The output of a query that uses DISTINCT isn't updatable and doesn't reflect
subsequent changes made by other users.
DISTINCTROW Omits data based on entire duplicate records, not just duplicate fields. For
example, you could create a query that joins the Customers and Orders tables on the Customer ID field.
The Customers table contains no duplicate Customer ID fields, but the Orders table does because each
customer can have many orders. The following SQL statement shows how you can use
DISTINCTROW to produce a list of companies that have at least one order but without any details
about those orders
SELECT DISTINCTROW CompanyName
FROM Customers INNER JOIN Orders
ON Customers.CustomerID = Orders.CustomerID
ORDER BY CompanyName;
If you omit DISTINCTROW, this query produces multiple rows for each company that has
more than one order.DISTINCTROW has an effect only when you select fields from some, but not all,
of the tables used in the query. DISTINCTROW is ignored if your query includes only one table, or if
you output fields from all tables.

RENAME OPERATION:
SQL provides a mechanism for renaming both tables and fields. It uses the as clause taking the form:

46

VISUAL BASIC
old_name as new_name
SELECT DISTINCT LastName as name FROM Employees;
TOP & ORDER BY Clause:
TOP
Returns a certain number of records that fall at the top or the bottom of a range
specified by an ORDER BY clause. Suppose you want the names of the top 25 students from the class
of 1994:
SELECT TOP 25
FirstName, LastName
FROM Students
WHERE GraduationYear = 1994
ORDER BY GradePointAverage DESC;
If you don't include the ORDER BY clause, the query will return an arbitrary set of 25 records
from the Students table that satisfy the WHERE clause. The TOP predicate doesn't choose between
equal values. In the preceding example, if the twenty-fifth and twenty-sixth highest grade point
averages are the same, the query will return 26 records. You can also use the PERCENT reserved word
to return a certain percentage of records that fall at the top or the bottom of a range specified by an
ORDER BY clause. Suppose that, instead of the top 25 students, you want the bottom 10 percent of the
class:
SELECT TOP 10 PERCENT
FirstName, LastName
FROM Students
WHERE GraduationYear = 1994
ORDER BY GradePointAverage ASC;
The ASC predicate specifies a return of bottom values. The value that follows TOP must be an
unsigned Integer. TOP doesn't affect the query's updatability.
GROUP BY Clause:
Syntax:
SELECT fieldlist
FROM table
WHERE criteria
GROUP BY groupfieldlist
This example creates a list of unique department names and the number of employees in each of those
departments.
SELECT Department, Count([Department]) AS Tally FROM Employees GROUP BY
Department;
HAVING Clause:
Syntax:
SELECT fieldlist
FROM table
WHERE selectcriteria
GROUP BY groupfieldlist
HAVING groupcriteria
This example selects the job titles in the Production department assigned to more than 50 employees.
SELECT Title, Count(Title) FROM Employees WHERE Department = 'Production' GROUP
BY Title HAVING Count(Title) > 50;
INNER JOIN:

47

VISUAL BASIC
Inner join is used to connect two tables.
Syntax:
SELECT Field name FROM table1 INNER JOIN table2 ON table1.field1 compare
table2.field2
SELECT DISTINCTROW Sum(UnitPrice * Quantity) AS [Sales], FirstName & " " &
LastName AS Name FROM Employees INNER JOIN(Orders INNER JOIN [Order Details]
ON Orders.OrderID = [Order Details].OrderID) ON Employees.EmployeeID =
Orders.EmployeeID GROUP BY FirstName & " " & LastName;

5.2 Cross Tab Queries


A crosstab query displays summarized values (sums, counts, and averages) from one field in a table
and groups them by one set of facts listed down the left side of the datasheet and another set of facts
listed across the top of the datasheet. For an example of a crosstab query
Syntax:
Sum(expr)
First(expr)
Last(expr)
Min(expr)
Max(expr)
Count(expr)
Avg(expr)
SELECT Sum(UnitPrice * Quantity)
AS [Total Revenue] FROM [Order Details];
SELECT First(LastName), Last(LastName) FROM Employees;
The next two examples compare using the First and Last functions with simply using the Min and Max
functions to find the earliest and latest birth dates of Employees.
SELECT First(BirthDate), Last(BirthDate) FROM Employees;
SELECT Min(BirthDate), Max(BirthDate) FROM Employees;
SELECT Count(ShipCountry)AS [UK Orders] FROM Orders WHERE ShipCountry = 'UK';

5.3 Action Queries


An action query is a query that makes changes to many records in just one operation. There
are four types of action queries: make-table, delete, append, and update.
Make-table query
Creates a new table from all or part of the data in one or more tables. Make-table queries are helpful
for:
Creating a table to export to other Microsoft Access databases. For example, you might want to create a
table that contains several fields from your Employees table, and then export that table to a database
used by your personnel department.
Syntax:
CREATE TABLE table (field1 type [(size)] [index1] [, field2 type [(size)] [index2] [, ...]] [,
multifieldindex [, ...]])
This example creates a new table called MyTable with two Text fields, a Date/Time field, and a
unique index made up of all three fields.

48

VISUAL BASIC
CREATE TABLE MyTable (FirstName TEXT, LastName TEXT, DateOfBirth DATETIME,
CONSTRAINT MyTableConstraint UNIQUE (FirstName, LastName, DateOfBirth));
Delete query
Deletes a group of records from one or more tables. For example, you could use a delete query to
remove products that are discontinued and for which there are no orders. With delete queries, you
always delete entire records, not just selected fields within records.
Syntax:
DELETE [table.*]
FROM table
WHERE criteria
DELETE * FROM Employees WHERE Title = 'Trainee';
DELETE Employees.* FROM Employees INNER JOIN Payroll ON Employees.EmployeeID
= Payroll. EmployeeID WHERE Employees.Title = 'Trainee';
Append query
Adds a group of records from one or more tables to the end of one or more tables. For example,
suppose that you acquire some new customers and a database containing a table of information on
those customers. To avoid typing all this information in, youd like to append it to your Customers
table. Append queries are also helpful for:

Appending fields based on criteria. For example, you might want to append only the names and
addresses of customers with outstanding orders.
Appending records when some of the fields in one table dont exist in the other table. For example,
in the Northwind sample database, the Customers table has 11 fields. Suppose that you want to
append records from another table that has fields that match 9 of the 11 fields in the Customers
table. An append query will append the data in the matching fields and ignore the others.

Syntax:
Multiple-record append query:
INSERT INTO target [IN externaldatabase] [(field1[, field2[, ...]])]
SELECT [source.]field1[, field2[, ...]
FROM tableexpression
Single-record append query:
INSERT INTO target [(field1[, field2[, ...]]
Error! No table of contents entries found.)]
VALUES (value1[, value2[, ...])
Update query
This example creates a new record in the Employees table.
INSERT INTO Employees (FirstName,LastName, Title) VALUES ("Harry", "Washington",
"Trainee");
This example selects all trainees from a hypothetical Trainees table who were hired more than 30
days ago and adds their records to the Employees table.

49

VISUAL BASIC
INSERT INTO Employees SELECT Trainees.* FROM Trainees WHERE HireDate < Now() 30;
Update Table
Syntax:
UPDATE table
SET newvalue
WHERE criteria;
This example increases the UnitPrice for all nondiscontinued products from supplier 8 by 10 percent.
UPDATE Products SET UnitPrice = UnitPrice * 1.1 WHERE SupplierID = 8 AND
Discontinued = No;

5.4 SQL Queries


An SQL query is a query you create using an SQL statement. Some examples of SQL-specific queries
are the union query and subqueries.
Union query
This type of query combines fields (columns) from one or more tables or queries into one field or
column in the query's results. For example, if you have six vendors that send new inventory lists each
month, you can combine these lists into one result set using a union query, and then create a make-table
query based on the union query to make a new table.
Syntax:
[TABLE] query1 UNION [ALL] [TABLE] query2 [UNION [ALL] [TABLE] queryn [ ... ]]
This example retrieves the names and cities of all suppliers and customers in Brazil.
SELECT CompanyName, City FROM Suppliers WHERE Country = "Brazil" UNION
SELECT CompanyName, City FROM Customers WHERE Country = "Brazil";
Subquery
This type of query consists of an SQL SELECT statement inside another select query or action query.
You can use subquery to:

Test for the existence of some result from the subquery (using the EXISTS or NOT EXISTS
reserved words).
Find any values in the main query that are equal to, greater than, or less than values returned by the
subquery (using the ANY, IN, or ALL reserved words).
Create subqueries within subqueries (nested subqueries).

A Subquery is a SELECT statement nested inside a SELECT, SELECT...INTO, INSERT...INTO,


DELETE, or UPDATE statement or inside another subquery.
Syntax:
You can use three forms of syntax to create a subquery:
comparison [ANY | ALL | SOME] (sqlstatement)
expression [NOT] IN (sqlstatement)
[NOT] EXISTS (sqlstatement)
This example lists the name, title, and salary of every sales representative whose salary is higher than
that of all managers and directors.

50

VISUAL BASIC
ALL
SELECT LastName, FirstName, Title, Salary FROM Employees WHERE Title LIKE "*Sales
Rep*" AND Salary > ALL (SELECT Salary FROM Employees WHERE (Title LIKE
"*Manager*") OR (Title LIKE "*Director*"));
EXISTS
SELECT CompanyName FROM Customer WHERE EXISTS (SELECT * FROM Orders
WHERE Customer.CustomerID = Orders.CustomerID)
NOT EXISTS
SELECT CompanyName FROM Customer
WHERE NOT EXISTS (SELECT * FROM Orders
WHERE Customer.CustomerID = Orders.CustomerID)
This example lists the Firstname of employees who is working in ACCT, PRCH, PERSN departments
only.
IN
SELECT FirstName FROM Employees
WHERE DeptCode
IN (ACCT, PRCH,PERS)
This example lists the Firstname of employees who is working in all the departments except ACCT
department.
NOT IN
SELECT FirstName FROM Employees
WHERE DeptCode
NOT IN (ACCT)

5.5 Relationships
Defining relationships
You define a relationship by adding the tables you want to relate to the Relationships window, and then
dragging the key field from one table and dropping it on the key field in the other table.
How do relationships work?
A relationship works by matching data in key fields usually a field with the same name in both tables.
In most cases, this will be the "primary key" from one table, which provides a unique identifier for each
record, being matched with an entry in the "foreign key" in the other table. For example, employees can
be associated with orders they're responsible for by creating a relationship between EmployeeID fields.
A one-to-many relationship
A one-to-many relationship is the most common type of relationship. In a one-to-many relationship, a
record in Table A can have many matching records in Table B, but a record in Table B has no more
than one matching record in Table A. For example, the Suppliers and Products tables have a one-tomany relationship: each supplier provides many products, but each product comes from only one
supplier.
A many-to-many relationship
In a many-to-many relationship, a record in Table A can have many matching records in Table B, and
vice versa. This is only possible by defining a third table (called a junction table) whose primary key
consists of at least two fields the foreign keys from both Table A and B. For example, the Orders
table and the Products table have a many-to-many relationship that's defined by creating two one-tomany relationships to the Order Details table.
A one-to-one relationship
In a one-to-one relationship, a record in Table A can have no more than one matching record in Table
B, and vice versa. This type of relationship is not common, because most information related in this

51

VISUAL BASIC
way would be in one table. You might use a one-to-one relationship to divide a wide table, to isolate
part of a table for security reasons, or to store information that only applies to a subset of the main
table. For example, you might want to create a table to track employees participating in a fundraising
soccer game.

A one-to-many relationship is created if only one of the related fields is a primary key or has a
unique index.
A one-to-one relationship is created if both of the related fields are primary keys or have unique
indexes.
A many-to-many relationship is really two one-to-many relationships with a third table whose
primary key consists of two fields the foreign keys from the two other tables.

Primary key
You can use the Primary property to specify whether the index is the primary key for the table. A
primary key uniquely identifies each record in a table and prevents you from entering duplicate values
in a primary key field.

Foreign key
Foreign key is a column or group of column in a table that corresponds to or references a primary key
in another table in the database. A foreign key need not be unique, but it must uniquely identify the
column in the table that it references.

5.6 Querying a Database


To work with the data in a database, you can use queries to manipulate or extract data. A
query either asks the database for a set of records matching specified criteria (a SELECT query), or
tells the database to perform a specified operation on a set of records that match specified criteria (an
action query).
You can use a data control's RecordSource property to query the database, or you can use one
of the Find methods with a data control's Recordset property.
Using an SQL query with a data control

Design your query so the database returns only the records you want.
Enter the SQL statement in the RecordSource property. You can do this at design time or run
time. At run time, you can use this code:
Data1.RecordSource = "SELECT * FROM Employees WHERE Salary >= 10000'"

At run time, use the Refresh method to recreate the data control, ie rearranging data in the
database:
Data1.Refresh

In your program you can use variables also


For example you want to select all the details about a particular employee, you can define a variable
and assign employee code to that. You can compare this variable with the following query statement.
Dim empcode as integer
Data1.RecordSource = SELECT * FROM Employees WHERE Empid = & empcode
data1.refresh
If empid data type is defined as integer in your database you can use this format. If empid datatype is
defined as string you have to use the following format.

52

VISUAL BASIC
Dim empcode as string
Data1.RecordSource = SELECT * FROM Employees WHERE Empid = & & empcode &
data1.refresh

53

VISUAL BASIC

6. MENUS AND DIALOG BOXES


6.1 Menus
6.1.1 Creating menus at design time.
Menus can be created using the Menu Editor Dialog Box as shown in figure below.

Fig 6.1 Menu Editor


Dialog Box Options
Caption Allows you to enter the menu or command name that you want to appear on your menu bar or
in a menu.
If you want to create a separator bar in your menu, type a single hyphen (-) in the Caption box.
To give the user keyboard access to a menu item, insert an ampersand (&) before a letter. At run time,
this letter is underlined (the ampersand is not visible), and the user can access the menu or command by
pressing ALT and the letter. If you need an ampersand to show in the menu, put two consecutive
ampersands in the caption.
Name Allows you to enter a control name for the menu item. A control name is an identifier used only
to access the menu item in code; it doesn't appear in a menu.
Index Allows you to assign a numeric value that determines the control's position within a control
array. This position isn't related to the screen position.
Shortcut Allows you to select a shortcut key for each command.
HelpContextID Allows you to assign a unique numeric value for the context ID. This value is used to
find the appropriate Help topic in the Help file identified by the HelpFile property.
NegotiatePosition
Allows you to select the menu's NegotiatePosition property. This property
determines whether and how the menu appears in a container form.
Checked Allows you to have a check mark appear initially at the left of a menu item. It is generally
used to indicate whether a toggle option is turned on or off.

54

VISUAL BASIC
Enabled Allows you to select whether you want the menu item to respond to events, or clear if you
want the item to be unavailable and appear dimmed.
Visible Allows you to have the menu item appear on the menu.
WindowList Determines if the menu control contains a list of open MDI child forms in an MDI
application.
Right Arrow
Moves the selected menu down one level each time you click it. You can create up to four levels of
submenus.
Left Arrow
Moves the selected menu up one level each time you click it. You can create up to four levels of
submenus.
Up Arrow
Moves the selected menu item up one position within the same menu level each time you click it.
Down Arrow
Moves the selected menu item down one position within the same menu level each time you click it.
Menu List A list box that displays a hierarchical list of menu items. Submenu items are indented to
indicate their hierarchical position or level.
Next Moves selection to the next line.
Insert Inserts a line in the list box above the currently selected line
Delete Deletes the currently selected line.
OK Closes the Menu Editor and applies all changes to the last form you selected. The menu is
available at design time, but selecting a menu at design time opens the Code window for that menu's
Click event rather than executing any event code.
Cancel Closes the Menu Editor and cancels all changes.

6.1.2 Creating a menu Control Array


A menu Control Array is a set of menu items on the same menu that share the same name and event
procedures. Use a menu control array to:
create a new menu at runtime. Text editor for eg. Uses a menu control array to store a list of opened
files while the application is running.
Simplify code since common blocks of code can be used for the same menu item.
All menu items in the control array have the same Name but different captions and indices. Their index
should start form 0 and go on as 1,2 etc. Since the name is the same, the menuitems are identified by
their index.

6.1.3 Controlling the menus at Run time.


If a menu item action becomes inappropriate at some point of time, it can be disabled. Look through the
code for examples.

55

VISUAL BASIC
Displaying a check mark on a menu control.
Using the checked property, you can place a check mark on the menu to:
Tell the user the status of an on/off condition.
Indicates which of several modes is in effect. For eg, the current font size.
Adding menu controls at run time.
You must use a control array to create a control at runtime. One can create a new index and load a
menu item to the control array. See the procedure UpdateMenu given below.

6.1.4 Example program


This example program has Form1 with a menu bar with the following items.
Caption

Name

Index

Cut and paste


mCut
Font
mFont
. mSep
.12
Fsize
1
.mSep1
.14
Fsize
2
File
File
.
Mfile
0
mFile is a control array with on element of index 0. MFont is control array with 2 elements.
Form1 has 2 Text Controls, Text1 and Text2. A command button Form2 when clicked displays the
form Forrm2.
The program performs as follows.
1.

When Text1 is empty, the menuitem Cutandpaste is diabled as shown in fig2. When you enter data
in text1 the menuitem is enabled. See procedure Text1_Change

2.

After selecting text in Text1, The menuitem Cutandpaste is clicked to cut the text and paste in
Text2. See procedure mCut_Click.
The fonts of Text1 and Text2 can be chaged to size 12 or 14 using Font menuitem. The selection
will be indicated using a check mark. See procedure Fsize_click.
When the button Form2 is clicked, form2 is displayed. If data is entered in the text box and OK is
clicked, the contents of text box in Form2 appears in Text1 in Form1. See ComForm2_Click and
procedure but_click of form2. At the same time the text entered in Form2 is appended to the
Control array mFile by a call to UpdateMenu. See procedure ComForm2_Click and UpdateMenu.

3.
4.

General

Declarations

Dim ind As Integer


Dim Selected As String

Declarations made in general, declarations


are available for all procedures in the
corresponding form
General procedure (subroutine of function) Which can be
called in any of the procedures of the corresponding form.

Sub UpdateMenu()
ind = ind + 1
Load mFile(ind)
mFile(ind).Caption = Selected
mFile(ind).Visible = True

Set a new index and load the menuitem

End Sub

56

VISUAL BASIC

Procedure that is executed when form is


loaded

Procedure on Form1 load


Private Sub Form_Load()
ind = 0
Text1.Text = Form2.Text1.Text
End Sub

Porcedure when menu item 12 or 14 is clicked in the popup menu of main menuitem Font.
Private Sub Fsize_Click(Index As Integer)
Select Case Index
Case 1
Text1.FontSize = 12
Text2.FontSize = 12
Fsize(1).Checked = True
Fsize(2).Checked = False
Case 2
Text1.SelText
Text1.FontSize = 14
Text2.FontSize = 14
Fsize(2).Checked = True
Fsize(1).Checked = False
End Select
End Sub

Changing font size of text control Text1 and Text2 to


12. Font 12 has index 1 and 14 has index 2 in menu

Menuitem Name.Checked = True checks the menuitem


Menuitem Name.Checked = false unchecks it.

Procedure when menuitem Cut and paste is clicked


Private Sub mCut_Click()
Clipboard.SetText Text1.SelText
Text2.SelText = Clipboard.GetText
Selected = Clipboard.GetText
Text1.SelText = ""
End Sub

The text selected in the control Text1 is


copied to clipboard

Contents of Text1 is cleared

Procedure when the text in control Text1 changes.


Private Sub Text1_Change()
If Text1.Text = "" Then
mCut.Enabled = False
Else
mCut.Enabled = True

A menu item is disabled by setting its


enabled property to False

End If
End Sub

Procedure when Command button named ComForm2 caption Form2 is clicked


Private Sub ComForm2_Click()
Form2.Show 1
Text1.Text = Form2.Text1.Text
Selected = Form2.Text1.Text
UpdateMenu

Displays Form2 as a modal dialog box


Form2.show will display Form2 as a modeless dialog
b
The general procedure is being called

End Sub

57

VISUAL BASIC

Procedure when buttons OK or Cancel is clicked in Form2.


OK and Cancel command buttons have the same name but their indices are 1 and 0 respectively.
Private Sub but_Click(Index As Integer)
Select Case Index
Case 1
Text1.Text = ""
End Select
Hides Form2 when ok or Cancel button of
Form2.Hide
Form 2 is Clicked
End Sub

6.2 Dialog boxes


In Windows based application, a Dialog Box is used to:
1.
2.

Promp the user for data needed by the application to continue.


Display information to the user.

6.2.1 Modal And Modeless Dialog Boxes.


Dialog Boxes are either modal or modeless. A modal Dialog box must be closed (hidden or unloaded)
before you can continue working with the rest of your application.
The show method with style argument 1 displays a modal dialog box.
Form2.Show 1
Modeless dialog boxes let you shift the focus between Dialog box and another form without having to
close the dialog box. You can continue to work else where in the current application while the dialog
box is displayed.
Show method without style argument displays a modeless dialog box.
Form2.Show

6.2.2 Using pre defined Dialog Boxes.


InputBox function

Display a prompt in a Dialog box and return the text entered by the user.

Eg.
FileName = InputBox(Enter file to open:, File Open)
MsgBox statement

Display a message in a Dialog Box.

MsgBox Function
Display a message in a dialog box, and return a value indicating the
command button clicked by the user.

6.2.3 Creating a custom Dialog Box.


A form with the controls required forms a dialog box.
Use Form.caption = About to chage the caption to About.

58

VISUAL BASIC
The other properties often changed are
Property
Setting
Borderstyle
0,1,2,3,4 or 5
0
None
1
Fixed Single
2
Sizable and soon.
ControlBox
Min button
Max button

True/False
True/False
True/False

6.2.4 Displaying a custom Dialog box


Use Load or Show to Display.
Load Form1
Form1.Show
Use hide or unload to close the dialog visually.
Unload Form2
Form2.Hide

59

VISUAL BASIC

7. VISUAL BASIC REPORT


7.1 Definition
A report is simply an organized presentation of data. As a management tool, a report is used to provide
management with the insight it needs to run an organization effectively. Crystal Reports allows you to
create comprehensive, customized, attractive management reports quickly and easily. But report in
Crystal Reports means much more. It also refers to invoices, form letters, mailing labels, and other
related items that require the organization and output of data.

Visual Basic can produce report in using two methods

 Using Crystal report (Report designer)


 Writing VB code by using Printer object method & Print form method

7.2 Using Crystal reports


7.2.1 What is Crystal Reports?
Crystal Reports is a powerful report generator for creating custom reports, lists and form
letters using data from existing databases. It is producing reports with the standard report generation
features built in to the database software. Report generator is the term used to describe this feature of
software that produces custom report without programming. No Program code had to be written to get
the report. Crystal Report can build reports using the standard data files generated by
dBASE(III,II+,IV), Foxpro, Access, Paradox, Clipper. Since many program can export data in dBASE
format(.dbf files), you will find that you can use Crystal Reports to create reports with virtually any
database. It is designed to work with all kinds of data: numbers, currency, text, dates, and Boolean
(Yes/No) fields. It has a wide range of built-in tools that you can use to manipulate that data to fit your
needs. This add-in report writer is supplied with Visual basic as a part of it.
Crystal Reports is a powerful Windows report writer that you can use to design a nearly endless variety
of custom reports. Using Crystal Reports, you can design the report or reports you want your users to
be able to call up from your application. You can think of the Crystal Reports package as containing
two separate elements: Crystal Reports, and the Crystal Custom Control. Used together, these two
elements give you the ability to generate custom reports, transparently, via your application. From
Visual Basic Window menu, select the Report designer for Crystal Basic for Visual Basic(CRVB).

7.2.2 How CR create reports..?


CR prepares reports by reading data in the database files you have selected and making that
data available for use in your report.

 when you wish to use data in a single data file, simply choose that file when you create
the report
 if you wish to use data in multiple data files, select the files and also to indicate the
field or fields in each file that CR is to use to match data. Then user has to select a
linking fields which might be a field common in both databases. Once the linking field
is identified. Crystal Reports matches up the data.

60

VISUAL BASIC
7.2.3 Crystal Reports Window

Minimize and Maximize buttons appear in the upper right hand corner of the window
The Minimize and Maximize buttons serve the same purpose for mouse users as the Minimize and
Maximize options on the System menu serve for keyboard users.
Title Bar appears at the top of the window
The Title Bar displays the name of the program running in the window, Crystal Reports. You can use
the title bar to activate the window (if the window is buried in a cascade of windows) or to move the
window (by depressing the left mouse button with the pointer on the title bar and then, while the button
is still depressed, dragging the window to a new location), or to maximize the window (by double
clicking on the title bar).
Menu Bar appears just below the Title Bar
The Menu Bar is Crystal Reports' command center. Each option on the menu bar calls up a drop down
menu of commands that you can use to create, modify, print, and save your reports.
File

The File menu includes commands you can use to open, close, and save files, to save files
under a different file name, print the file to a printer, compile your report, and create new
report files. It also includes a command you can use to exit Crystal Reports. Additionally it
contains a command that allows you to configure Crystal Reports to your specifications. File
Menu Commands are New Report, New Mailing Labels Report, Open Report, Save, Save As,
Close, Print To Printer, Options, Exit
Edit
The Edit menu allows you to modify aspects of your report. The menu includes commands
you can use to edit formulas, text fields, and summary operations, to review field data, to
change the position of items in a stack, to change the report title, or to delete group sections. It
also contains commands for cutting, copying, and pasting text, and clearing (deleting) report
elements, and toggling the display of field names on and off. Edit Menu Commands are Cut,
Copy, Paste, Clear, Formula, Text Field, Summary Operation, Browse Field Data, Send
Behind Others, Group Section, Delete Section, Show field names, Report Title.
]Insert The Insert menu is the central menu you use for creating reports. The menu includes
commands you can use to insert database, text, and formula fields; subtotals, grand totals,
summaries (counts, averages, etc.), and group sections; print date, page number, record
number and group number fields; and graphics, lines, and boxes. Insert Menu Commands are
Database Field, Text Field, Formula Field, Subtotal, Grand Total, Summary, Group Section,
Print Date Field, Page Number Field, Record Number Field, Group Number Field, Graphic,
Line, Box.
Format

The Format menu includes commands for changing the look of the elements in your report.
It includes commands for changing fonts, adding borders and colors and formatting fields,
graphics, lines, and boxes. It also includes a command for formatting report sections.
Format Menu Commands are Font, Field, Border and Colors, Graphic, Line, Box, Section.
Database The Database menu is used to select and delete databases for use with your reports, to
change the alias you use to identify the database, and to link and unlink databases. It also

61

VISUAL BASIC
has a command, File Location, for directing Crystal Reports to look for database files in
new locations. Database Menu Commands are File Links, Add File to Report, Remove File
from Report, File Location, File Alias, Verify Database, Verify on Every Print.
Print The Print menu includes commands that let you print your report to a print window, to a
file, or to a printer, print the report definition (a report describing your report), select the
records or groups to be included in your report, select printers, set up printer margins, and
select the order in which report data is to be sorted (by record or by group). Print Menu
Commands are Print To Window, Print To Printer, Print To File, Print Report Definition,
Select Printer, Set Printer Margins, Select Records, Edit Record Selection Formula, Select
Groups, Edit Group Selection Formula, Record Sort Order, Group Sort Order.
Window The Window menu includes commands that let you rearrange icons and windows. It also
lists the report windows that are open and includes a command that lets you close all report
windows at once, if desired. Window Menu Commands are Tile, Cascade, Arrange Icons,
Close All,
Help
The Help menu includes a command that takes you to Crystal Reports' main help index,
and a command that will give you information about the Crystal Reports version you are
using.
Button Bar appears just below the Menu Bar.
Crystal Reports groups several commonly--used commands on a Button Bar that remains on screen at
all times (unless you choose to turn it off).
Insert Text Field- Insert Formula Field- Insert Box- Print to
Printer

New Report
Save Cut Copy Paste Insert Database Field Insert Graphic Print to Window
Open Report
Insert Summary
Insert Line Print to File

You activate Button Bar commands by clicking the appropriate button one time with the left mouse
button.
The Button Bar eliminates some of the steps needed to activate the included commands, and it can thus
greatly speed your work in creating reports.

7.2.4 The Report Editor


Once you select your database, Crystal Reports displays the Report Editor screen. You use this screen
to insert and format data and to watch your report take shape.
When you open a new report, Crystal Reports automatically creates three sections in the Report Editor
Ref figure in next page.
Page header section this section is generally used for the report title, field headings, range of values
included, and other information that you want to appear at the top of each page. By default, the Page
header section has room for three lines.

62

VISUAL BASIC

Details section this section is the body of the report. The bulk of your report data will generally appear
in this section. By default, the Details section has room for one line.
Page footer section this section usually contains the page number and any other information that you
want to appear on the bottom of each page. By default, the Page footer section has room for three lines.
Each section is separated by a section marker which displays the section name.
You build your report by inserting data fields, formulas, and other report elements (record counts,
record numbers, etc.) in the Details section of the Editor. You use the Insert menu, in most cases, to
select or create the elements you want to insert on the report. The Report Editor uses rectangular field
boxes to indicate the size, position, and data type of the fields and formulas you have inserted.

7.2.5 Creating a Crystal report


Windows user who wants to get right into the Crystal Report designer, follow these steps to set up a
Crystal Reports report for the first time.
1.

Start Crystal Reports by double clicking on the Crystal Reports icon in the Program Manager.

2.
3.

Select New Report from the File menu.


When the Choose Database File dialog box appears, select the first database you want to activate
from your report and Click OK when finished.
You build your report by inserting data fields, formulas, and other report elements (record counts,
record numbers, etc.) in the Details section of the Editor. You use the Insert menu, in most cases,
to select or create the elements you want to insert on the report. The Report Editor uses rectangular
field boxes to indicate the size, position, and data type of the fields and formulas you have
inserted.
You add subtotals (and other group values) by selecting a field to subtotal and then telling Crystal
Reports the conditions that are to generate a new subtotal or group value(change of customer
number, change of sales rep, etc.). Crystal Reports creates group sections as needed and places the
group value in the section. Again, Crystal Reports uses rectangular field boxes to represent the
group values.

63

VISUAL BASIC

You insert grand totals in the Grand Total section. This section appears when you select the field
to total and then select Insert|Grand Total or when you opt to place a summary field in the Grand
Total section. In both cases, Crystal Reports uses a rectangular field box, this time to identify the
field in the Grand Total section of the Report Editor.
You can add freeform text anywhere on the report by positioning the insertion point in the section
in which you want the text to appear, typing in the text, and then using the Tab key to move it into
position. You can also type freeform text as a formula; this allows you to avail yourself of
additional formatting options (alignment, hide options, etc.)
The Crystal Reports Report Editor appears with Page Header, Details, and Page Footer sections set
up on your report template. The sections are all blank initially. You create your report by inserting
and formatting items in each of these sections.
4.

The Insert Database Field dialog box appears on screen with the Report Editor. The Insert
Database Field dialog box displays a list of all of the fields in the active database. To speed the
entry of multiple fields, the box remains on screen until you Click on the Done button. You can
move the dialog box to a new location if you wish.

5.

Select the first field you want to appear on the report. A rectangular placement cursor appears.

6.

Position the cursor at the point in the Details section where you want your field to appear, and
Click the left mouse button to enter it. Crystal Reports marks the field position with a rectangular
box. The characters in the box indicate whether the field is text (XXX...), number (555,...), dollar
value ($555,...) date (YYYY--M...), or Boolean (T/F). The number of characters in the box
indicate the number of characters allowed for the field in the database from which it came.

7.
8.

Repeat Steps 5 and 6 until you have placed all the fields you want to place.
To create a title, select Insert|Text Field, type in the information you want to appear, Click Accept
when finished, and position the field where you want it in the Page Header section. You can also
insert database fields or special fields in that section from the insert menu.

9.

To see how your results will print, select Print To Window from the Print menu. Close out the
window when you are finished with your review.

10. If you want to: change the placement or width of a field,


grand total for a field, or delete a field,

format the field, insert a subtotal or

Click the field box for that field. Black handles appear on the right and left sides of the field box to
indicate that it has been selected. To change the placement of the field, drag the field box to its
new position using the mouse or the arrow keys. The arrow keys move the field box one grid
position each time you press them.
To change the width of the field, drag the right or left handle using your mouse or use a Shift-Arrow combination on your keyboard.
To format or subtotal the field, Click the right mouse button while the cursor is inside the field. A
pop--up menu appears listing your various options.

To change the font, select Change Font and refine your selection using the Font dialog box when it
appears.

To change the format (alignment within field; number, currency, or date display; etc.) select
Change Format and refine your selection using the Field Format dialog box when it appears.

To insert a subtotal, select Insert Subtotal and refine your selection using the Insert Subtotal dialog
box when it appears. In this dialog box you select the sort and group by field, the condition that

64

VISUAL BASIC

Triggers a new subtotal whenever the field's value changes, and the sort direction: Ascending (A to
Z, 1 to 9) or Descending (Z to A, 9 to 1).
NOTE: The program automatically sorts the data (based on the field that triggers the subtotals)
before it subtotals. You don't have to manually enter a subtotal sort.

-- To insert a grand total (or a grand total average, a grand total count, etc.), select Insert Grand Total.
-- To delete the field, select Delete Field.
11. If you want to create a formula to make data calculations or comparisons, select Formula from the
Insert menu. Enter a name for your formula in the Insert Formula dialog box, and enter the formula
itself in the Formula Editor when it appears. Enter fields, operators, and functions by selecting
them from their respective boxes. You can get complete information on each available Function
and Operator via the Help button, and you can check your formula syntax via the Check button.
Entering a Crystal Reports formula is similar to entering a formula in a spreadsheet cell. When
finished editing, Click Accept and place the formula just like you do a database field.
14. To change the sort order, select Record Sort Order from the print menu. Select the field(s) you want
Crystal Reports to use for sorting the report data.
15. To change the sort and group by field, select Group Section from the Edit menu. Select the group
section of interest from the list that appears in the Edit Group Section (sections) dialog box, and
select the new trigger field from the Edit Group Section (edit) dialog box when it appears.
16. If you want to limit your report to specific records (for example, the records of California
customers that have YTD sales greater than $10,000), Click the first field on which you want your
selection to be based (in this case the State field) and choose Select Records from the Print menu
or the right mouse button pop--up menu. Answer the questions that appear in the Select Records
dialog box and Click OK when finished. If your selection is based on more than one field, repeat
the process with the remaining field(s) until you have completed entering your selection
specifications.
17. When finished, you can print your report by selecting Print To Printer from the Print menu.

7.2.6 Creating A New Report


Selecting a database
Use File|New Report to create a new report.
When you use the New Report command while using another report, Crystal Reports creates a new
report window and opens the new report in that window. The report you were working on remains
unchanged in its own Report window.
To use File|New Report
1.
Select File|New Report, the Choose Database File dialog box appears. A box displays the
current database specification.If you know the name of the database you want to activate, type the
name in this edit box. Include the path if different than the path currently displayed in the Directories
heading. If you don't know the name of the database you want to activate, but you do know the kind of
database it is (.mdb, .db, .dbf, etc.), type in the new specification or select the database type from the
List Files of Type scroll box. This will change the current database specification to the database type of
your choice. If you want to display all files, type in *.*
A scroll box displays a list of those files in the selected directory that match the specification in the File
Name edit box.
If you haven't typed a database name in the File Name edit box, or if you are uncertain of the file name,
select the database you want from the list of database files that Crystal Reports displays in this scroll
box.
.mdb files

65

VISUAL BASIC

To activate an Access table, you can select any .mdb file. Crystal Reports activates all of the tables in
the selected file. If you want to activate more than one of the tables in the .mdb file, it will be
necessarry for you to specify linking fields via the File Links dialog box.
If you haven't typed a database name in the File Name edit box, or if you are uncertain of the file name,
select the database you want from the list of database files that Crystal Reports displays in this scroll
box.
Linking the databases
You link databases so that records from one database will match up with records from another. For
example, if you activate a Customer database and an Order database, you link the databases so that
orders in the Order database can be matched up with the customers (from the Customer database) who
placed the orders.
Links are fields that are common to the two databases. The fields don't have to have the same name;
but they must have the same structure (size, data type), and contain the same kind of data.
When you activate additional databases using the Database|Add File to Report command, Crystal
Reports takes you directly to the Define Link dialog box. You use this dialog box to establish the link
between the database you are activating and a database which is already active..
If you later wish to create new links, or update or delete existing links, you use the Database|File Links
command which takes you to the File Links dialog box .You use this dialog box for a variety of linking
activities.
Inserting fields Use Insert|Database Field to place data fields from an active database on your report.
To use Insert|Database Field
1.

Select Insert|Database Field. The Insert Database Field dialog box appears listing all of the fields
in the active database(s).
You use this dialog box to select the fields you want to include in your report. Use the Insert button to
insert the highlighted field. You can bypass the insert button by simply double clicking the field you
want to insert. Use Done to close out the dialog box when you are finished entering fields

2.
3.

4.
5.

Select the field of interest. Crystal Reports


displays the insertion cursor.
Move the cursor to the desired insertion
point and Click the left mouse button to
enter the field at that point.
Repeat Steps 2 and 3 until you have
inserted all the fields you want to insert.
Click on Done when finished, and the
dialog box disappears.

You set spacing between data fields by placing the fields where you want them in the Report Editor
(using the mouse or Arrow keys), checking your spacing using the Print|Print to Window command,
and then fine--tuning the spacing , again in the Report Editor.
You can change fonts quickly for any field value or text string in your report using the Font dialog box.
To change fonts for a field value select the field(s) for which you want to change the font. Select

66

VISUAL BASIC
Format|Font or Click the right mouse button and select Change Font from the pop--up menu. The Font
dialog box appears. Make the font, style, size, color, and/or effects changes you want and Click OK
when finished.
Creating page headers and foot headers
To insert page headers and footers, insert page headers and footers by placing the desired information
in the appropriate section of the report editor. header information goes in the Page header section and
footer information goes in the Page footer section. Any information you place in these sections prints
on each page of the report (unless you take special steps to prevent some printing). You can use text,
fields, or formulas in these sections just as you can in the Details section.
Creating group headers
Crystal Reports allows you to place incremental headers above each group in your report. This feature
allows you to give your reports a polished, professional appearance. Whenever you insert a group,
Crystal Reports creates two new sections on your report. One section, the Group Footer section,
appears below the Details section. This section holds the group value field itself. A matching section,
the Group Header section appears above the Details section. Anything you place in this section will
appear as a header for your group.
A report is simply an organized presentation of data. As a management tool, a report is used to provide
management with the insight it needs to run an organization effectively. Crystal Reports allows you to
create comprehensive, customized, attractive management reports quickly and easily. But report in
Crystal Reports means much more. It also refers to invoices, form letters, mailing labels, and other
related items that require the organization and output of data.
Crystal Reports gives you the ability to insert special fields in your reports (in addition to the data
fields you draw from databases). These special fields allow you to insert dates, page numbers, and
group and record numbers in your report.

Inserting page numbers/date/record numbers fields


Use Insert|Print Date Field to insert a field that prints whatever is the current date when the report
prints. Use Insert|Page Number Field to insert a field that prints the current page number. Insert|Record
Number Field to have Crystal Reports number each record printed in the Details section of your report.
When you select any of these special fields, a rectangular placement cursor appears. Move the cursor to
the point where you want to insert the field and Click the left mouse button to place it.
Grouping data with Crystal Reports
Grouping data means breaking your data into meaningful groups before it appears on your report.
Crystal Reports makes it easy to group your data, and to evaluate or perform calculations on the data
in each group should you so wish.
To do simple grouping
1.
Select the field you want to group. For example:
if you want to group a customer list by state, select the field that contains the company name,
or
f you want to group an orders report by customer, select the field that contains the order
amount.
2.
3.

Select Insert|Group Section. The Insert Group Section dialog box appears.
In the top scroll box, select the field that you want to trigger a grouping, whenever its value
changes. For example:

67

VISUAL BASIC
If you want to group a customer list by state, select the state field, or if you want to group an
orders report by customer, select the field that contains the customer name or customer
number.
4.
5.

6.

In the second scroll box, select the sort direction (in ascending order = A to Z, 0 to 9, in
descending order = Z to A, 9 to 0).
If you selected a date or Boolean field in the top scroll box, a third scroll box appears near the
bottom of the dialog box. In this scroll box, select the date or Boolean condition that finalizes
your subtotal specification.
Select OK when finished. Crystal Reports groups the data to your specifications.

Grouping, then summarizing grouped data


Sometimes you may want to go beyond mere grouping of data. You may want to first group the data
and then evaluate or perform calculations on the data in each group. You may want to sum, average, or
count the values, calculate the variance or standard deviation of the values, or determine the highest
(maximum) or lowest (minimum) value in each group.
You can sum the data using the Insert|Subtotal or Insert|Summary commands. The Insert|Subtotal
command is simply a shortcut for setting up a summary field that adds the values in each group. You
can average, count, calculate the variance or standard deviation, or determine the maximum or
minimum values using the Insert|Summary commands.
How to group and summarize grouped data
1.

2.
3.

4.

5.
6.

7.

Select the field you want to group. For example, if you want to group a customer list by state and
then count the number of values in each group, select the field that contains the company name, or
if you want to group an orders report by customer and then determine the average sized order for
each customer, select the field that contains the order amount.
Select Insert|Summary. The Insert Summary dialog box appears.
In the top scroll box, select the action you want to take on the grouped data. For example if you
want to count the number of values in each group, select Count, or if you want to average the
values in each group, select Average.
In the next scroll box, select the field that you want to trigger a grouping, whenever its value
changes. For example if you want to group a customer list by state, select the state field, or if you
want to group an orders report by customer, select the field that contains the customer name or
customer number.
In the next scroll box select the sort direction (in ascending order = A to Z, 0 to 9, in descending
order = Z to A, 9 to 0).
If you selected a date or Boolean field in the top scroll box, a third scroll box appears near the
bottom of the dialog box. In this scroll box, select the date or Boolean condition that finalizes your
subtotal specification.
Select OK when finished. Crystal Reports sorts the data, and then groups and summarizes it to
your specifications

Creating formulas
A formula is a symbolic statement of the manipulations you want performed on certain data before
it is printed on your report. If your report is to contain a {file.Sales} field and a {file.Cost} field,
for example, you may want to create an @GrossProfit field (@ designates that the field is a
formula) and designate its value as {file.Sales} -- {file.Cost}. {file.Sales} -- {file.Cost} is a simple
formula that tells Crystal Reports to subtract the value of the {file.Cost} field from the value of the
{file.Sales} field and then to print the result. You can use formulas to calculate numeric values,
compare one value to another and select alternative actions based on the comparison, join multiple
text strings into a single string, and for a multitude of other purposes.

Formula examples
.80* {file.Price}

"Dear " + TrimRight({file.FNAME})+ ":"

68

VISUAL BASIC
{file.QTY} * {file.SELPRICE}
If ({file.ONHAND}) < 5 then
"Reorder"
else
""
To insert a formula use the following steps
1.
Select Insert|Formula Field. The Insert Formula dialog box appears.
2.
Type in the name you want to use to identify the formula and Click OK when finished.
The Edit Formula dialog box (the Formula Editor) appears.
3.
Enter the formula by typing in the components or selecting them from the scroll lists
displayed in the Formula Editor.
4.
Select Check to check the syntax in your formula when finished, and fix any syntax
errors the Formula Checker identifies.
5.
When the formula has the correct syntax, select Accept and a rectangular placement
cursor appears.
6. Place the formula where you want it to appear in the report.

To have Crystal Reports generate your selection formula


1.

Select the first field/group value you want Crystal Reports to use for determining the
records/groups to be included in the report.
2.
Select Print|Select Records or Print|Select Groups, whichever is appropriate.
The Select Records or Select Groups dialog box appears, depending on your selection.
3.
Enter your selection criteria in the dialog box and Click OK when finished to return to the
Report Editor.
4.
Repeat Steps 1-- 3 for each additional field/group value you want the program to use for
selecting records/groups.
Crystal Reports will generate a selection formula based on your specifications and limit the report to
the records or groups you have specified.
Using the Formula Editor, you can build a formula that restricts your report to the records or groups
you specify. For example, to limit your report to those records with a customer number greater than
099999, you would build a record selection formula similar to this: {file.CustNumb} >> 099999"
To limit your report to those groups with a subtotal on the Amount column (triggered by changes in the
CustNumb field) less than $10,000, you would build a group selection formula similar to this
Sum({file.Amount},{file.CustNumb})< $10000
Printing a report
When you want to print your report, see what your report will look like when printed, or print the
report to a disk file, you can use one Crystal Reports' three printing options:
Print to Printer (for hard copy output)
Print to Window (to review your work)
Print to File (to print the report electronically, to a disk)
When you are creating a report, you will find yourself printing to the print window often, in order to
check placement and formatting of the various report elements. When you want to print a final or
interim copy of the report for hands--on review, you can print to the printer for hard copy output. When
you want to send a copy of the report to another office, or when you need to export report data so it can
be used in other applications (spreadsheets, word processors, etc.), you can print to file.

7.3 VB code by using Printer object & Print form method.


We can cause text to appear directly on a form or a picture box. When we print to a form the text
appears in a layer behind any controls that have been placed on the form. So printing to a form usually
works best on a form specifically created to hold the text. We can also print text to a Picture box
control. A picture box is a simple rectangular area in to which user can load or copy a bitmap, draw
graphics, or print text. One advantage to using a picture box is that it gives a well defined area separate
from other controls to display text and graphics.

69

VISUAL BASIC
7.3.1 Using Print Method
To print on a form or picture box, use the Print method, preceded by the name of a form, picture box,
the Printer object. The print method syntax is : [object].Print [expression list] [{;|,}]
The object is optional; if omitted, the Print method applies to the form to which the code is attached.
For example, the following statements print messages to:
A form named Myform : Myform.Print This is a form
A picture box named picMiniMsg : picMiniMsg.Print This is a picture
The current form: Print Printing in the current object/form
The Printer object: Printer.Print This text is going to printer
The expression list is the text that appears on the form or picture box. Multiple items in the expression
list must be separated by commas or semicolons, or both . In expression list , it is possible to include
values, constants and variables(either string or numeric) Positive number value in numeric item have a
leading and a trailing spaces. If we use semicolon to separate one item from next Visual Basic prints
one item after another without intervening spaces. If we use comma, VB skips to the next print zone.
Example : Print Tha value of X is ;XVAL ,and the value of Y is :;YVAL
where XVAL and YVAL are variables.
Placing a semicolon (or comma) at the end of the first statement cause the output of the next Print
statement to appear on the same line.
We can control the placement of Print output by providing CurrentX and CurrentY properties. For
example the statement Picture1.CurrentX=0 and Picture1.CurrentY=0 reset the drawing coordinates
to the upper-left corner for Picture1 and CurrentX=0 and CurrentY=0 set the same for the current form.
Cls method erases all text and graphics created in the object with previous Print and graphics methods.
It also set the drawing co-ordinate to (0,0). Example Picture1.Cls for clearing a picture box and Cls for
current form .
By default, forms and picture boxes use a coordinate system in which each unit corresponds to a twip.
(1,440 twips equal an inch and approximately 567 twips equal a centimeter). Twip is a unit of screen
measurement equal to 1/20 of a printers point. There are approximately 1440 twips to a logical inch or
567 twips to a logical centimeter the length of a screen item measuring one inch or one centimeter
when printed. A twip is a screen-independent unit used to ensure that placement and proportion of
screen elements in your screen application are the same on all display systems. Contrast with pixel, a
screen-dependent unit of measurement.
Displaying Tabular Data :
Tabular data can be displayed in a form by using the Print method by using preset tabs. If the data is no
longer than 13 characters we can use the preset tab method to print to the print zones. Each print zone
is 14 columns wide and each column is the width of the average character in the font and font size
user specify. When user insert a comma between two items in a Print method, the second item starts
printing at the next print zone. The following statements use built in tabs:

Form1.FontName = "MS Sans Serif"


Form1.FontSize = 10
Form1.Print "First Name", "Last Name", "Phone Number"
Form1.Print "----------", "---------", "------------"
Form1.Print
Form1.Print "Manoj", "Kumar K", "0495-287266"
Form1.Print "Dr. Madhu", "Mangal", "0495-287166"
Form1.Print "Mrs.Sheela", "V.S", "0495-287268"
The output of the report will be as shown in the figure

70

VISUAL BASIC

For more control over the appearance of tables, you can set your own tab positions. To specify a tab
position, call the Tab function and include the position as one of the items in a Print statement. The
syntax is : Tab (column); The above code can be rewritten by using Tab command as follows
Form1.FontName = "MS Sans Serif"
Form1.FontSize = 5
Form1.Print Tab(5); "First Name"; Tab(22); "Last Name"; Tab(35); "Phone Number"
Form1.Print Tab(5); "----------"; Tab(22); "---------"; Tab(35); "------------"
Form1.Print
Form1.Print Tab(5); "Manoj"; Tab(22); "Kumar K"; Tab(35); "0495-287266"
Form1.Print Tab(5); "Dr. Madhu"; Tab(22); "Mangal"; Tab(35); "0495-287166"
Form1.Print Tab(5); "Mrs.Sheela"; Tab(22); "V.S"; Tab(35); "0495-287268"

Out will be as shown in figure


Setting Font Properties :
Fonts generally fall into one of these two categories (1) Screen fonts designed for display on computer
monitors (2) Printer fonts designed for use by printers to reproduce text on a printed page. The ability
to print text as it appear on the screen depends on a close match between the screen fonts used in the
application and the printer fonts available to the printer. Fonts available in Visual Basic vary according
to your system configuration, display devices, and printing devices. Font-related properties can be set
only to values for which actual fonts exist. In Controls, text is often available through the Caption or
text properties. Font properties determine the visual characteristics of the text. There are six font
properties FontName, FontSize, FontBold, FontItalic, FontStrikethru, and FontUnderline.
FontTransparent. For the properties FontName and FontSize user has to enter value such as Modern
and 12 while others are boolean type
Determine font styles in the following formats: FontBold, FontItalic, FontStrikethru, and
FontUnderline. FontTransparent determines whether background text or graphics are included with the
characters in a particular font; FontTransparent applies only to forms, picture boxes, and the Printer
object.
Usage:
{[form.][control.]|Printer.}FontBold[ = boolean ]
{[form.][control.]|Printer.}FontItalic[ = boolean ]
{[form.][control.]|Printer.}FontStrikethru[ = boolean ]

eg form1.FontBold=True
form1.FontItalic = True
Text1.FontUnderline=True

{[form.][picturebox.]|Printer.}FontTransparent[ = boolean ]
{[form.][control.]|Printer.}FontUnderline[ = boolean
Formatting Numbers, Dates and Times:

71

VISUAL BASIC

Visual Basic gives flexibility in displaying number format as well as date and time formats. This is
done by using Format and Format$ functions. Both function share a common syntax. Difference is
that Format function converts in to a string, while Format$ converts in to a Variant data type.
Syntax
Format[$](expression[, fmt] )
Part
expression
fmt

Description
Numeric or string expression to be formatted.
Format expression - a string of display-format characters that specify how the
expression is to be displayed or the name of a commonly used format that has been
predefined in Visual Basic. Different type format expressions (numeric, date/time, or
string) cannot be mixed in a single fmt argument.

To format numbers, you can use the commonly used formats that have been predefined in Visual Basic
or you can create user-defined formats with standard characters that have special meaning when used in
a format expression.

The following table shows the predefined numeric format names you can use and the meaning of each:
Format name

Description

General Number Display the number as is, with no thousand separators.


Currency
Display number with thousand separator, if appropriate; display negative
numbers enclosed in parentheses; display two digits to the right of the
decimal separator.
Fixed
Display at least one digit to the left and two digits to the right of the decimal
separator.
Standard
Display number with thousand separator, if appropriate; display two digits
to the right of the decimal separator.
Percent
Display number multiplied by 100 with a percent sign (%) appended to the
right; display two digits to the right of the decimal separator.
Scientific
Use standard scientific notation.
Yes/No
Display No if number is 0, otherwise display Yes.
True/False
Display False if number is 0, otherwise display True.
On/Off
Display Off if number is 0, otherwise display On.
The following table shows the characters you can use to create user-defined number formats
and the meaning of each:
Character

Meaning

Null string
0

Display the number with no formatting.


Digit placeholder.
Display a digit or a zero. If there is a digit in the expression being formatted
in the position where the 0 appears in the format string, display it; otherwise,
display a zero in that position.
Digit placeholder. Display a digit or nothing. If there is a digit in the
expression being formatted in the position where the # appears in the format
string, display it; otherwise, display nothing in that position.
Decimal placeholder.
The decimal placeholder determines how many digits are displayed to the
left and right of the decimal separator.
Percentage placeholder.
The expression is multiplied by 100. The percent character (%) is inserted
in the position where it appears in the format string.
Thousand separator.

72

VISUAL BASIC

E- E+ e- e+

The thousand separator separates thousands from hundreds within a number


that has four or more places to the left of the decimal separator. Standard
use of the thousand separator is specified if the format contains a comma
surrounded by digit placeholders (0 or #).
Scientific format.
If the format expression contains at least one digit placeholder (0 or #) to the
right of E-, E+, e-, or e+, the number is displayed in scientific format and E
or e is inserted between the number and its exponent.
Time separator.
The time separator separates hours, minutes, and seconds when time values
are formatted.
Date separator.
The date separator separates the day, month, and year when date values are
formatted.

To format dates and times, you can use either the commonly used formats that have been predefined in
Visual Basic or create user-defined time formats using standard characters that have special meaning
when used in a format expression.
The following table shows the predefined data format names you can use and the meaning of each:
Format Name

Description

General Date

Display a date and/or time. For real numbers, display a date and time. (e.g.
4/3/93 05:34 PM); If there is no fractional part, display only a date (e.g.
4/3/93); if there is no integer part, display time only (e.g. 05:34 PM).
Display a Long Date, as defined in the International section of the Control
Panel.
Display a date in the same form as the Short Date, as defined in the
International section of the Control Panel, except spell out the month
abbreviation.
Display a Short Date, as defined in the International section of the Control
Panel.
Display a Long Time, as defined in the International section of the Control
Panel. Long Time includes hours, minutes, seconds.
Display time in 12-hour format using hours and minutes and the AM/PM
designator.

Long Date
Medium Date

Short Date
Long Time
Medium Time

Short Time

Display a time using the 24-hour format (e.g. 17:45)

The following table shows the characters you can use to create user-defined date/time formats and the
meaning of each:
Character
c

d
dd
ddd
dddd
ddddd

dddddd

Meaning
Display the date as ddddd and display the time as t t t t t, in that order. Only
date information is displayed if there is no fractional part to the date serial
number; only time information is displayed if there is no integer portion.
Display the day as a number without a leading zero (1-31).
Display the day as a number with a leading zero (01-31).
Display the day as an abbreviation (Sun-Sat).
Display the day as a full name (Sunday-Saturday).
Display a date serial number as a complete date (including day, month, and
year) formatted according to the Short Date setting in the International
section of the Windows Control Panel. The default Short Date format is
m/d/yy.
Display a date serial number as a complete date (including day, month, and
year) formatted according to the Long Date setting in the International
section of the Control Panel. The default Long Date format is mmmm dd,
yyyy.

73

VISUAL BASIC
w

mmm
mmmm
q

Display the day of the week as a number (1 for Sunday through 7 for
Saturday.)
Display the week of the year as a number (1-53).
Display the month as a number without a leading zero (1-12). If m
immediately follows h or hh, the minute rather than the month is displayed.
Display the month as a number with a leading zero (01-12). If m
immediately follows h or hh, the minute rather than the month is displayed.
Display the month as an abbreviation (Jan-Dec).
Display the month as a full month name (January-December).
Display the quarter of the year as a number (1-4).

y
yy

Display the day of the year as a number (1-366).


Display the year as a two-digit number (00-99).

yyyy

Display the year as a four-digit number (100-9999).

h
hh

Display the hour as a number without leading zeros (0-23).


Display the hour as a number with leading zeros (00-23).

n
nn
s
ss

Display the minute as a number without leading zeros (0-59).


Display the minute as a number with leading zeros (00-59).
Display the second as a number without leading zeros (0-59).
Display the second as a number with leading zeros (00-59).

ttttt

Display a time serial number as a complete time (including hour, minute,


and second) formatted using the time separator defined by theTime Format
in the International section of the Control Panel. A leading zero is displayed
if the Leading Zero option is selected and the time is before 10:00 A.M. or
P.M. The default time format is h:mm:ss.

ww
m
mm

AM/PM
am/pm
A/P
a/p
AMPM

Use the 12-hour clock and display an uppercase AM with any hour before noon;
display an uppercase PM with any hour between noon and 11:59 PM.
Use the 12-hour clock and display a lowercase AM with any hour before noon;
display a lowercase PM with any hour between noon and 11:59 PM.
Use the 12-hour clock and display an uppercase A with any hour before noon;
display an uppercase P with any hour between noon and 11:59 PM.
Use the 12-hour clock and display a lowercase A with any hour before noon;
display a lowercase P with any hour between noon and 11:59 PM.
Use the 12-hour clock and display the contents of the 1159 string (s1159) in the
WIN.INI file with any hour before noon; display the contents of the 2359 string
(s2359) with any hour between noon and 11:59 PM. AMPM can be either
uppercase or lowercase, but the case of the string displayed matches the string as
it exists in the WIN.INI file. The default format is AM/PM.

The following are examples of user-defined date and time formats:


Format
Display
m/d/yy
12/7/58
d-mmmm-yy
7-December-58
d-mmmm
7 December
mmmm-yy
December 58
hh:mm AM/PM 08:50 PM
h:mm:ss a/p
8:50:35 p
h:mm
20:50
h:mm:ss
20:50:35
m/d/yy h:mm
12/7/58 20:50

74

VISUAL BASIC
7.3.2 Printing from an application
Visual Basic provides two techniques for printing text and graphics to the default printer (specified by
the user in the Control Panel)
Produce the required output on a form and then print the form using PrintForm
method
First send text and graphics to the Printer object and then print them using
NewPage and EndDoc methods.
Using PrintForm Method
This method sends pixel-by-pixel image of the specified form to the printer. To use PrintForm to print
information from your application, you must first display that information on a form then print that
form with PrintForm method which sends a bit-for-bit image of a non-MDI form to the printer.
Syntax is [form.]PrintForm
Using PrinterObject Method
The Printer object is accessed with the keyword Printer. It is used to control text and graphics printed
on a page and to send output directly to the default system printer. For example, you can use this
object to manipulate the appearance of your printed output by changing fonts. You may need to check
and revise the layout of your forms if you want to print them. When you use the Print method,
graphical images are clipped at the bottom of the page and text is carried over to the next page. Printer
Object has three scale properties ie ScaleMode, ScaleLeft & ScaleTop, ScaleWidth & ScaleHeight
ScaleMode determines the unit of measurement for coordinates of an object when using graphics
methods or when positioning controls. Using the related ScaleHeight, ScaleWidth, ScaleLeft, and
ScaleTop properties, you can create a custom coordinate system with both positive and negative
coordinates.
The ScaleMode property settings are:
Setting
Description
0
Indicates that one or more of the ScaleHeight, ScaleWidth, ScaleLeft, and
ScaleTop properties are set to custom values.
1
(Default) Twip (1440 twips per logical inch; 567 twips per logical
centimeter).
2
Point (72 points per logical inch).
3
Pixel (smallest unit of monitor or printer resolution).
4
Character (horizontal = 120 twips per unit; vertical = 240 twips per unit).
5
Inch.
6
Millimeter.
7
Centimeter.
ScaleLeft and ScaleTop determine the horizontal (ScaleLeft) and vertical (ScaleTop) coordinates for
the left and top edges of an object when using graphics methods or when positioning controls. The
default for both properties is 0.
ScaleHeight, ScaleWidth, determine the number of units for the internal horizontal (ScaleWidth) and
vertical (ScaleHeight) measurement of an object when using graphics methods or when positioning
controls. For MDI forms, not available at design time and read-only at run time.
Eg.. ScaleHeight = 100 ' Set height units.
ScaleWidth = 100
We can set CurrentX and CurrentY properties for the Printer Object, just as for picture boxes and
forms. For example . Printer.CurrentX=0 set x coordinate in the printer page to 0 in current page.

7.3.3 Printing the Contents of the Printer Object


Once user place text and graphics on the Printer object, use the EndDoc method to print the contents.
The EndDoc method advances the page and sends all pending output to the spooler. When printing
longer documents, we can specify where we want a new page to begin by using NewPage method. If
the user want to print a header at the top of every page of a report use the following statements:

75

VISUAL BASIC
Header$ = Monthly Budget Summary
Printer.Print Header$ + Printer.Page
Printer.NewPage
Printer.Print Header$ + Printer.Page
PageNo=Printer.Page
MsgBox Your document contains + PageNo + Pages.
Printer.EndDoc
Two sample programs are given in Annexure for creating PrinterObject and printing.

7.3.4 The Crystal Custom Control


The Crystal Reports package
You can think of the Crystal Reports package as containing two separate elements: Crystal Reports,
and the Crystal Custom Control. Used together, these two elements give you the ability to generate
custom reports, transparently, via your application.
The Crystal Custom Control is a set of tools that makes it easy for you to build the connection between
your application and the print engine. Using these tools you can have your application generating
reports in a very short time.Custom controls are programs that add tools to the Visual Basic toolbox.
Once in the toolbox, these tools can be used on any form just as if they were part of the original Visual
Basic language.
Custom controls can produce objects that are visible at design time and at runtime. These objects
(stylish buttons, dials, etc.) can be used to add visual impact and increased functionality to your
applications.Custom controls can also produce objects that are visible at design time but invisible at
runtime. These kinds of objects were designed to make it easier for your applications to access the
capabilities available in Dynamic Link Libraries (DLL's). By setting the properties for these objects in
the Properties dialog box, you eliminate the need for a lot of manual coding.
Crystal Reports comes with a custom control in the second category: visible at design time but invisible
at runtime. When you place the object on your form and set the properties, you can add sophisticated
reporting capabilities to your application without the need for writing extensive code.
Adding the Crystal Custom Control to your project
You add the Crystal Custom Control to your project using the File|Add File command on the Visual
Basic menu bar.
To add the Crystal Custom Control:
1.
Open Visual Basic.
2.
Open the project to which you want to add the Custom Control.
3.
Select File|Add File. The Add File dialog box appears.
4.
Select the file CRYSTAL.VBX from the \WINDOWS\SYSTEM directory or the directory in
which you had Crystal Reports installed. Visual Basic adds the Crystal Custom Control to your
toolbox. The tool looks like this:
5.
When you want to add the program to a form, Double--Click the tool and the program installs
it on the active form.
Using the Crystal Custom Control
Once you have the Crystal Custom Control object on your form, you build the connection between
your application and the print engine by setting the object's properties via the control's Properties list.
Using the properties list you specify:

76

VISUAL BASIC

the name of the report you want to print in response to an application event,
the destination for that report (window, file, or printer),
the number of copies you want to print (if your report is going to the printer),
print file information (if your report is going to a file),
print window sizing and positioning information (if your report is going to a window),
selection formula information (if you want to limit the records in your report)
sorting information,
and other related properties.

Setting CRYSTAL.VBX properties at runtime


You can set most of the Crystal Custom Control properties at runtime by adding simple entries to your
procedure code. Runtime property settings replace settings you make via the Properties list at design
time. Use the following sample code as a reference for coding property settings at runtime:
Action Report1.Action = 1
prints the specified report
Connect Report1.Connect = "DSN = Accounting;UID = 13321;PWD = HARDDISK; DSQ = Orders"
Logs on to the Orders database on the network server "Accounting" using the I.D. 13321 and the
password HARDDISK
CopiesToPrinter
Report1.CopiesToPrinter = 3
prints three copies of the specified report
DataFiles
Report1.DataFiles(0) = "C:\VB\orders.mdb"
sets the new location of orders.mdb to the C:\VB directory
Destination
Report1.Destination = 0
sends the specified report to a print window
Formulas
Report1.Formulas(0) = "EXTEND= {file.QTY} * {file.PRICE}"
sets the value of the formula @EXTEND to "{file.QTY} * {file.PRICE}"
GroupSelectionFormula Report1.GroupSelectionFormula
{header.CustNumb}) > 15"

"Count

(header.Amount,

with the values in the Amount field grouped each time the value in the CustNumb field changes and
the values in each group counted, limits the report to only those groups for which the group count is
greater than 15
GroupSortFields Report1.GroupSortFields(0) = "+ Max ({orders.Amount}, {orders.Customer})"
with the Amount field sorted and grouped each time the value in the Customer field changes and the
maximum value calculated for each group, this string sorts those groups in ascending order so that the
group with the lowest maximum value comes first, then the next lowest, etc.
LastErrorNumber
If Result <> 0 Then
MsgBox Report.LastErrorNumber
End If
directs the last error number to be displayed in a message box is the call is unsuccessful
LastErrorString
If Result <> 0 Then
MsgBox Report1.LastErrorString
End If
directs that the last error string be displayed in a message box if the call is unsuccessful

77

VISUAL BASIC
Left
Report1.Left = 3120
sets the Left coordinate to 3120 twips
Name

You cannot change the Name property at runtime.

Password
Report1.Password = "Schoolboy"
sends the password "Schoolboy" to open an Access .mdb file
PrintFileName Report1.PrintFileName = "c:\vb\report\cust_rpt.txt"
prints the report to a file named "cust_rpt.txt" in the c:\vb\report directory
PrintFileType
Report1.PrintFileType = 1
prints the report to a file in a tab separated format
ReportFileName Report1.ReportFileName = "c:\vb\report\company.rpt"
prints the report named "company.rpt" that is located in the c:\vb\report directory
SelectionFormula
Report1.SelectionFormula = "{file.STATE} = 'CA'"
limits the report to records that have the value 'CA' in the STATE field (only California records)

SortFields
Report1.SortFields(0) = "{bmc endash.bmp}{order.DATE}"
sorts the report data by date and prints the data in descending date order
Top
Report1.Top = 1800
sets the Top coordinate to 1800 twips
UserName
Report1.UserName = "JohnG"
sends the user name "JohnG" to open an Access .mdb file
WindowBorderStyle
Report1.WindowBorderStyle = 2
sets a sizable border style (Style #2) for the print window
WindowControlBox
Report1.WindowControlBox = True
specifies that a control box (system menu) is to appear in the print window
WindowHeight Report1.WindowHeight = 300
sets the height of the print window to 300 pixels
WindowLeft
Report1.WindowLeft = 100
sets the left edge of the print window 100 pixels from the left edge of the screen
WindowMaxButton
Report1.WindowMaxButton = False
specifies that no Maximize button is to appear in the print window
WindowMinButton
Report1.WindowMinButton = True
specifies that a Minimize button is to appear in the print window
WindowParentHandle
Report1.WindowParentHandle = Form1.hWnd
sets the WindowParentHandle to the handle of Form1. This specifies that the print window is to be a
child of Form1
WindowTitle
Report1.WindowTitle = "Quarterly Earnings"
sets the title of the print window (the string that appears on the title bar) to "Quarterly Earnings"
WindowTop
Report1.WindowTop = 100
sets the top edge of the print window 100 pixels from the top of the screen
WindowWidth

Report1.WindowWidth = 480

78

VISUAL BASIC
specifies a print window 480 pixels wide

7.4 Sample Programs and reports


7.4.1 Example for Custom Control
This program code is written with the Custom Control which is placed in the form. When the event is
activated it causes to generate the report to printer/file or screen depending on the users choice. Bold
letter line indicate the major statements used to include to link the report generated by crystal Report
Program1
Sub Report_Click ()
Dim str1 As String
If combo3.Text = "Window" Then 'combo3.text gives the output media
OutputDestination = 0
Else
If combo3.Text = "Printer" Then
OutputDestination = 1
Report1.CopiesToPrinter = Number_Of_Copies
Else
If combo3.Text = "File" Then
OutputDestination = 2
Report1.PrintFileName = Output_File_Name
Report1.PrintFileType = Output_File_Type
End If
End If
End If
Report1.Destination = OutputDestination
str1 = combo2.Text

'Combo2.text gives the selected .rpt file for report generation

LocText$ = LCase(app.Path)
If Right$(app.Path, 1) <> "\" Then LocText$ = LocText$ + "\" 'handles the root
Report1.DataFiles(0) = LocText$ + "pis.mdb"
Report1.ReportFileName = LocText$ + "report\" + str1
On Error GoTo ErrorHandler
Report1.Action = 1
Exit Sub

'Fire the action

ErrorHandler:
MsgBox Error$
Exit Sub
End Sub

7.4.2 Example for PrinterObject


The below function used to create a Printer Object. This is using a grid of 9 columns.
Printing program
This function uses the PrinterObject created by the above function. The printer Object is a grid with
some data. It uses Printer.Print command to print in the printer with additional heading
Sub PrintGrid ()
dim curr as integer
curr = 2000#
printer.Print "

CENTRE FOR ELECTRONIC DESIGN AND


TECHNOLOGY- CALICUT"

79

VISUAL BASIC
printer.Print " "
printer.Print " "
printer.Print "
CASH BOOK "
printer.Print " "
printer.Print
"___________________________________________________________________________
___________________________________________________"
printer.Print ""
printer.Print "
Date V. No Acc.Code
Particulars
Chq No
Cash
Bank"
printer.Print "________________________________________________________________________
____________________________________________________________"
printer.Print ""
printer.Print "
Payments Receipts Payments
Reciepts"
printer.Print
"_________________________________________________________________________
_________________________________________________"
printer.Print " "
For i = 0 To DBgrid.Rows - 1
DBgrid.Row = i
DBgrid.Col = 0
printer.CurrentX = 1500
printer.CurrentY = curr
printer.Print DBgrid.Text
DBgrid.Row = i
DBgrid.Col = 1
printer.CurrentX = 3300
printer.CurrentY = curr
printer.Print DBgrid.Text
DBgrid.Row = i
DBgrid.Col = 2
printer.CurrentX = 4300
printer.CurrentY = curr
printer.Print DBgrid.Text
DBgrid.Row = i
DBgrid.Col = 3
printer.CurrentX = 5500
printer.CurrentY = curr
printer.Print DBgrid.Text
Else
printer.Print "----------------------------------------------------------------------------------------------------------------------------------"
End If
If curr > 15000# Then
printer.Print "
"+
"
Page Number = " + printer.Page
printer.NewPage
curr = 1000#
printer.CurrentY = curr
printer.Print "----------------------------------------------------------------------------------------------------------------------------------"
printer.Print " "
End If
Next i
printer.EndDoc
End Sub

80

VISUAL BASIC

Output of program

81

VISUAL BASIC

8. ADVANCED PROGRAMMING IN VISUAL BASIC


8.1 Multiple Document Interface
The multiple-document interface (MDI) allows programmer to create an application that maintains
multiple forms within a single container form. Applications such as Microsoft Excel and Microsoft
Word for Windows have multiple-document interfaces.
An MDI application allows the user to display multiple documents at the same time, with each
document displayed in its own window. Documents or child windows are contained in a parent
window, which provides a workspace for all the child windows in the application.
A child form is an ordinary form that has its MDIChild property set to True. The application can
include many MDI child forms of similar or different types.
At run time, child forms are displayed within the workspace of the MDI parent form (the area inside
the form's borders and below the title and menu bars). When a child form is minimized, its icon
appears within the workspace of the MDI form instead of on the taskbar.

Figure 1.1 Child forms displayed within the workspace of the MDI form
The application can also include standard, non-MDI forms that are not contained in the MDI form.
A typical use of a standard form in an MDI application is to display a modal dialog box.
A MDI form is similar to an ordinary form with one restriction. Programmer can't place a control
directly on a MDI form unless that control has an Align property (such as a picture box control) or
has no visible interface (such as a timer control).
A MDI form can provide familiar tools designed to help th euser open and work with documents
A set of menu commands often appears at the top of the MDI form. These commands
generally apply to the child document that is active at a given moment during a program run.
The MDI form may also display a toolbar, containing single-click shortcuts for carrying out
the most common menu commands.
A Window menu on the MDI form typically lists the names of all the open windows inside the
form, and provides an easy way to select and activate a given document.
The Window menu may also contain commands designed to rearrange the open documents
within the MDI form.

8.1.1 Using MDI in Visual Basic


Visual Basic application can have only one MDI form, which contains all the applications child
forms.

82

VISUAL BASIC
A child form is an ordinary form that has its MDIChild property set to True. The application can
include many MDI child forms.
At run time, child forms are displayed within the internal area of the MDI form. When a child form
is minimized, its icon appears on the MDI form instead of on the MDI form instead of on the
desktop.
Creating an MDI Application
The following procedure can be used to create an MDI form and its child forms.
1. Create an MDI form.
From the Project menu, choose Add MDI Form.
An application can have only one MDI form. If a project already has an MDI form, the Add MDI
Form command on the Project menu is unavailable.
2. Create the application's child forms.
To create an MDI child form, create a new form (or open an existing one) and set its MDIChild
property to True.
Design Time Features of MDI Child Forms
At design time, child forms are not restricted to the area inside the MDI form. Programmer can add
controls, set properties, write code, and design the features of child forms just as he would with any
other Visual Basic form.
Programmer can determine whether a form is an MDI child by looking at its MDIChild property, or
by examining the Project Explorer. If the form's MDIChild property is set to True, it is a child form.
Visual Basic displays special icons in the Project Explorer for the MDI and MDI child forms, as
shown in Figure 1.2.

Figure 1.2 Icons in the Project Explorer identify MDI child, standard, and MDI forms
Run-Time Features of MDI Forms
At run time, an MDI form and all of its child forms take on special characteristics:

All child forms are displayed within the MDI form's workspace. The user can move and size
child forms like any other form; however, they are restricted to this workspace.
When a child form is minimized, its icon appears on the MDI form instead of the taskbar.
When the MDI form is minimized, the MDI form and all of its child forms are represented by
a single icon. When the MDI form is restored, the MDI form and all the child forms are
displayed in the same state they were in before being minimized.
When a child form is maximized, its caption is combined with the caption of the MDI form
and is displayed in the MDI form's title bar.
By setting the AutoShowChildren property, programmer can display child forms
automatically when forms are loaded (True), or load child forms as hidden (False).
The active child form's menus (if any) are displayed on the MDI form's menu bar, not on the
child form.

8.1.2 Working with MDI Forms and Child Forms


When users of your MDI application open, save, and close several child forms in one session, they
should be able to refer to the active form and maintain state information on child forms. This topic

83

VISUAL BASIC
describes coding techniques that programmer can use to specify the active child form or control,
load and unload MDI and child forms, and maintain state information for a child form.
Specifying the Active Child Form or Control
Sometimes programmer may want to provide a command that operates on the control with the focus
on the currently active child form. For example, suppose selected text is to be copied from the child
form's text box onto the Clipboard.
When there are several controls on a form, the control which is to be made active must be
specified. Like the ActiveForm property, the ActiveControl property returns the control with the
focus on the active child form.
Another way to specify the current form in code is to use the Me keyword. Me can be used to
reference the form whose code is currently running. This keyword is useful when you need to pass a
reference to the current form instance as an argument to a procedure.
Loading MDI Forms and Child Forms
When a child form is loaded, its parent form (the MDI form) is automatically loaded and displayed.
When the MDI formis loaded, however, its children are not automatically loaded.
The AutoShowChildren property can be used to load MDI child windows as hidden, and leave
them hidden until they are displayed using the Show method. This allows programmer to update
various details such as captions, position, and menus before a child form becomes visible.
If a modal dialog box is to be used in an MDI application, use a form with its MDIChild property
set to False.
Setting Child Form Size and Position
When an MDI child form has a sizable border (BorderStyle = 2), Microsoft Windows determines its
initial height, width, and position when it is loaded. The initial size and position of a child form
with a sizable border depends on the size of the MDI form, not on the size of the child form at
design time. When an MDI child form's border is not sizable (BorderStyle = 0, 1, or 3), it is loaded
using its design-time Height and Width properties.
If AutoShowChildren is set to False, the position of the MDI child can be changed after loading it,
but before it is made visible.
Unloading MDI Forms with QueryUnload
The boolDirty flag becomes useful when the user decides to exit the application. This can occur
when the user chooses Close from the MDI form's Control menu, or through a menu item provided,
such as Exit on the File menu. If the user closes the application using the MDI form's Control
menu, Visual Basic will attempt to unload the MDI form.
When an MDI form is unloaded, the QueryUnload event is invoked first for the MDI form and then
for every child form that is open. If none of the code in these QueryUnload event procedures
cancels the Unload event, then each child is unloaded and finally, the MDI form is unloaded.
Because the QueryUnload event is invoked before a form is unloaded, programmer can give the
user the opportunity to save a form before unloading it.

8.1.3 MDI NotePad


As its name suggests, the multiple-document interface was designed especially for documentcentered applications. Such applications allow the user to open many similar documents at the same
time. For example, in Microsoft Excel, the user can work with several different spreadsheets at the
same time, each spreadsheet appearing in a separate window.
To create the MDI NotePad application

i) From the File menu, choose New Project.


ii) From the File menu, choose New MDI Form to crate the container form.
iii) The project should now contain an MDI form (MDIForm1) and a standard
form (Form1).
iv) Set properties for the two forms.
Object name Property
Setting
MDIForm1 Caption
MDI NotePad
Form1
Caption
Untitled

84

VISUAL BASIC

Form1

MDIChild

True

4. In the Menu Design window, create a File menu for form1.


Caption
Object name
Indented
&File
mnuFile
No
&New
mnuFileNew
Yes
5.

Add the following code to the mnuFileNew_Click procedure:


Sub mnuFileNew_Click()
Dim NewDoc As New Form1
NewDoc.Show
End Sub

This procedure creates and then displays a new instance of Form1, called NewDoc. Each time the
user chooses New from the File menu, an exact duplicate of Form1 is created, including all the
controls and code that it contains. At run time you can see the following window on the screen.

8.1.4 Creating a Toolbar


The toolbar has become a standard feature in many Windows-based applications. A toolbar
provides quick access to the most frequently used menu items and commands in an application.
To create a toolbar

i) Place a picture box on the MDI form.


ii) The width of the picture box automatically stretches to fill the width of the
MDI forms client area. The client area is the area inside a forms borders, not
including the title bar, menu bar, or any toolbars, status bars, or scroll bars that
may be on the form. When a form does not contain any toolbars or status bars,
its client area and internal area are the same.
iii) Inside the picture box, place any controls you want displayed on the toolbar.
Typically you create buttons for the toolbar using command buttons or image
controls.
iv) Set design-time properties
v) One advantage of using a toolbar is that you can present the user with a
graphical representation of a command. The image control is a good choice as

85

VISUAL BASIC

a toolbar button because you can use it to display a bitmap. Set its Picture
property at design time to display a bitmap that provides the user with a visual
cue of the command performed when the button is chosen.
vi) Write code.
vii) Since toolbar buttons are usually used to provide easy access to other
commands, most of the time you call other procedures from within each
buttons Click event.
viii)Toolbars are used to provide the user with a quick way to access some of the
applications commands. Since it is not possible to call another forms event
procedure, organize your code in well-defined procedures in a separate
module so that it is easily accessible from other form and code modules.

Toolbar (picture box)

Image controls

Client area
Create toolbar using image controls.

8.2 Object Linking/ Embedding (OLE)


8.2.1 Introduction
Object linking and embedding (OLE) is a technology that allows a programmer of Windows-based
applications to create an application that can display data from many different applications, and
allows the user to edit that data from within the application in which it was created.
Programmer can link or embed all or part of an existing file created in an application or in any other
application that supports linking and embedding. A new object can also be created and then can
link or embed it. If the file to be used was created in an application that does not support linking
and embedding, information from the file can still be copied and pasted, but may not be able to
link or embed from it.

8.2.2 Linking Vs Embedding


The main differences between linking and embedding are where the data is stored and how it is
updated after it is placed in the file.
When programmer link, information gets updated if the source file is modified. Linked data is
stored in the source file; the file into which data is placed stores only the location of the source and
displays a representation of the linked data.
When you embed, information does not change if you modify the source file. Embedded objects
become part of the container file itself. Double-clicking an object after you embed it opens the
object in the source application. You can then edit it in place, and the original object in the source
application remains unchanged.

Embed
When information is embedded, the new document is not linked to the original, so if you change
information in one place, it is not updated in the other. Embedding does enable you to edit the
information by using toolbars and menus from the program used to create the information. To edit
the embedded information, double-click it. The toolbars and menus from the program that was used
to create the information appear. To insert information created in one file (the source file) into
another file (the container file). After it's been embedded, the information called an object
becomes part of the container file. When you double-click an embedded object, it opens in the

86

VISUAL BASIC
application in which it was created. Any changes you make to the object are reflected in the
container file but not in the source file.
To embed information in another document.

i) In the document that contains the information you want to embed, select the
information by highlighting it.
ii) On the Edit menu, click Copy.
iii) In the document where you want the information to appear, click the place
where you want to put the information.
iv) On the Edit menu, click Paste.
Not all programs support embedding. If embedding isn't supported, your information will be
copied. You can embed information in documents that were created in different programs. If you
want the information to be updated when it changes in the original document, you may be able to
link the information instead of embedding it.
Link
When information is linked, the new document is updated automatically if the information in the
original document changes. If you want to edit the linked information, double-click it. The toolbars
and menus from the program that was used to create the information appear. If the original
document is on your computer, changes that you make to the linked information will also appear in
the original document. To copy information from one file (the source file) to another file (the
destination file) and maintain a connection between the two files. When you change the information
in the source file, the information is automatically updated in the destination file.
To link information between documents

i) In the document that contains the information you want to link, select the
information by highlighting it.
ii) On the Edit menu, click Copy.
iii) In the document where you want the information to appear, click the place
where you want to put the information.
iv) On the Edit menu, click Paste Special.
v) Click the format you want to use, and then click Paste Link.
Some programs do not support linking. If linking isn't available, there will not be a Paste Special
command. You can link information between documents that were created in different programs.

8.2.3 OLE and Visual Basic


The Visual Basic OLE control provides an interface to this technology. In some cases, the user can
even edit the data from within the Visual Basic application.
The following terms and concepts are fundamental to understanding the OLE control.
OLE Object
An OLE object refers to a discrete unit of data supplied by an OLE application. An application can
expose many types of objects. For example a spreadsheet application can expose a worksheet,
macro sheet, chart, cell, or range of cells all as different types of objects.
You use the OLE control to create linked and embedded objects. When a linked or embedded
object is created, it contains the name of the application that supplied the object, its data (or, in the
case of a linked object, a reference to the data), and an image of the data. An OLE control can
contain only one object at a time. There are several ways to create a linked or embedded object:
Use the Insert Object or Paste Special dialogs (run time and design time).
Set the Class property in the Properties window, then click the OLE control with the right
mouse button and select the appropriate command (design time only).
Set the Action property of the OLE control (run time only).
OLE Automation
Some applications provide objects that support OLE Automation. You can use Visual Basic to
programmatically manipulate the data in these objects. Some objects that support OLE Automation

87

VISUAL BASIC
also support linking and embedding. If an object in the OLE control supports OLE Automation,
you can access its data using the Object property.
You can create an OLE Automation object without the OLE control using the CreateObject
function.
Class
An objects class determines the application that provides the objects data and the type of data the
object contains. The class names of some commonly used Microsoft applications include
MSGraph, MSDraw, WordDocument, and ExcelWorksheet. You can get a list of the class names
available to your application by selecting the Class property in the Properties window and clicking
on the three dots in the Settings box.
Note The Insert Object dialog does not display a list of class names. This dialog displays userfriendly names for each class of object, which are generally longer and more easily understood.
Container Application
An application that receives and displays an objects data is a container application. For example, a
Visual Basic application that uses an OLE control to embed or link data from another application is
a container application.
In Visual Basic, applications that provide access to objects were called server or source
applications. Applications used to contain objects were referred to as client or destination
applications.

8.2.4 Linked and Embedded Objects


You use an OLE control to incorporate data into a Visual Basic application by linking or
embedding data from another application. Data associated with a linked object is stored by the
application that supplied the object; the OLE control stores only link references that enable display
of snapshots of the source data. Data associated with an embedded object is contained in an OLE
control and can be saved by your Visual Basic application.
When an object is linked, the object's data can be accessed from any application containing a link to
that data and can be changed from within any of them. For example, if a text file is linked to a
Visual Basic application, it can be modified by any other application linked to it. The modified
version will appear in all the documents linked to this text file.
When you use an OLE control to create an embedded object, all the data associated with the object
is contained in the OLE control. For example, if a spreadsheet were an embedded object, all the
data associated with the cells would be contained in the OLE control, including any necessary
formulas. The name of the application that created the object is saved along with the data. If the
user selects the embedded object while working with the Visual Basic application, the spreadsheet
application can be started automatically for editing those cells. When an object is embedded into an
application, no other application has access to the data in the embedded object. Embedding is
useful when you want only your application to maintain data that is produced and edited in another
application.
The Visual Basic OLE control
The Visual Basic OLE control provides an interface to this technology. You use the OLE control to
display an OLE object on a form. You either create the object at design time using standard OLE
dialogs (Insert Object, Paste Special), or at run time by setting the appropriate properties.
Using the OLE Control's Pop-up Menus
Each time you draw an OLE control on a form, the Insert Object dialog is displayed. You use this
dialog to create a linked or embedded object. By choosing Cancel, an object is not created. At
design time, you click the OLE control with the right mouse button to display a pop-up menu. The
commands displayed on this pop-up menu depend on the state of the OLE control as displayed in
the following table:
Command

Enabled in pop-up when...

Insert Object
this command is always enabled.
Paste Special
the Clipboard contains a valid OLE object.
Delete Embedded Object the OLE control contains an embedded object.

88

VISUAL BASIC
Delete Linked Object
the OLE control contains a linked object.
Create Link
the SourceDoc property is set.
Create Embedded Object the Class or SourceDoc property is set.set.
Insert Object screen

8.3 Active X Designers


8.3.1 Introduction
A designer provides a visual design window in the Visual Basic development environment. You
can use this window to design new classes visually. Visual Basic has built-in designers for forms
and ActiveX controls and documents.
Objects created from the classes you design in this fashion have separate design-time and run-time
behavior and appearance, although many objects such as forms and controls look very similar
in the two modes.
In addition to its built-in designers, Visual Basic allows third parties to develop designers for use in
the Visual Basic development environment. These ActiveX designers work just like the built-in
designers in Visual Basic, making them easy to learn and use.
ActiveX designers can provide visual interfaces for tasks that otherwise might require a great deal
of code.
Similarities between ActiveX Designers and Built-in Designers
ActiveX designers are like form designers in the following ways:

ActiveX designers produce classes from which you can create objects. These classes appear in
the Project window, just like form classes.
Each class you create with an ActiveX designer has its own code module, in which you can
write code for the event procedures provided by the designer.
You can customize a class, by adding your own properties, methods, and events to the ones
provided by the ActiveX designer.
The objects created from classes you design can have different characteristics at design time
and run time.
An ActiveX designers design window is fully integrated into the development environment.
It can be sized and arranged just like built-in design windows.
You can add as many instances of an ActiveX designer to your project as you need, just as
you can add as many form designers as you need.
Comparing ActiveX Designer Classes to other Visually Designed Classes
ActiveX designers are extremely flexible. Some, like the UserConnection designer, create classes
whose run-time instances are programmable, but not visible. Others, like the Microsoft Forms
designer used by Microsoft Office, produce visible objects similar to Visual Basic forms.

89

VISUAL BASIC
ActiveX designers that have visible run-time components may be able to host ActiveX controls. In
effect, they become alternate forms packages, which can be used in addition to Visual Basics
native forms.
The following list compares classes produced with ActiveX designers to those produced with builtin Visual Basic designers.

If an object created from an ActiveX designer class is visible at run time, it has its own
window. It is not contained within another form, as ActiveX controls are.
Like form classes, but unlike ActiveX controls, the classes produced by ActiveX designers are
private classes.

8.3.2 Using ActiveX Designer Objects at Run Time


Like the built-in form designer, ActiveX designers are available only in the development
environment. Once you make your project into an executable, it only uses the ActiveX designers
run-time .dll. This may be much smaller than the design-time .dll, because it doesnt include the
visual design tool. ActiveX designers may produce classes whose objects are not visible at run time.
Creating ActiveX Designers
The ActiveX Designer SDK, can be used to create new ActiveX designers for use with Visual
Basic. The ActiveX Designer SDK includes full instructions and sample code.
The ActiveX Designer SDK requires a C++ compiler, such as Microsoft Visual C++. ActiveX
designers cannot be written using Visual Basic.
Adding an ActiveX Designer to the Project Menu
After you install a new ActiveX designer, using the Setup program supplied by the vendor, you
must make the designer available to your projects by adding it to the project menu.
Installing the ActiveX designer will register it in the Windows Registry, under the appropriate
component category. It will then be available from the Designers tab of the Components dialog box.
To add an ActiveX designer to the Project menu

i) On the Project menu, click Components to open the Components dialog


box.
ii) Click the Designers tab and select the designer you want to use, as shown in
the following figure. Click OK.
The Microsoft Forms designer is included in all versions of Visual Basic, to allow forms created in
Microsoft Office applications to be ported easily. Like all designers, the Microsoft Forms designer
has its own run-time .dll. Using this designer in a Visual Basic project will therefore increase the
memory requirements of the resulting executable.
Inserting a New Instance of an ActiveX Designer
Once youve used the Components dialog box to add a designer to the Project menu, you can insert
as many instances of the designer as you need.
To insert an instance of an OLE Designer

On the Project menu, click Add ActiveX Designer to display a list of installed designers.
Pick the designer you want from the list
Once youve added an instance of an ActiveX designer to your project, you can use its visual
interface to design a class. You can click the Code button on the Project window to open the code
module for the designer, and add code to event procedures. You can further customize the class by
adding by adding your own properties, methods, and events, just as you would in a Visual Basic
class module.

8.3.3 Types of ActiveX Components


ActiveX components give you the power to put together sophisticated applications from pieces that
already exist. Your Visual Basic applications can include several types of ActiveX components:

Applications that support ActiveX technology provide objects that you can manipulate
programmatically from within your Visual Basic application.

90

VISUAL BASIC

Code components provide libraries of programmable objects. For example, a code component
could include a library of specialized financial functions for spreadsheet users, or userinterface elements, such as dialog boxes, that are common to multiple applications. Unlike an
object in an ActiveX-enabled application, an object in a code component can run in the same
process as your application, allowing faster access to the object.
You can add features without having to create them yourself by using ActiveX controls as
components. ActiveX controls are available from a variety of vendors to provide many
specialized features, such as displaying a calendar on a form or reading data in a particular
format.
ActiveX documents let you create interactive Internet applications. You can create forms that
can be contained within Internet Explorer. ActiveX documents can show message boxes and
secondary forms and contain ActiveX controls. ActiveX documents can also function as code
components.
Some ActiveX components run in the same process as your application, while others run in a
separate process. In addition to components in existing ActiveX-enabled applications, code
component libraries, ActiveX controls, and ActiveX documents, you can create your own
components.
In-Process and Out-of-Process Servers
ActiveX components interact with your application and with each other through a
client/server relationship. The client is the application code or component that uses the features of a
component. The server is the component and its associated objects. For example, suppose your
application uses an ActiveX control to provide a standard Employee form for multiple applications
in your company. The ActiveX control that provides the Employee form is the server; the
applications that use the control are its clients.
Depending on how an ActiveX component has been implemented, it may run in the same process as
its client applications, or in a different process. For example, if your application uses a component
that is part of an ActiveX-enabled application, it runs in a separate process. If the component has
been implemented as a programmable object in a dynamic-link library (.dll file), it runs in the same
process as your application.
In general, if an ActiveX component has been implemented as part of an executable file (.exe file),
it is an out-of-process server and runs in its own process. If it has been implemented as a dynamiclink library, it is an in-process server and runs in the same process as the client application.
Applications that use in-process servers usually run faster than those that use out-of-process servers
because the application doesn't have to cross process boundaries to use an object's properties,
methods, and events.
The following table shows how you can implement the different types of components:
Component
Server Type
ActiveX-enabled application
Out-of-process
Code component
Either in-process or out-of-process
ActiveX control
In-process
ActiveX document
Either in-process or out-of-process

8.3.4 Working with ActiveX Components


You work with object provided by ActiveX components in much the same way that you work with
other objects. You assign an object reference to a variable, then write code that uses the object's
methods, properties, and events. However, there are some things you need to be aware of when you
work with objects provided by components.
This topic provides an overview of the top-level tasks for working with objects provided by
components and an example of using objects in an ActiveX-enabled application.
To use most objects provided by ActiveX components

Create a reference to the object you want to use. How you do this depends on
the type of object and whether the ActiveX component supplies a type library.
2 Write code using the object's methods, properties, and events.
3 Release the object when you are finished using it.

91

VISUAL BASIC

Create error-handlers;

Creating a Reference to an Object


Before you can use an object's properties, methods, and events in your application, you must
declare an object variable, then assign an object reference to the variable. How you assign an object
reference depends on two factors:

Whether the ActiveX component supplies a type library. An ActiveX component's type library
contains definitions of all the objects the component provides, including definitions for all
available methods, properties, and events. If an ActiveX component provides a type library,
you need to add a reference to the type library in your Visual Basic project before you can use
the library's objects.
Whether the object is a top-level, externally creatable object, or a dependent object. You can
assign a reference to an externally created object directly, while references to dependent
objects are assigned indirectly.
If an object is externally creatable, you can assign an object reference to a variable by using the
New keyword, CreateObject, or GetObject in a Set statement from outside the component. If the
object is a dependent object, you assign an object reference by using a method of a higher-level
object in a Set statement.
To create a reference to an object defined in a type library

1 From the Project menu, choose References.


2 In the References dialog box, select the name of the ActiveX component
containing the objects you want to use in your application.
3 You can use the Browse button to search for the type library file containing
the object you need. Type libraries can have a .tlb or .olb file-name extension.
Executable (.exe) files and dynamic link libraries (dlls) can also supply type
libraries, so you can also search for files with these file-name extensions.
4. From the View menu, choose Object Browser to view the referenced type
library. Select the appropriate type library from the Project/Library list. You
can use all the objects, methods, and properties listed in the Object Browser
in your application.
5. Declare an object variable of the object's class.
Dim xlChart As Excel.Chart
6. Assign an object reference to the variable by using the New keyword,
CreateObject, or GetObject in a Set statement.
If the object is a dependent object, assign an object reference by using a
method of a higher-level object in a Set statement.
To create a reference to an object not defined in a type library

i) Declare an object variable of the Object data type.


Because the object isn't associated with a type library, you won't be able to use the Object
Browser to view the properties, methods, and events of the object. You need to know what
properties, methods, and events the object provides, including any methods for creating a
reference to a dependent object.
2.

Assign an object reference to the variable by using CreateObject or GetObject


in a Set statement.
If the object is a dependent object, assign an object reference by using a method of a higherlevel object in a Set statement.

8.4 Debugging and Error Handling


No matter how carefully crafted the code, errors can (and probably will) occur. Ideally, Visual
Basic procedures wouldn't need error-handling code at all. Unfortunately, sometimes files are
mistakenly deleted, disk drives run out of space, or network drives disconnect unexpectedly. Such

92

VISUAL BASIC
possibilities can cause run-time errors in the code. To handle these errors, programmer need to add
error-handling code to the procedures.
Sometimes errors can also occur within the code; this type of error is commonly referred to as a
bug. Minor bugs for example, a cursor that doesn't behave as expected can be frustrating or
inconvenient. More severe bugs can cause an application to stop responding to commands, possibly
requiring the user to restart the application, losing whatever work hasn't been saved.
The process of locating and fixing bugs in the application is known as debugging. Visual Basic
provides several tools to help analyze how the application operates. These debugging tools are
particularly useful in locating the source of bugs.

8.4.1 Error Handling


Reality dictates that hardware problems or unanticipated actions by the user can cause run-time
errors that halt the code, and there's usually nothing the user can do to resume running the
application. Other errors might not interrupt code, but they can cause it to act unpredictably.
To avoid such situation, programmer can use the error-handling features in Visual Basic to intercept
errors and take corrective action. (Intercepting an error is also known as trapping an error.) When
an error occurs, Visual Basic sets the various properties of the error object, Err, such as an error
number, a description, and so on. Programmer can use the Err object and its properties in an errorhandling routine so that the application can respond intelligently to an error situation.
Designing an Error Handler
An error handler is a routine for trapping and responding to errors in the application. The process
of designing an error handler involves three steps:

i) Set, or enable, an error trap by telling the application where to branch to


(which error-handling routine to execute) when an error occurs.
ii) Write an error-handling routine that responds to all errors you can anticipate.
If control actually branches into the trap at some point, the trap is then said to
be active.
iii) Exit the error-handling routine.
Setting the Error Trap
An error trap is enabled when Visual Basic executes the On Error statement, which specifies an
error handler. The error trap remains enabled while the procedure containing it is active that is,
until an Exit Sub, Exit Function, Exit Property, End Sub, End Function, or End Property statement
is executed for that procedure.
To set an error trap that jumps to an error-handling routine, use a On Error GoTo line statement,
where line indicates the label identifying the error-handling code.
Writing an Error-Handling Routine
The first step in writing an error-handling routine is adding a line label to mark the beginning of the
error handling routine.
The body of the error handling routine contains the code that actually handles the error, usually in
the form of a Case or IfThenElse statement. You need to determine which errors are likely to
occur and provide a course of action for each.
The Number property of the Err object contains a numeric code representing the most recent runtime error. By using the Err object in combination with the Select Case or If...Then...Else statement,
programmer can take specific action for any error that occurs.
Exiting an Error-Handling Routine
There are different ways to exit an error-handling routine.
Statement
Description
Resume [0]
Program execution resumes with the statement that caused
the error or the most recently executed call out of the
procedure containing the error-handling routine. Use it to
repeat an operation after correcting the condition that
caused the error.
Resume Next
Resumes program execution at the statement immediately
following the one that caused the error. If the error

93

VISUAL BASIC

Resume line

Err.Raise Number:= number

occurred outside the procedure that contains the error


handler, execution resumes at the statement immediately
following the call to the procedure wherein the error
occurred, if the called procedure does not have an enabled
error handler.
Resumes program execution at the label specified by line,
where line is a line label (or nonzero line number) that
must be in the same procedure as the error handler.
Triggers a run-time error. When this statement is executed
within the error-handling routine, Visual Basic searches
the calls list for another error-handling routine.

The difference between Resume and Resume Next is shown in Figure 8.1.

START
STATEMENT WITH
ERROR
STATEMENT
FOLLOWING THE
ONE WITH ERROR

RESUME
ERROR
HANDLER

RESUME NEXT

END
Figure 8.1 Program flow with Resume and Resume Next
Resuming Execution at a Specified Line
Resume Next can also be used where an error occurs within a loop, and you need to restart the
operation. Or, you can use Resume line, which returns control to a specified line label.
The Error Handling Hierarchy
An enabled error handler is one that was activated by executing an On Error statement and hasn't
yet been turned off either by an On Error GoTo 0 statement or by exiting the procedure where it
was enabled. An active error handler is one in which execution is currently taking place. To be
active, an error handler must first be enabled, but not all enabled error handlers are active. For
example, after a Resume statement, a handler is deactivated but still enabled.
When an error occurs within a procedure lacking an enabled error-handling routine, or within an
active error-handling routine, Visual Basic searches the calls list for another enabled error-handling
routine. The calls list is the sequence of calls that leads to the currently executing procedure; it is
displayed in the Call Stack dialog box.
Testing Error Handling by Generating Errors
Simulating errors is useful when you are testing your applications, or when you want to treat a
particular condition as being equivalent to a Visual Basic run-time error. For example, you might be
writing a module that uses an object defined in an external application, and want errors returned
from the object to be handled as actual Visual Basic errors by the rest of your application.
In order to test for all possible errors, you may need to generate some of the errors in your code.
You can generate an error in your code with the Raise method:
object.Raise argumentlist
The object argument is usually Err, Visual Basic's globally defined error object. The argumentlist
argument is a list of named arguments that can be passed with the method.
You can also simulate any Visual Basic run-time error by supplying the error code for that error:
Err.Raise Number:=71
' Simulate "Disk Not Ready"
' error.

94

VISUAL BASIC
8.4.2 Inline Error Handling
You may be accustomed to programming in a language that doesn't raise exceptions in other
words, it doesn't interrupt your code's execution by generating exceptions when errors occur, but
instead records errors for you to check later. The C programming language works in this manner,
and you may sometimes find it convenient to follow this practice in your Visual Basic code.
When you check for errors immediately after each line that may cause an error, you are performing
inline error handling. The different approaches to inline error handling are:

Writing functions and statements that return error numbers when an error occurs.
Raising a Visual Basic error in a procedure and handling the error in an inline error handler in
the calling procedure.
Writing a function to return a Variant data type, and using the Variant to indicate to the calling
procedure that an error occurred.

8.4.3 Centralized Error Handling


When you add error-handling code to your applications, you'll quickly discover that you're handling
the same errors over and over. With careful planning, you can reduce code size by writing a few
procedures that your error-handling code can call to handle common error situations.
As you write larger applications, you'll find that you are using the same constants in several
procedures in various forms and modules. Making those constants public and declaring them in a
single standard module may better organize your code and save you from typing the same
declarations repeatedly.
Turning Off Error Handling
If an error trap has been enabled in a procedure, it is automatically disabled when the procedure
finishes executing. However, you may want to turn off an error trap in a procedure while the code
in that procedure is still executing. To turn off an enabled error trap, use the On Error GoTo 0
statement. Once Visual Basic executes this statement, errors are detected but not trapped within the
procedure. You can use On Error GoTo 0 to turn off error handling anywhere in a procedure
even within an error-handling routine itself.

8.4.4 Debugging Code with Error Handlers


When you are debugging code, you may find it confusing to analyze its behavior when it generates
errors that are trapped by an error handler. You could comment out the On Error line in each
module in the project, but this is also cumbersome.
Instead, while debugging, you could turn off error handlers so that every time there's an error, you
enter break mode.
To disable error handlers while debugging

i) From the Code window context menu (available by right-clicking on the Code
window), choose Toggle.
ii) Select the Break on All Errors option.
With this option selected, when an error occurs anywhere in the project, you will enter break mode
and the Code window will display the code where the error occurred.

8.4.5 Approaches to Debugging


Visual Basic cannot diagnose or fix errors for you, but it does provide tools to help you analyze
how execution flows from one part of the procedure to another, and how variables and property
settings change as statements are executed. Debugging tools let you look inside your application to
help you determine what happens and why.
Visual Basic debugging support includes breakpoints, break expressions, watch expressions,
stepping through code one statement or one procedure at a time, and displaying the values of
variables and properties. Visual Basic also includes special debugging features, such as edit-andcontinue capability, setting the next statement to execute, and procedure testing while the
application is in break mode.
Kinds of Errors

95

VISUAL BASIC
To understand how debugging is useful, consider the three kinds of errors that can encounter:
Compile errors
Run-time errors
Logic errors
Compile Errors
Compile errors result from incorrectly constructed code. If you incorrectly type a keyword, omit
some necessary punctuation, or use a Next statement without a corresponding For statement at
design time, Visual Basic detects these errors when you compile the application.
Compile errors include errors in syntax. For example, you could have a statement as follows:
Left
Left is a valid word in the Visual Basic language, but without an object, it doesn't
meet the syntax requirements for that word (object.Left). If you have selected the Auto Syntax
Check option in the Editor tab on the Options dialog box, Visual Basic will display an error
message as soon as you enter a syntax error in the Code window.
To set the Auto Syntax Check option
1. From the Tools menu, select Options, and click the Editor tab on the Options dialog box.
2. Select Auto Syntax Check.
Run-Time Errors
Run-time errors occur while the application is running (and are detected by Visual Basic) when a
statement attempts an operation that is impossible to carry out. An example of this is division by
zero. Suppose you have this statement:
Speed = Miles / Hours
If the variable Hours contains zero, the division is an invalid operation, even though the statement
itself is syntactically correct. The application must run before it can detect this error.
Logic Errors
Logic errors occur when an application doesn't perform the way it was intended. An application can
have syntactically valid code, run without performing any invalid operations, and yet produce
incorrect results. Only by testing the application and analyzing results can you verify that the
application is performing correctly.

8.4.6 Avoiding Bugs


There are several ways to avoid creating bugs in your applications:

Design your applications carefully by writing down the relevant events and the way your code
will respond to each one. Give each event procedure and each general procedure a specific,
well-defined purpose.
Include numerous comments. As you go back and analyze your code, you'll understand it
much better if you state the purpose of each procedure in comments.
Explicitly reference objects whenever possible. Declare objects as they are listed in the
Classes/Modules box in the Object Browser, rather than using a Variant or the generic Object
data types.
Develop a consistent naming scheme for the variables and objects in your application.
One of the most common sources of errors is incorrectly typing a variable name or confusing
one control with another. You can use Option Explicit to avoid misspelling variable names.
Monitoring Data With WATCH Expressions
As you debug your application, a calculation may not produce the result you want or problems
might occur when a certain variable or property assumes a particular value or range of values.
Many debugging problems aren't immediately traceable to a single statement, so you may need to
observe the behavior of a variable or expression throughout a procedure.
Visual Basic automatically monitors watch expressions expressions that you define for you.
When the application enters break mode, these watch expressions appear in the Watch window,
where you can observe their values.
You can also direct watch expressions to put the application into break mode whenever the
expression's value changes or equals a specified value. For example, instead of stepping through

96

VISUAL BASIC
perhaps tens or hundreds of loops one statement at a time, you can use a watch expression to put the
application in break mode when a loop counter reaches a specific value. Or you may want the
application to enter break mode each time a flag in a procedure changes value.
To add a watch expression

i) From the Debug menu, choose Add Watch.


ii) The current expression (if any) in the Code Editor will appear in the
Expression box on the Add Watch dialog box. If this isn't the expression you
want to watch, enter the expression to evaluate in the Expression box.
iii) If necessary, set the scope of the variables to watch.
iv) If you select the Procedure or Module option under Context, select a
procedure, form, or module name from the appropriate list box.
v) If necessary, select an option button in the Watch Type group to determine
how you want Visual Basic to respond to the watch expression.
vi) Choose OK.
You can also add an expression by dragging and dropping from the Code Editor to the Watch
window.
To edit a watch expression

i) In the Watch window, double click the watch expression you want to edit. Or
Select the watch expression you want to edit and choose Edit Watch from the
Debug menu.
ii) The Edit Watch dialog box is displayed and is identical to the Add Watch
dialog box except for the title bar and the addition of a Delete button.
iii) Make any changes to the expression, the scope for evaluating variables, or the
watch type.
iv) Choose OK.
To delete a watch expression in the Watch window, Select the watch expression you want to
delete and then Press the DELETE key.

8.4.7 Tips for Debugging


There are several ways to simplify debugging:

When your application doesn't produce correct results, browse through the code and try to find
statements that may have caused the problem. Set breakpoints at these statements and restart
the application.
When the program halts, test the values of important variables and properties. Use Quick
Watch or set watch expressions to monitor these values. Use the Immediate window to
examine variables and expressions.
Use the Break on All Errors option to determine where an error occurred. To temporarily
change this option, select Toggle from the Code window context menu, then toggle the option
from the submenu. Step through your code, using watch expressions and the Locals window to
monitor how values change as the code runs.
If an error occurs in a loop, define a break expression to determine where the problem occurs.
Use the Immediate window together with Set Next Statement to re-execute the loop after
making corrections.
If you determine that a variable or property is causing problems in your application, use a
Debug.Assert statement to halt execution when the wrong value is assigned to the variable or
property.
To set the error trapping state that Visual Basic defaults to at the beginning of any debugging
session, open the Options dialog box (available from the Tools menu), select the General tab,
and set the Default Error Trapping State option. Visual Basic will use this setting the next time
you start it, even if the setting was entered for another project.

97

VISUAL BASIC

9. ADVANCED TOOLS IN VB
9.1 Active X Control
An ActiveX control is an extension to the Visual Basic Toolbox. You use ActiveX controls just as
you would any of the standard built-in controls, such as the CheckBox control. When you add an
ActiveX control to a program, it becomes part of the development and run-time environment and
provides new functionality for your application.
ActiveX controls leverage your capabilities as a Visual Basic programmer by retaining some
familiar properties, events, and methods, such as the Name property, which behave as you would
expect. Then, however, the ActiveX controls feature methods and properties that greatly increase
your flexibility and capability as a Visual Basic programmer.

The following ActiveX controls provided with Visual Basic.


1.
2.
3.
4.

MSChart Control
Multimedia Control
Animation Control
Status Bar Control

Tool Bar

Animation

MSChart

Multimedia

Status Bar

9.2 Using The MSCHART Control


MSChart control is associated with a data grid (DataGrid object). This data grid is a table that
holds the data being charted. The data grid can also include labels used to identify series and
categories on the chart. The person who designs your chart application fills the data grid with
information by inserting data or by importing data from a spreadsheet or array.

98

VISUAL BASIC
The MSChart control supports the following features:

True three-dimensional representation.


Support for all major chart types.
Data grid population via random data and data arrays.
Possible Uses
To display data as a two-dimensional bar/pictograph, line, area, step, combination, pie, or
scatter chart

To display data as a three-dimensional bar, line, area, step, or combination chart.


To show how data compares over time by stacking series.
To load data into a grid from an array.
Changing the Chart Type
Charts provide a graphical representation of data. Values or data points are displayed in formats
such as bars, lines, markers, filled areas, or pie slices. These data points are grouped into series that
are identified with unique colors or patterns. In many chart types, one data point from each series
is grouped together by category along an axis. Charts can also have titles, backdrops, legends,
plots, and footnotes.
When the MSChart control is initially drawn on the form, a default chart type displays. In order to
display your data in a meaningful way, you may wish to change the chart type.
1
2
3
4

To change the chart type


Right-click on the MSChart control and click Properties to display the MSChart Property
Pages.
On the Chart tab, in the Chart Type section, select either 2D or 3D to display a list of possible
chart types.
From the Chart Type box, select the type of chart you wish to display.
In the Chart Options section, you may select one or more options to hide or show a chart
legend, hide or show datapoint markers, stack series, or display series data from data grid rows
rather than columns.
Click OK or Apply to redraw the chart as the new type.

Adding Chart Elements


In addition to the plot, the major chart elements are titles and footnotes.
1
2
3
4
5
6
7

To add titles and footnotes to a chart


Right-click on the MSChart control and click Properties to display the MSChart Property
Pages.
On the Text tab, select Footnote or one of the title types.
Type the title or footnote in the Text field.
Choose the alignment and text orientation if desired.
Click OK or Apply to redraw the chart to display the new chart element.
On the Font tab, choose the font name, size, style, effects, and color for the chart element.
Click OK or Apply to redraw the chart to include the font details.

Using Combination Charts

99

VISUAL BASIC
Combination charts allow you to plot each series differently on a chart. By depicting each series in
its own unique way, you increase the impact and readability of your chart.
When using combination charts, you must specify the type used to display each series in the chart.
To change a series type
1 Right-click on the MSChart control and click Properties to display the MSChart Property
Pages.
2 On the Series tab, select an option in the Series drop-down list.
3 In the Series Type drop-down list, select one of the valid types for the selected series.
4 Continue specifying types for each series as necessary.

Stacking Series
The options grouped in the Chart Options section of the Chart Tab control whether the chart is
stacked and whether certain chart features are visible. You can stack series in bar, line, area, step,
and combination charts. Stacking places the data points from the same category on top of each
other. Each bar still represents the same value.
Stacking series in a chart can provide a better way of plotting similar data for multiple series. By
stacking the data, you can illustrate changes and trends for multiple series together in one chart
position. Stacking data can eliminate the obstructed views common to three-dimensional charts.
1
2
3
4

To stack series
Right-click on the MSChart control and click Properties to display the MSChart Property
Pages.
On the Chart tab, select Stack series under Chart Options.
Click Apply to redraw the chart.
To unstack the series, select the Stack series again.

Assigning and Editing Backdrops


You can enhance a chart's appearance by placing a backdrop on the chart itself, and on individual
chart elements. A backdrop can include a frame or box around the chart or chart element, a shadow
behind the element, or a pattern behind the element.
Once you have decided to use a backdrop for your chart element, you may need to edit the
backdrop in order to achieve the desired results.
1
2
3
4

To edit a backdrop
Right-click on the MSChart control and click Properties to display the MSChart Property
Pages.
On the Backdrop tab, select the particular chart object for which you want to edit a backdrop.
Once you have selected the chart object, select the color, pattern, and pattern color for the
backdrop's interior, as well as the style, width, and color for the backdrop's border.
Click OK or Apply to redraw the chart to reflect the changes.

Formatting the Base and Walls


You can change the colors and patterns applied to the walls of a two-dimensional chart and the
walls and base of a three-dimensional chart, the color used to draw the lines in the base and walls,
the height of the base, and the width of the walls. The height and width are measured in points.
To format the walls and base

100

VISUAL BASIC
1 Right-click on the MSChart control and click Properties to display the MSChart Property
Pages.
2 On the Backdrop tab, in the Property Name list box, select Plot.
3 Make any necessary changes to color, pattern, and line width and click OK or Apply to redraw
the chart to reflect the changes.

Manipulating the MSChart Data Grid


The data grid (DataGrid object) is created and filled with random data when you draw the
MSChart control on a form. You can manipulate this grid using several properties and methods.
The ColumnCount and RowCount properties determine the number of data columns and data rows.
The ColumnLabelCount and RowLabelCount properties set the number of levels of column and
row labels. The Column and Row properties identify a specific point in the data grid. The
ColumnLabelIndex and RowLabelIndex properties identify a specific row or column of labels. The
ColumnLabel and RowLabel properties change the label identifying a row or column.
The following example sets the chart parameters for a three-dimensional bar chart, fills the chart
with random data, and labels the data grid columns.
Private Sub Command1_Click()
Dim rowLabelCount As Integer
Dim columnLabelCount As Integer
Dim rowCount As Integer
Dim columnCount As Integer
Dim DataGrid As DataGrid
Set DataGrid = MSChart1.DataGrid
MSChart1.chartType = VtChChartType3dBar
With MSChart1.DataGrid
'Set MSChart parameters using methods.
rowLabelCount = 2
columnLabelCount = 2
rowCount = 6
columnCount = 6
.SetSize rowLabelCount, columnLabelCount, _
rowCount, columnCount
'Random Fill the data
.RandomDataFill
'Then assign labels to second Level.
Dim labelIndex as Integer
Dim column as Integer
Dim row as Integer
labelIndex = 2
column = 1
.ColumnLabel(column, labelIndex) = "Product 1"
column = 4
.ColumnLabel(column, labelIndex) = "Product 2"
row = 1
.RowLabel(row, labelIndex) = "1994"
row = 4
.RowLabel(row, labelIndex) = "1995"
End With
End Sub

101

VISUAL BASIC

Loading Data from an Array


When charting data, you may want to substitute random data with an actual data set. The MSChart
control provides a ChartData property for loading data directly from an array into the data grid.
Conversely, the ChartData property can also be used to query the data grid and load data into an
array.
The example below uses a variant array to load the chart data grid directly:
'Declare the variant array (note that lower bounds need
'not be 0).
Dim X(1 To 3, 1 To 3) As Variant
'Set the data.
For i = 1 To UBound3
For j = 1 To 3
X(i, j) = i * j
Next
Next
'Set the row labels.
X(1, 2) = "Wheat"
X(1, 3) = "Corn"
'Set the column labels.
X(2, 1) = "January"
X(3, 1) = "February"
'Set the chart data.
MSChart1 = X
'Set the variant from the chart data.
Y = MSChart1
'Print out the variant (now an array)
For i = LBound(Y, 1) To UBound(Y, 1)
For j = LBound(Y, 2) To UBound(Y, 2)
MsgBox Y(i, j)
Next
Next
In this example, we used a Variant data type array where the top row and left column are set to
string variables and the lower right 2 by 2 submatrix is set to numeric values. This allows both the
chart's labels and data to be set simultaneously. Note that declaring the array as String works as
long as the lower-right submatrix contains text representations of numeric values.
The following example demonstrates querying data from the chart:
'Declare a variant variable.
Dim data As Variant
'Load it from the chart.
data = MSChart1.ChartData
The returned array will always be a two dimensional array of type Variant with a lower bound of 1
for both dimensions. The array will basically look exactly like the tab-delimited text matrix
generated when a chart copies to the clipboard.

9.3 Using The Multimedia MCI Control

102

VISUAL BASIC
The Multimedia control allows you to manage Media Control Interface (MCI) devices. These
devices include: sound boards, MIDI sequencers, CD-ROM drives, audio players, videodisc
players, and videotape recorders and players.
This Multimedia control contains a set of push buttons that issue MCI commands which resemble
the commands (functions) you would expect to see on a typical compact disc player or videotape
recorder. The Figure is shown below.
Prev

Play

Back

Next

Stop

Pause

Eject

Step

Record

Possible Use
To manage the recording and playback of MCI devices.

Multimedia Requirements and Supported Device Types


Which buttons you use, and the functions provided to you by the Multimedia control, depend on
the hardware and software configurations of a particular machine. For instance, if your application
uses specific multimedia devices and drivers, they must be installed on the user's machine.
Driver support for many multimedia devices (audio and video files, for instance) is provided for in
the Windows 95 and Windows NT operating systems. Other devices, such as digital audio tape
players or image scanners require separate drivers, are usually provided by the manufacturer.
Devices are considered to be of two types: simple and compound. Simple multimedia devices do
not require a data file for playback. For example, when Videodisc and CD audio players are
opened, you play, rewind, or forward through 'tracks'. Compound devices, however, require a data
file for playback.
The following table lists some of the devices supported by the Multimedia control. Those listing an
accompanying file type are compound devices.
Device type
animation
cdaudio
dat
sequencer
vcr
video
videodisc
waveaudio
for

File Type

.mid
.avi
.wav

Description
Animation device
Audio CD player
Digital audio tape player
MIDI sequencer
Videotape recorder or player
Video file
Videodisc player
Audio device that plays digitized waveform files. A PC sound card,
example.

MCI Commands
The Multimedia control uses a set of high-level, device-independent commands, known as Media
Control Interface commands, that control various multimedia devices. Many of these commands
correspond directly to a button on the Multimedia control. For instance, the Play command
corresponds to the Play button.

103

VISUAL BASIC
The Multimedia control is essentially a Visual Basic interface to this command set. Commands
like Play or Close have equivalents in the MCI command structure of the Win32 API. For
instance, Play corresponds to MCI_PLAY. The following table lists the MCI commands used by
the Multimedia control, along with their Win32 equivalents:
Command MCI Command Description
Open
Close
Play
Pause
Stop
Back
Step
Prev

MCI_OPEN
MCI_CLOSE
MCI_PLAY
MCI_PLAY or
MCI_RESUME
MCI_STOP
MCI_STEP
MCI_STEP
MCI_SEEK

Opens a MCI device.


Closes a MCI device.
Plays a MCI device.
Pauses playing or recording.
Stops a MCI device.
Steps backward through available tracks.
Steps forward through available tracks.
Goes to the beginning of the current track using the Seek command. If
executed within three seconds of the previous Prev command, goes to

the
beginning of the previous track or to the beginning of the first track if at
the
Next
Seek
Record
Eject
Save

first track.
Goes to the beginning of the next track (if at last track, goes to the
beginning of the last track) using the Seek command.
MCI_SEEK
Seeks track forward or backward.
MCI_RECORD Records MCI device input.
MCI_SET
Ejects Audio CD from CD drive.
MCI_SAVE
Saves an open file.
MCI_SEEK

In Visual Basic, these commands are initiated using the Multimedia control's Command property.
For example:
MMControl1.Command = "Open"
While the Multimedia control's implementation of the MCI command set is sufficient for most
uses, directly utilizing the Win32 API can provide advanced programming functions and
techniques.

Programming the Multimedia Control


The Multimedia Control can be either visible or invisible at run time by setting the Enabled and
Visible properties. By default, the Enabled and Visible properties are set to True and the control is
visible at run time.
If you do not want the user to interact directly with the buttons on the Multimedia control but want
to use the control for its multimedia functionality, set the Visible property to False. An application
can control MCI devices with or without user interaction.
To enable or make individual buttons visible or invisible, you set each button's visible and enabled
properties. For example, the Back button contains the properties BackEnabled and BackVisible.
Each of the nine push buttons have corresponding properties.

Opening the MCI Device


After you place the Multimedia control on a form, whether it is set to be visible or not, the first
step is accessing the MCI device. To do this, you set a number of run-time properties. For
example:
'Set initial property values of the media device
MMControl1.Notify = False
MMControl1.Wait = True
MMControl1.Shareable = False

104

VISUAL BASIC
MMControl1.DeviceType = "CDAudio"
The Notify property, if set to True, generates a Done event when next command is completed. The
Done event provides useful feedback indicating the success or failure of the command. The Wait
property determines whether or not the Multimedia control waits for the next command to
complete before returning control to the application. The Shareable property either restricts or
allows use of the media device by other applications or processes. The DeviceType property is
used to specify the type of MCI device.
Finally, the Open command is used to open the MCI device.
'Open the media device
MMControl1.Command = "Open"
When the control is visible, setting these properties and issuing the Open command enables the
push buttons of the Multimedia control that are inherently supported by the MCI device. For
instance, opening the cdaudio device enables the Prev, Next, Play, and Eject buttons. When Play is
pressed, the Stop and Pause buttons are enabled.
Multiple instances of the Multimedia control can be added to a form to provide concurrent control
of several MCI devices. You use one control per device.

Managing Multimedia Resources


To properly manage multimedia and system resources, you should close those MCI devices that
are open before exiting your application. You can place the following statement in the
Form_Unload procedure to close an open MCI device when the form containing the Multimedia
control is unloaded.
Private Sub Form_Unload (Cancel as Integer)
Form1.MMControl1.Command = "Close"
End Sub

9.4 Using Animation Control


The Animation control displays silent Audio Video Interleaved (AVI) clips. An AVI clip is a
series of bitmap frames like a movie.
One example is the piece of paper that "flies" between folders when copying files in the Windows
95 system:

Although AVI clips can have sound, such clips cannot be used with the Animation control, and an
error will occur if you try to load such a file. Only silent AVI clips can be used. To play .avi files
with sound, use the Multimedia (MCI) control.
Note A variety of soundless .avi files can be found in the \Graphics\AVI directory.
At run time, the Animation control does not have a visible frame.
The Animation control maintains a separate thread of execution while it is playing. Therefore, your
application will not be blocked, and can continue to execute within its process.

Possible Uses

105

VISUAL BASIC
To create dialog boxes that inform the user of the length and nature of an operation.
To play silent instructional video clips about your application.
To allow users to play files dropped onto the control.
Basic Operation: Open, Play, Stop, and Close Methods
When using the control, you open an .avi file using the Open method, play it using the Play
method, and stop it with the Stop method. After a video has played, use the Close method to close
the file. You do not need to close the file before opening a new one.
The following code uses two CommandButton controls, cmdPlay and cmdStop, and a
CommonDialog control named dlgOpen. Set the caption of cmdPlay to "Open and Play." The
caption of the CommandButton control cmdStop is set to "Stop."
Private Sub cmdPlay_Click()
' Configure a CommonDialog control to allow the
' user to find .avi files to play. The CommonDialog
' control is named "dlgOpen." The Animation control
' is named "anmAVI."
dlgOpen.Filter = "avi files (*.avi)|*.avi"
dlgOpen.ShowOpen
anmAvi.Open dlgOpen.FileName
anmAVI.Play
End Sub

This code stops the video playing:


Private Sub cmdStop_Click()
anmAVI.Stop
End Sub

9.5 Using Status Bar Control


A StatusBar control is a frame that can consist of several panels which inform the user of the status
of an application. The control can hold up to sixteen frames. Additionally, the control has a
"simple" style (set with the Style property), which switches from multi-panels to a single panel for
special messages.
The StatusBar control can be placed at the top, bottom, or sides of an application. Optionally, the
control can "float" within the application's client area.

Possible Uses
To inform the user of a database table's metrics, such as number of records, and the present
position in the database.

To give the user information about a RichTextBox control's text and font status.
To give status about key states (such as the Caps Lock or the Number Lock)
The Panel Object and the Panels Collection

106

VISUAL BASIC
The StatusBar control is built around the Panels collection. Up to sixteen Panel objects can be
contained in the collection. Each object can display an image and text.
At run time, you can dynamically change the text, images, or widths of any Panel object, using the
Text, Picture and Width properties. To add Panel objects at design time, right-click on the control,
and click on Properties to display the Property Pages dialog box, as shown in Figure below:
Figure StatusBar panels page

Using this dialog box, you can add individual Panel objects, and set the various properties for each
panel.

Use the Set Statement with the Add Method to Create Panels at Run Time
To add Panel objects at run time, use the Set statement with the Add method. First declare an
object variable of type Panel, then set the object variable to a Panel created with the Add method,
as shown in the code below:
' The StatusBar control is named "sbrDB."
Dim pnlX As Panel
Set pnlX = sbrDB.Panels.Add()
Once you have created a Panel object and set the object variable to reference the new object, you
can set the various properties of the Panel:
pnlX.Text = Drive1.Drive
pnlX.Picture = LoadPicture("mapnet.bmp")
pnlX.Key = "drive"
If you plan to have the control respond when the user clicks on a particular Panel object, be sure to
set the Key property. Because the Key property must be unique, you can use it to identify
particular panels.

Use the Select Case Statement in the PanelClick Event to Determine the
Clicked Panel
To program the StatusBar control to respond to user clicks, use the Select Case statement within
the PanelClick event. The event contains an argument (the panel argument) which passes a
reference to the clicked Panel object. Using this reference, you can determine the Key property of
the clicked panel, and program accordingly, as shown in the code below:
Private Sub sbrDB_PanelClick(ByVal Panel As Panel)

107

VISUAL BASIC
Select Case Panel.Key
Case "drive"
Panel.Text = Drive1.Drive
Case "openDB"
Panel.Text = rsOpenDB.Name
Case Else
' Handle other cases.
End Select
End Sub

The Style Property: Automatic Status Functions


One feature of the StatusBar control is its ability to display key states, time, and date with a
minimum of code. By simply setting the Style property, any Panel object can display one of the
following:
Constant
sbrText
sbrCaps
enabled,
sbrNum
is
sbrIns
and
sbrScrl
enabled,
sbrTime
sbrDate
sbrKana
dimmed

Value
0
1
2
3
4
5
6
7

Description
(Default). Text and/or a bitmap. Set text with the Text property.
Caps Lock key. Displays the letters CAPS in bold when Caps Lock is
and dimmed when disabled.
Number Lock. Displays the letters NUM in bold when the number lock key
enabled, and dimmed when disabled.
Insert key. Displays the letters INS in bold when the insert key is enabled,
dimmed when disabled.
Scroll Lock key. Displays the letters SCRL in bold when scroll lock is
and dimmed when disabled.
Time. Displays the current time in the system format.
Date. Displays the current date in the system format.
Kana. displays the letters KANA in bold when kana lock is enabled, and
when disabled. (enabled on Japanese operating systems only)

The code below creates eight Panel objects, and assigns one of the eight styles to each:
Private Sub MakeEight()
' Delete the first Panel object, which is
' created automatically.
StatusBar1.Panels.Remove 1
Dim i As Integer
' The fourth argument of the Add method
' sets the Style property.
For i = 0 To 7
StatusBar1.Panels.Add , , , i
Next i
' Put some text into the first panel.
StatusBar1.Panels(1).Text = "Text Style"
End Sub

Bevel, AutoSize, and Alignment Properties Program Appearance


Using the Bevel, AutoSize, and Alignment properties, you can precisely control the appearance of
each Panel object. The Bevel property specifies whether the Panel object will have an inset bevel
(the default), raised, or none at all. All three bevels are shown in the figure below:
Settings for the Bevel property are:
Constant

Value

Description

108

VISUAL BASIC

sbrNoBevel
status bar
sbrInset 1
sbrRaised

The Panel displays no bevel, and text looks like it is displayed right on the

The Panel appears to be sunk into the status bar.


2
The Panel appears to be raised above the status bar.

The AutoSize property determines how a Panel object will size itself when the parent container
(either a Form or a container control) is resized by the user. The figure below shows a StatusBar
control before being resized:
When the container (the Form on which the StatusBar control is placed) of the control is resized,
notice that the first panel retains its width, the second "springs" to fill the extra space, and the third
sizes according to its contents (and therefore retains its width):

Settings for the AutoSize property are:


Constant

Value

Description

sbrNoAutoSize
that
sbrSpring

0
1

None. No autosizing occurs. The width of the panel is always and exactly
specified by the Width property.
Spring. When the parent form resizes and there is extra space available, all
panels with this setting divide the space and grow accordingly.
panels' width never falls below that specified by the MinWidth

Content. The panel is resized to fit its contents.

However, the
property.
sbrContents

Tip Set the AutoSize property to Content (2) when you want to assure that the contents of a
particular panel are always visible.
The Alignment property specifies how the text in a panel will align relative to the panel itself as
well as any image in the panel. As with a word processor, the text can be aligned left, center, or
right, as shown below:
Settings for the Alignment property are:
Constant

Value

Description

sbrLeft
sbrCenter
sbrRight

0
1
2

Text appears left-justified and to right of bitmap.


Text appears centered and to right of bitmap.
Text appears right-justified but to the left of any bitmap.

Style Property and the SimpleText Property


The StatusBar control features a secondary mode in which the multiple panels are replaced by a
single panel that spans the width of the control. This single panel has one property, the SimpleText
property which specifies what text is displayed on the panel. To display this single panel, set the
Style property of the StatusBar to sbrSimple (1).
One reason for switching to the Simple style and displaying a single panel is to notify the user that
a lengthy transaction is occurring. For example, if you are performing a database operation, the
Simple style may be used to notify the user of the current state of the transaction, as seen in the
code below:
Private Sub GetRecords(State)
' The query finds all records which match
' the parameter State. While the query
' is creating the recordset, show the

109

VISUAL BASIC
' SimpleText on the StatusBar control.
sbrDB.SimpleText = "Getting records "
sbrDB.Style = sbrSimple ' Simple style.
sbrDB.Refresh ' You must refresh to see the
' Simple text.
Set rsNames = mDbBiblio.OpenRecordset _
("select * from Names Where State= " & _
State)
End Sub

110

VISUAL BASIC

10. VB EXERCISE

6.1

In an organization they have a technical store, which manages and keep track of equipment's
and components required for the organization. The components and equipment's are stocked in
store in some suitable locations. Whenever an item is purchased its d@s are entered in to the
stock register maintained for this purpose. The stock register gives an indication of the receipts
and issues of items. 14ence the need for a computer based system arises. Information systems
process input, maintain files of data and produce information reports and other outputs. Create
a database for the stock management with tables for Product Category, Products, Suppliers
details, Invoices and other transactions.

When an employee want a component he/she gives a request to the stores and on availability, the item
is issued to the employee. Whenever the items goes below a particular level (Re ordering level) the
Stores Places an order for the items. When the item is purchased the details like, quantity, price,
invoice no. and Supplier details are added to the system. The store keeper needs Periodical reports for
store maintenance like total quantities of items received, issued and available. Similarly, the
employees may need to know the availability of particular item in the store, price and supplier details
and other similar products.

6.1

In the organization they have to maintain details about employees and their works. The
information about the employees , activities which are handling by the organization are entered.
Whenever an employee is join in to the organization the details are entered in to the register
maintained for this purpose. Hcnce the need for a computer based svstcm arises. Information
I
systems proms input maintain files of data and produce information reports and other outputs.
Create the database for personnel information with tables for Employee details, Department details,
Activities and Present activities of the employees.

6.2

Create necessary Data entry forms for Ex. 1. & Ex.2 for adding, @ting and deleting records u
'mg data control. Create message boxes to wam the user with help messages while entering
incorrect data to the above forms.

6.3

Create command buttons and write necessary code for manipulation of records like Add, Edit,
Save, Cancel, Delete, Find, FiM Previous, Next, Last in all the Data entry screens in Ex.1 and
Ex,2.

6.4

Modify the above with Combo box controls so that the user can select from the available
opfions.

6.5

Create a procedure such that the user can search for the items based on it code, inv. No, etc., in
Ex. 1
Create an application based on the database mentioned in Ex. 1 with the following facilities

6.6

111

VISUAL BASIC

6.7

I Daidy transaction of the store


2. Facilit), to get the information regarding the quantities available, cost involved, supplier
details, location of each product, and the amount, of consumption during a period.
3 . Periodical reports for store management
Create an application for the Ex 2.

112

Вам также может понравиться