Sei sulla pagina 1di 87

Centre for Electronics Design & Technology of India

A Scientific Society under Department of Electronics,


Govt. of India, New Delhi

Published by CFS Documentation Cell


Centre for Electronics Design and Technology of India
An Autonomous Scientific Society under Department of Electronics,
Govt. of India,
New Delhi.

First Edition: 1999

TRADEMARKS: All brand name and product names mentioned in this book are trademarks or registered trademark of their
respective companies.
Every effort has been made to supply complete and accurate information. However, CEDTI assumes no responsibility for its
use, nor for any infringement of the intellectual property rights of third parties which would result from such use.
No part of this publication may be stored in a retrieval system, transmitted or reproduced in any forms or by any means,
electronic, photocopy, photograph, magnetic or otherwise, without written permission of CEDTI.

CEDTI/CFS/99/6/2.4/R1

FOREWORD
The information technology and telecom sectors have suddenly opened up avenues,
which require a very large specially trained manpower. These sectors are highly dynamic and
need training and re-training of manpower at a rapid rate. The growing gap of requirement of
the industry and its fulfillment has created a challenging situation before manpower training
institutes of the country. To meet this challenge most effectively, Centre for Electronics Design
and Technology of India (CEDTI) has launched its nation-wide franchising scheme.
Centre for Electronics Design and Technology of India (CEDTI) is an Autonomous
Scientific Society under the Govt. of India, Department of Electronics with its Headquarters at
New Delhi. It operates seven centres located at Aurangabad, Calicut, Gorakhpur, Imphal,
Mohali, Jammu and Tezpur. The scheme will be implemented and coordinated by these centres.
The scheme endeavours to promote high quality computer and information technology
education in the country at an affordable cost while ensuring uniform standards in order to
build a national resource of trained manpower. Low course fees will make this education
available to people in relatively small, semi urban and rural areas. State-of-the-art training will
be provided keeping in view the existing and emerging needs of the industrial and Govt.
sectors. The examinations will be conducted by CEDTI and certificates will also be awarded
by CEDTI. The scheme will be operated through all the seven centres of CEDTI.
The CEDTI functions under the overall control and guidance of the Governing Council
with Secretary, Department of Electronics as its Chairman. The members of the council are
drawn from scientific, government and industrial sectors. The Centres have separate executive
committees headed by Director General, CEDTI. The members of these committees are from
academic/professional institutes, state governments, industry and department of electronics.
CEDTI is a quality conscious organisation and has taken steps to formally get recognition
of the quality and standards in various activities. CEDTI, Mohali was granted the prestigious
ISO 9002 certificate in 1997. The other centres have taken steps to obtain the certification as
early as possible. This quality consciousness will assist CEDTI in globalizing some of its
activities. In keeping with its philosophy of Quality in every Activity, CEDTI will endeavour to
impart state of the art computer and IT training through its franchising scheme.
The thrust of the Software Courses is to train the students at various levels to carry out
the Management Information System functions of a medium sized establishment, manufacture
Software for domestic and export use, make multimedia presentations for management and
effectively produce various manufacturing and architectural designs.

The thrust of the Hardware Courses at Technician and Telecommunication Equipment


Maintenance Course levels is to train the students to diagnose the faults and carry out repairs
at card level in computers, instruments, EPABX, Fax etc. and other office equipment. At
Engineer and Network Engineer levels the thrust is to train them as System Engineers to
install and supervise the Window NT, Netware and Unix Networking Systems and repair
Microcontrollers / Microprocessor based electronic applications.
An Advisory Committee comprising eminent and expert personalities from the Information
Technology field have been constituted to advise CEDTI on introduction of new courses and
revising the syllabus of existing courses to meet the changing IT needs of the trade, industry
and service sectors. The ultimate objective is to provide industry-specific quality education in
modular form to supplement the formal education.
The study material has been prepared by the CEDTI, document centre. It is based on
the vast and rich instructional experience of all the CEDTI centres. Any suggestions on the
improvement of the study material will be most welcome.

(R. S. Khandpur)
Director General (CEDTI)

TABLE OF CONTENTS
UNIT

CHAPTER NAME

PAGE NO.

Introduction to Visual Basic

11

Programming in VB

27

Introduction to Bound Controls

39

Menus and Dialog Boxes

53

Database Connections

63

Assimilation Exercises

84

PREFACE
Visual Basic is a very powerful and popular programming tool. Its latest versions have powerful
features for working with the Internet. It is also almost completely customizable through its
new extensibility model. Accordingly, it has been included into the curriculum of the course
module on Certificate Course in Computer Programming. The aim is to train the students or
any working professional to write simple application program to meet the requirements of his
organisation or business. No previous experience in programming on part of the student is
required before going through this course material.
This course material deals with Visual Basic in a very systematic manner.
The First Chapter provides the introduction to the basic concepts of Visual Basic and helps
the student in designing an effective user interface. It also elaborates the various properties
used in designing the interface window..
The Second Chapter gives the fundamentals involved in the Programming of Visual Basic. It
guides the student towards the handling & working with procedures, setting & retrieving
properties and in using the various controls in an efficient manner.
The Third Chapter introduces the concept of bound controls. It outlines the different types of
controls and brings out how to utilize them in the most convenient manner for a particular
program.
The Fourth Chapter deals with the Menus & Dialog boxes which help us in creating & controlling
the menus at run time. It tells the reader about the usage of predefined dialog boxes and the
creation of Customised Dialog Boxes.
The Fifth Chapter, which is one of the most important one, provides us with the knowledge of
connecting Visual Basic to some backend. It involves the creation & opening of Recordsets &
Dynasets and also tells the student about the manipulation of data using the Recordsets. It
also illustrates the usage of Sequential Query Language.
At the end of each chapter the student is required to undertake Assimilation Exercises. Besides
checking the assimilation, these exercises also provide a summary of the entire chapter.
The instructor should ask the students do the programming exercises as Own Time Work and
then run these programmes in the ATC lab. This will provide adequate hands-on experience
to the students.
After completing the study of this course material, the student should be able to fully grasp the
working of Visual Basic, acquire the necessary skills in programming and develop a useful
application. The students will also find that Visual Basic is one of the very powerful frontend
tool which is easy to use.

What you do or dream you can, begin it; boldness


has genius, power and magic in it.
Goethe

INTRODUCTION TO VISUAL BASIC

COMPETENCY OBJECTIVES
The objective of this section is to introduce students to the basic fundamentals involved in Computer
Programming through one of the strongest Front end tool i.e Visual Basic . At the end of the chapter the
student should be able to :v
v
v
v

Understand the basic concepts of VB.


Visualize the importance of properties in VB.
Set the property values according to the requirements of his program.
Design an effective user interface.

VISUAL BASIC

10

VISUAL BASIC

CHAPTER - 1

INTRODUCTION TO VISUAL BASIC


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 youve 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.
Visual Basic Editions
Visual Basic is available in three versions, each geared to meet a specific set of development
requirements.
l
l
l

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
11

VISUAL BASIC

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.
Hardware and System Requirements
To run Visual Basic, you must have certain hardware and software installed on your computer. The system requirements include:
l
l
l
l
l
l
l

Microsoft Windows NT 3.51 or later, or Microsoft Windows 95 or higher.


80486 or higher microprocessor.
A hard disk with a minimum of 100 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.

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.
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:
l
l
l
l
l
l
l

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.

12

VISUAL BASIC

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
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.
13

VISUAL BASIC

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 contain data in
different formats, such as spreadsheets, bitmaps, and text, which were all created by different applications.
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.
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.
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).

14

VISUAL BASIC

3.

Double-click the Visual Basic icon.

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.

The Visual Basic integrated development environment


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.
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 applications 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.
15

VISUAL BASIC

There are three main steps to creating an application in Visual Basic:


1. Create the interface.
2. Set properties.
3. Write code.
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 applications interface. Then you draw the objects that make up the interface on the
forms you create. For this first application, youll use two controls from the Toolbox.

Tool Box Controls


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.

16

VISUAL BASIC

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 control
users 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 cant
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. This controls is no more in vogue as
we, now, have commondialog controls in windows95.
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 users 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.

17

VISUAL BASIC

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 cant 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.

18

VISUAL BASIC

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 isnt 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
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.
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.

19

VISUAL BASIC

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.
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.
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 to 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.
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.
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:

20

VISUAL BASIC

Appearance property
Returns or sets the paint style of controls on an MDIForm or Form object at design time.
Read-only 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 drag-and-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
21

VISUAL BASIC

FontName Property
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 by 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.
22

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 controls 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 the controls position and size can be edited or not.
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.
23

VISUAL BASIC

Style Property
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 isnt used by Visual Basic; you can use this
property to identify objects.
Text Property
ComboBox control and TextBox control It 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) . This properties is Read-only at both the design time and at
the run time.
Visible Property
Returns or sets a value indicating whether an object is visible or hidden.

24

VISUAL BASIC

Any time there is a change, there is opportunity, so it is paramount that an


organisation gets energised rather than paralysed.
Jack Welch, CEO, General Electric
Be prepared for the Digital Future.

PROGRAMMING IN VISUAL BASIC

COMPETENCY OBJECTIVES
The objective of this section is to introduce students to the basic fundamentals involved in Computer Programming. At the end of the chapter the student should be able to :v
v
v
v
v

Describe the various terms used in VB.


Understand the programming fundamentals in order to produce effective programs.
Handle the procedures in an efficient manner.
Set & retrieve the properties according to the requirements of his program.
Use the various controls with their properties in an efficient manner.

25

VISUAL BASIC

26

VISUAL BASIC

CHAPTER - 2

PROGRAMMING IN VISUAL BASIC


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.
27

VISUAL BASIC

type-declaration character
A character appended to a variable name indicating the variables 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
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.
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
into 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 user-defined types. A
variable belonging to a user-defined type is sometimes known as a record variable:
l

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


represented by a single variable name and contain same type of data elements. 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.
28

VISUAL BASIC

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.

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.
Structure of a Visual Basic Application
Your application can contain form modules (.FRM) and code modules (.BAS), as well as
custom controls (.OCX). 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.
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:
l

Declarations: You can place constants, types, variables, 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.

29

VISUAL BASIC

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.
Note: If you change the name of the control after you write the event procedure for that control , you will have to
rename the event procedure otherwise the procedure will not run and it will also not give any error.

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

Sub controlname_eventname()
statement block
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 state30

VISUAL BASIC

ments 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.
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.
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.
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]

31

VISUAL BASIC

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 (variable-length 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:
Call MultiBeep(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:
32

VISUAL BASIC

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)
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.
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.
l
l

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

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:
33

VISUAL BASIC

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.
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:
l
l
l

Set value of a property


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

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 : object.property=value.
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:
34

VISUAL BASIC

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.
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
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
Form1!Text1.Move 0,0

35

VISUAL BASIC

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
Check box
Combo box
Command button
Common dialog
Data
Directory list box
Drive list box
File list box
Frame
Grid
Horizontal scroll bar
Image
Label
Line
List box
Menu
Option button
Picture box
Shape
Text box
Timer
Vertical scroll bar

Property
Value
text
Value
Action
Caption
Path
Drive
FileName
Caption
Text
Value
Picture
Caption
Visible
Text
Enabled
Value
Picture
Shape
Text
Enabled
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

36

VISUAL BASIC

War is such that the Supreme consideration is speed.


Sun-tzu, The Art of Warfare
Today business is such that the Supreme consideration is speed.

INTRODUCTION TO BOUND CONTROLS

COMPETENCY OBJECTIVES
The objective of this section is to introduce students to the data controls involved during Computer Programming. At the end of the chapter the student should be able to :v
v
v
v

Understand the basic concepts of Data Controls.


Differentiate between the various types of controls.
Appreciate the need of controls and visualize their importance in the construction of a program.
Use these controls in the most efficient manner.

37

VISUAL BASIC

38

VISUAL BASIC

CHAPTER - 3

INTRODUCTION TO BOUND CONTROLS

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.
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.
39

VISUAL BASIC

Figure shows a data control icon that is available in the Toolbox.


Figure : 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.

TYPES OF CONTROL
Intrinsic Controls
The standard bound controls that you can use with the data control include the following:
l
l
l
l
l
l
l
l

Check box
Image
Label
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.
40

VISUAL BASIC

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
formats: bitmap, icon, metafile, enhanced metafile, or as JPEG or GIF files.
Fig : 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.
Fig.: 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.
Fig.: Label Control

41

VISUAL BASIC

Labels are used in many instances, for many different purposes. Most commonly, they are
used to label controls that dont 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.
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 dont want the user to change, unless
youve 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.
Fig.: The Text box
controll

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
42

VISUAL BASIC

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.
Fig.: 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
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.
Fig.: 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.

43

VISUAL BASIC

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.
Fig.: The OLE container
control

kjdksad

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:
l
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.
l
Create a linked object in your application.
l
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
44

VISUAL BASIC

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 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.
ActiveX Controls
In addition to the intrinsic bound controls, Visual Basic also provides the following ActiveX
controls that can be added to your project:
l
Data-bound list box
l
Data-bound combo box
l
MSFlexGrid
l
Apex Data-Bound Grid (DBGrid)
ActiveX controls are distributed as OCX files which can be inserted in your Toolbox,(if not
visible )by pressing CTRL+T from the control tabbed page.
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.
l
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.
l
The DBList control is similar to the list box control. When used in conjunction with a data
45

VISUAL BASIC

control, it can be automatically filled with a list of data from a field in an external database.
l
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.
l
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.
l
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.

Property
DataChanged
DataField
DataSource

Description
Indicates whether a value displayed in a bound control has changed.
Specifies the name of a field in the recordset created by the data control.
Specifies the name of the data control to which the control is bound.

The steps in adding bound controls to your application are:


1. Draw the bound control on the same form as the data control to which it will be bound.
2. Set the DataSource property to specify the data control to which it will be bound.
3. Set the DataField property to a valid field in the data controls recordset.
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.
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.
Fig.: DB List

46

VISUAL BASIC

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
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 property.
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.
DB Combo 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
47

VISUAL BASIC

Fig.: DB Combo control

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 database file 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.
2.
3.

4.

5.
6.

7.

Add a data-bound combo box control and two data controls to your form.
In the Properties window, set the first data control (Data1) properties to create a tabletype recordset against the Titles table.
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
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.
Set the RowSource property for the data-bound combo box to the second data control
(Data2).
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).
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.

48

VISUAL BASIC

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 from 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.
2.
3.

Add a data control to a new form, and set its DatabaseName and RecordSource properties to the database and table you want to display.
Add a DBGrid control to the form, and set its DataSource property to the data control
you just created.
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 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 controls DataSource property to a Data control so that the control is automatically filled and its column headers set automatically from a
Data controls Recordset object. The DBGrid control is really a fixed collection of columns,
each with an indeterminate number of rows.
Fig.: DB Grid 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.
49

VISUAL BASIC

If a cells 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 cells Column objects Width
property and/or the DBGrid controls RowHeight property. At design time, you can change the
column width interactively by resizing the column or by changing the columns width in the
Column objects property page.
Use the DBGrid controls Columns collections Count property and the Recordset objects
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 objects 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
objects 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 controls 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.

50

VISUAL BASIC

Develop a strategy for a twenty-fold increase in Indias software and other IT


Service exports in the next ten years. In particular, the policy will focus on the
development of world-class software products and brands that can quickly
establish Global dominance.
Term of Reference for National IT Task Force

MENUS AND DIALOG BOXES

COMPETENCY OBJECTIVES
The objective of this section is to guide students towards the usage of Menus & Dialog boxes involved during
Computer Programming. At the end of the chapter the student should be able to :v
v
v
v
v

Understand the basic concepts of Menus & Dialog Boxes.


Create & control the menus at run time.
Observe the effects when the various menu items are clicked.
Differentiate between Model & Modeless Dialog boxes.
Use the pre-defined dialog boxes and create custom Dialog boxes.

51

VISUAL BASIC

52

VISUAL BASIC

CHAPTER - 4

MENUS AND DIALOG BOXES

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

Fig.: Menu Editor


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,
53

VISUAL BASIC

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 doesnt appear in a
menu.
Index :
Allows you to assign a numeric value that determines the controls position
within a control array. This position isnt 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 menus 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.
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 menus Click event rather than executing any
event code.
Cancel :
Closes the Menu Editor and cancels all changes.

54

VISUAL BASIC

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.
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.
Displaying a check mark on a menu control.
Using the checked property, you can place a check mark on the menu to:
l
Tell the user the status of an on/off condition.
l
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.
Example program
This example program has Form1 with a menu bar with the following items.
Caption

Name

Cut and paste


Font
. .12
..14
File
.

mCut
mFont
mSep
Fsize
mSep1
Fsize
File
Mfile

Index

1
2
0

mFile is a control array with on element of index 0. MFont is control array with 2 elements.

55

VISUAL BASIC

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.

3.

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.

4.

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
General

Declarations

Dim ind As Integer


Dim Selected As String

Sub UpdateMenu()
ind = ind + 1
Load mFile(ind)
mFile(ind).Caption =
Selected
mFile(ind).Visible = True
End Sub
Procedure on Form1 load
Private Sub Form_Load()
Text1.Text =
Form2.Text1.Text
End Sub

Declarations made in general declarations


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

Set a new index and load the menuitem

Procedure that is executed when form is


loaded

56

VISUAL BASIC

Procedure 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 uncheck 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

57

VISUAL BASIC

Procedure when
clicked

Command button named 'ComForm2' caption 'Form2' is

Private Sub ComForm2_Click()


Displays Form2 as a modal dialog box
Form2.Show 1
will display Form2 as a modeless dialog
Text1.Text = Form2.Text1.Text Form2.show
b
Selected = Form2.Text1.Text
Update Menu
The general procedure is being called

End Sub
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

lklklskdfklk

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.

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.
58

VISUAL BASIC

Show method without style argument displays a modeless dialog box.


Form2.Show
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.
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.
The other properties often changed are
Property
Borderstyle
0
1
2

Setting
0,1,2,3,4 or 5
None
Fixed Single
Sizable and soon.

ControlBox
Min button
Max button

True/False
True/False
True/False

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

60

VISUAL BASIC

How you gather, manage and use information will determine whether
you win or lose. A positive and rational information - focussed leadership can
lead to extra-ordinary success.

DATABASE CONNECTIONS

COMPETENCY OBJECTIVES
The objective of this section is to guide students towards the most important objective of Visual Basic. This
Chapter summarises the concept of connecting Visual Basic to any back-end. At the end of the chapter the
student should be able to :v
v
v
v
v

Understand and use the copncepts of database most effetively.


Create & open Recordsets and Dynasets.
Use the recordsets to manipulate the Data.
Create a new query, run it, close it and delete it.
Use data and bound control according to the need of his program.

61

VISUAL BASIC

62

VISUAL BASIC

CHAPTER - 5

DATABASE CONNECTIONS

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:
l
l

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, Paradox,
FoxPro, Btrieve and SQL server etc.

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
63

VISUAL BASIC

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.
Opening a Database
You can use two different methods to open a database in Visual Basic:
l
Use the data control.
l
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:
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
64

VISUAL BASIC

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.
l
Databasename provides Visual Basic with the named source for the data.
l
Connect provides Visual Basic with the type of database and the optional paramaters
that may be needed to gain access to the database.
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

In the case of Table variables, the changes, additions, and deletions that other users make
are written immediately as you move through the records. In the case of Dynaset or Snapshot
variables, the additions and deletions that other users make are not written.
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:
l
l
l

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.
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.

65

VISUAL BASIC

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)
66

VISUAL BASIC

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 ordereven 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)
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.
Selecting Records
When you want to further limit the scope of records returned by a Dynaset or Snapshot you
can:
l
Create a new Dynaset or Snapshot after having set the Filter property on an existing
Dynaset or Snapshop.
l
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:

67

VISUAL BASIC

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.
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.
l
The current record will become undefined and unusable when the current record is
positioned as follows:
l
Ahead of the first record, when the BOF property is True.
l
Behind the last record, when the EOF property is True.
l
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.
l
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.
l
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.
Method
MoveFirst
MoveLast
MoveNext
MovePrevious

Purpose
Makes the first record the current record
Makes the last record the current record
Makes the next record the current record
Makes the previous record the current record

68

VISUAL BASIC

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
FindFirst criteria
FindLast criteria
FindNext criteria
FindPrevious criteria

What it finds
First record matching criteria
Last record matching criteria
Next record matching criteria
Previous record matching criteria

Starting part
First record in recordset.
Last record in recordset.
Current record.
Current record.

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
69

VISUAL BASIC

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
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.
l
Use the Edit method to prepare the current record for editing.
l
Assign new values to the fields you want to change in the current record.
l
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:
l
Use the AddNew method to create a new record. The current record pointer is saved.
l
Assign new values to the fields in the new record.
l
Use the Update method to save the new record.

70

VISUAL BASIC

Locking Data
When multiple users are attempting to change the same data, there is an obvious conflictwhich 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:
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
71

VISUAL BASIC

Deleting a Query
To delete a query, you use following code:
db.DeleteQueryDef New Query
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
l
l
l

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:
l
l

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

72

VISUAL BASIC

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.
12. Your program is complete. Save the Project.
Now youre ready to run the prosgram 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.

73

VISUAL BASIC

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.
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
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:
l
l
l
l

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.
74

VISUAL BASIC

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
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
75

VISUAL BASIC

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.
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.
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.
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.

76

VISUAL BASIC

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
77

VISUAL BASIC

Data1.Refresh
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:
l
Your table has a unique index and this record is already in the table
l
One of the index key fields in your record is Null.
l
You do not have permission to write to the table or database.
l
The table is not updatable.
l
The record is on a page that is locked.
l
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
78

VISUAL BASIC

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
Data1.Recordset.MoveFirst
Data1.Recordseet.Bookmark = MyBookmark

Save current record pointer


Move off the record
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.
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:
l
The name of a database table.
l
The name of a Microsoft Access database query.
l
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

79

VISUAL BASIC

Databases and their respective recordsets are closed when:


l
l
l

You use the Close method against a specific recordset.


The form containing the data control is unloaded.
The program executes an End statement.

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
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

80

VISUAL BASIC

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

81

VISUAL BASIC

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 dont have to list the table name in the DELETE statement.
DELETE FROM Employees
WHERE Title = Trainee;
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
82

VISUAL BASIC

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 controls RecordSource property to query the database, or you can use
one of the Find methods with a data controls Recordset property.
Querying a Database
Using an SQL query with a data control
l
l

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 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


l

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

83

VISUAL BASIC

84

VISUAL BASIC

ASSIMILATION EXERCISES
Chapter 1 - 3
1.

Give 5 examples of objects and their properties(List atleast 5 properties for each objects).

2.

Which of the following is not a Visual Basic object?


a.
command button
b.
form
c.
variable
d.
text box

3.

List down the errors in the following statement?


txtDisplay.Text = Hi there!
Rectify it.

4.

Build the form from the Table given below. After you finish, attach code to the Click event
of the Exit button so that when the user clicks the Exit button, the program terminates.
Object
Form
Horizontal Scroll Bar

Command Button

Check Box

FontSize
Check Box

5.

Property
Name
Caption
Name
Max
Min
Name
Caption
FontName
FontSize
Name
Caption
FontName
10
Name
Caption
FontName
FontSize

Setting
frmEX1
The Exercise 1 Program
hsbMyScrollBar
100
0
cmdExit
E&xit
System
10
chkMyCheckBox
Check1
System
chkOurCheckBox
Check2
System
10

A certain statement apears in this book as follows :


Info = ABC + _
+ DEF + GH
How would you type it in your Visual Basic program?
a. Info = ABC + DEF + GH
b. Exactly as shown in the question.
85

VISUAL BASIC

6.

Suppose your program includes a vertical scroll bar with the name vsbVolume. Write a
statement that places the thumb of the scroll bar at position 37.

7.

Suppose your program includes a horizontal scroll bar with the name hsbDistance. How
do you change the Min and Max properties of the scroll bar to 10 and 200, respectively?

8.

Enhance the Sum program as follows:


Add a command button with the following properties: The Name property should be
cmdSqr and the Caption property should be Square Root.
Whenever the user clicks the Square Root button, the program should calculate and
display the square root of the number selected by the scroll bar.

Hint : Use the Sqr( ) function of Visual Basic to calculate the square root of a number.

Chapter - 4
1.

What is the difference between the Enabled property and the Visible property of a menu
control?

2.

How do you create a menu control array, and what is it used for?

3.

What are shortcut keys and how do you create them?

4.

What are check marks and how do you use them in a program?

5.

What is a separator bar?

6.

Assume that you have a common dialog custom control called CommonDialog1. What
does the following statement do?
CommonDialog1.Action = 2

7.

Write code that displays a dialog box with the title ERROR, the message Disk error1, an
OK button, and an exclamation point icon.

8.

Write code that displays a dialog box with the title QUESTION, the question message is
Are you sure you want to quit?. There are two buttons - Yes and No, and a question
mark icon. If the users response to the question is Yes (the user clicked the Yes button),
then terminate the program.

9.

Write code that displays a dialog box asking the user to enter a number between 1 and
10. If the user enters a number in the range 1 to 10, the code should display a dialog box
with the selected number. If, however, the user enters a number that is not in the range
1 to 10 (or the user enters non-numeric characters), the code should display an error
message. If the user presses the Cancel button of the dialog box, the code should not
display anything.
Chapter - 5

1.

What do you mean by RDO? What are the two categories with which Visual Basic can
be used as a Front end tool? Explain the differences between (i) Snapshots
(ii) Recordsets (iii) Dynaset. Give examples.

86

VISUAL BASIC

2.

Write a code to create a dynaset using an SQL Query that joins data from the tables in
the ATC database (assume that the ATC database is already existing).
ATC Name
TeeCS-CEDTI Training Centre
IBeeM-CEDTI Training Centre
HPee-CEDTI Training Centre
SAM-Private Coaching Centre
PETER-Private Coaching Centre

Validation Date
01-05-1999 to 01-05-2003
01-05-1999 to 01-05-2001
01-05-1999 to 01-05-2002
01-05-1999 to 01-05-2000
01-05-1999 to 01-05-2000

Faculty
BE / MCA
BE / MCA
BE / MCA
BA
B.Com

3.

How can you limit the scope of records returned by a Dynaset or a Snapshot? Write a
code that filters the ATC table to produce a dynaset that maintains only those ATCs
that have the string CEDTI Training Centres embedded in the name and then sort the
ATCs by the validation date and the first alphabet of the name (Refer the database given
in Q.2. Make the necessary assumptions wherever required).

4.

List the various methods for positioning the current record in the Recordsets. Referring
to Question 3, find the first ATC with name that begins with the letter T or higher in the
alphabet (use the most efficient method).

5.

After defining a recordset, how can you manipulate the data? Give examples.

6.

What do you mean by (i) Data control (ii) Bound control.

7.

Referring Question 2, create the Student Input program as a tool for entering and
revising of records in the Student table of the ATC mdb database. Use the necessary
data controls, bound text boxes and labels to produce the following output :

7b.

You should be able to enter new records by clicking on the Add New button.

8.

Write a code to add a new title to the ATC table of the ATC.mdb.
ATC Name becomes Authorised Training Centre
Student Name becomes Students Particulars
Module becomes Software Modules

9.

Suppose that the Parts table includes the InStock Boolean field. Write a SQL statement
so the Data1 control access only those records that have their InStock fields equal to
No.

10. When using an Access database, what does the Database Name property of a data
control specify.
87

Potrebbero piacerti anche