Sei sulla pagina 1di 60

SUBJECT: VISUAL BASIC 6.

1/119

SUBJECT: VISUAL BASIC 6.0


2/119
applications. This window has three tabs: New, Existing, and recent. You can
use any of these tabs to help get you started on a project in Visual Basic.

LECTURE 1
Introduction to VB. (Visual Basic)
Visual basic is a Microsoft Product. Visual basic is indisputably the most
attractive development environment currently available. Visual basic is an ideal
programming language for developing sophisticated professional applications
for Microsoft windows. It makes use of graphical uses interface for crating
robust and powerful applications.
Visual basic is a much-enhanced version of the Basic Programming Language
and the basic Integrated Development Environment (IDE). It acts as front-end
tool for developing applications with databases (FoxPro, oracle, SQLServices) as
back end.

How to Invoke VB
After installing Visual Basic on your system, you start it from the Windows Start
menu. The exact details will depend on how you got Visual Basic, which is
available both as a standalone product and as part of Microsofts Visual Studio
development platform. In any case, the process will be as follows:

1. Click on the Start button on the Windows taskbar.


2. Click on Programs.
3. On the next menu, click on Microsoft Visual Basic 98 or Microsoft
Visual Studio 98.
4. Finally, click on Visual Basic 98.

Difference between console based and window application


Console
Window
Uses character uses interface (CUI) Uses Graphical user interface (GUI)
Execution
speed
is
fast
as Slow execution speed.
compared to Window Application.
When you start Visual
for the first time, the
Project Wizard will open,
you will notice the New
Project dialog box (Figure
From this window, you can
from several types of
projects that will give you
head start on developing

Basic
and
1).
select
a
your

Introduction to
Environment)

VBIDE

(Integrated

Development

Main Window
The main Visual Basic window serves two primary purposes. First, it contains the
other windows that the program displays. Second, it displays the menu bar and
toolbar along the top of the window. The menu bar contains the titles of Visual
Basics menus, which contain the programs commands. The toolbar displays
buttons you can click on to carry out commonly needed commands. Note that if
you position the mouse pointer over a toolbar button for a moment (dont click),
Visual Basic will display a brief description, called a tool tip, of the buttons
function.

SUBJECT: VISUAL BASIC 6.0

3/119

SUBJECT: VISUAL BASIC 6.0


4/119
The toolbox buttons display tool tips in the same manner as the toolbar buttons.
The top left button in the toolboxthe arrowis not a control, but represents
the pointer. Select it when you want to edit controls that you have already
placed on the form.

Project Explorer Window


At the top right of the screen is the Project Explorer window, which lists all the
modules in the current project. The term project simply means a Visual Basic
program under development, with all its component objects. A module is just a
component of a Visual Basic project. For example, each form is a module. When
you start a new project, it contains only a single modulea form with the
default name Form1. Likewise, the project itself has the default name Project1.
Youll assign more meaningful names to modules and the project as you work.

Properties Window
Below the Project Explorer window is the Properties window. This window lists
the properties of the currently selected object, the name of which is displayed in
the box at the top of the window. A form is an object, and the controls you place
on it are also objects. An objects properties control its appearance and
behaviorfor example, the color of a forms background is one of its properties.
Youll be learning a lot about object properties throughout this book, so I wont
go into any further detail right now.

Form Layout Window

Form Design Window


Near the center of the screen is the Form Design window where you will draw
your programs visual interface. You start each new project with one blank form,
adding others as you develop the project. Each form in a project corresponds to
a window or dialog box in the final program. During program design, a grid of
dots aids you in aligning the elements placed on the form. These dots are not
displayed in the final program.

Toolbox Window
On the left side of the screen is the toolbox. This window contains icons
representing the various visual objects, or controls, that you can place on a
Visual Basic form. To place a control, click on the corresponding toolbox button,
then point and drag on the form to specify the size and location of the control.

In the lower right corner of the Visual Basic screen is the Form Layout window.
It shows a miniature representation of a computer screen with a small icon
showing the relative size and position of each of your projects forms. You use
the Form Layout window to view the relationships among your programs forms.
If you point at a form icon and drag it to a new location, youll change the
screen position where the form initially displays during program execution.
The Immediate window lets you enter a Visual Basic command or
expression and see its result using the Print command (which can also be
shortened to ?). In break modethat is, when you have temporarily suspended
a running programyou can use these commands to display the current value
of a variable or an expression. You can also write diagnostic messages from
your application's code to this window using the Debug.Print statement. Because
the Immediate window isn't visible when the application is compiled and
executed outside the environment, such diagnostic statements aren't included in
the executable file. You can quickly open the Immediate window by pressing the
Ctrl+G key combination

The Locals window is active only when a program is executing. It lists the
values of all the variables that are local to a module or to a procedure. If the
variable is an object itself (a form or a control, for example) a plus (+) sign

SUBJECT: VISUAL BASIC 6.0


5/119
appears to the left of the variable name, which means that you can expand it
and look at its properties.

The Watches window has a dual purpose: it lets you continuously monitor
the value of a variable or an expression in your programincluding a global
variable, which is outside the capabilities of the Locals windowand it also gives
you the ability to stop the execution of a program when a given expression
becomes True or whenever it changes its value. You can add one or more watch
expressions using the Add Watch command from the Debug menu, or you can
select the Add Watch command from the pop-up menu that appears when you
right-click the Watches window itself.
The Color Palette window is handy for quickly assigning a color to an
object, such as the control that's currently selected on a form designer. You can
select the foreground color of an object by left-clicking on the desired color, and
if you click on an empty item in the bottom row of cells you can also define a
custom color. Finally, you can select the background color of an object if you
click on the larger square located near the upper left corner of the Color Palette
window.

SUBJECT: VISUAL BASIC 6.0


6/119
have Top and Left properties, which specify the screen position of the upperleft corner of the object. Likewise, the Height and Width properties specify the
size of the object. Each type of object has its own set of properties, often
running to a couple dozen or more. While some properties (such as those just
mentioned) are common to many or all objects, other more specialized
properties are relevant to only one or, at most, a few types of objects.
Object properties play an important part in a Visual Basic programs interactions
with the user. For example, if the user has entered text in a Text Box control,
the program can access that text via the controls Text property. In a similar
manner, by reading a Check Box controls Value property, the program can
determine whether the user has turned the corresponding program option on or
off. Note that when I say the program, I am referring to the Basic code in the
programcode that you write.
You can change object properties during program design (referred to as designtime). Properties can also be read and modified at runtime, while the program is
executing (runtime). The ability to read and modify properties at runtime may
sound trivial, but it plays an essential role in Visual Basics power. This flexibility
permits a program to be self-modifyingto change its appearance and behavior
in response to current conditions and user input.

Methods
Other Windows
Visual Basic has a number of other windows you will use during program
development. They are not shown in Figure 2.2 because Visual Basic displays
these windows only when you need them. For the most part, well deal with
these other windows as the need arises. One type of window, however, is so
central to Visual Basic programming that Ill take a moment to introduce it now.
In a code window, you enter and edit Basic code. It works pretty much like any
other Windows text editor: You can type text, delete it, move and copy it from
place to place, and so on. If you want to see what a code window looks like,
click on the View Code button in the Project Explorer window. An empty code
window will open.

Event Driven Programming


VB is an Event driven
each and every users
program. While in an
executed only when a
assigned to the event.

programming language i.e. in VB there is an event for


action; events are various things that can happen in a
event driven application, the program statements are
particular event calls a specific part of the code that is

Properties
Each Visual Basic object has properties that determine its behavior and, if the
object has a visual interface, appearance. For example, almost all visible objects

Most Visual Basic objects have one or more methods associated with them. A
method can be thought of as a chunk of code that does something to, or with,
the object. Instead of you having to write the code, however, it is an integral
part of the object.
The methods that are available differ from object to object. For example, the
Move method, which moves an object to a different location on screen, is
available for most objects. In contrast, the Print method, which displays text on
an object, is available only for forms and a few other objects where the display
of text makes sense.

Events Make It Happen


The second major innovation that Visual Basic introduced is event-driven
programming. (The firstin case you were dozing for the first part of the
chapteris the use of visual objects.) What are events, and how do they work?
The first part of this question is easy. With a few exceptions, events are things
the user does with the mouse or the keyboard while the program is running. In
other words, event means user input. So far so good, and hardly surprising.

Event Procedures
Earlier in this chapter, I mentioned that Visual Basic brought two
groundbreaking innovations to Windows programming. The first one was visual
interface design. Now well meet the second one: event detection. Well, not
event detection itself; thats nothing new. The real innovation is the ease with

SUBJECT: VISUAL BASIC 6.0


7/119
which a programmer can make his or her program respond to events, and this is
all accomplished with event procedures.
An event procedure is a block of Basic code associated with an event. When the
event is detected, the code in the procedure is automatically executed. Creating
an event procedure in Visual Basic is a simple two-step process:
1. Select the object (Text Box, Command Button, etc.) that will respond
to the event.
2. Choose the desired event from a list of events that the selected object
can detect.
Its really that simple. Carrying out these steps creates the skeleton of an event
procedure that has this general form:
Sub ObjName_Event()
End Sub
The name of the event procedure identifies both the visual object and the event.
ObjName is the name of the object (its Name property), and Event is the
name of the event. For example, the event procedure to detect a mouse click on
a Command Button named ExitButton would be ExitButton_Click. This
procedure is executed when the program runs and the user clicks on the button.
Nothing more is involved in getting the program to respond to events.

LECTURE 2
VB Project: - VB Project is a group of all the files that make up our program.
These might include forms, modules, graphics or Active-X controls each of which
is saved as an individual file.
File Type Description
.FRM
Form
.BAS
Module
.FRX
Automatically generated file for every graphic in your object.
.OCX
Active -X control
.VBP
Visual Basic Project.
Back End - Front End:
Front End: The interface, which provides the interactivities with application to
user, is called fronted. Tools used for fronted are: - VB, VB.net, Developers
2000 etc.
Back End: The code which response every user actions as stores data is
particular manner, which is inputted by user using fronted, is called backend.
Back end packages are: - Database Management system (oracle, SQLServer,
Informix, Access)

SUBJECT: VISUAL BASIC 6.0

8/119

Design Time Run Time


Design Time: During Design time, programmers can create, modify, design
forms and enter code, which will be executed at the happening of certain
events.
Run Time: During runtime, the programmers comes to know about running the
code that he has written during design time, It also makes the development
process and programmers can pause the running program & debug the errors
and can again run the program. It also lets you know how the program looks
like when it runs.

Introduction to Controls
The controls are the building blocks on which we assemble the VB program. The
toolbox is a palette of controls from which we can select controls and place them
in our forms. There are two types of Controls in VB.

Intrinsic Controls:
In Microsoft Visual Basic jargon, intrinsic controls (or built-in controls) are those
controls visible in the Toolbox window when you launch the environment. This
important group includes controls, such as Label, TFextbox, and
CommandButton controls, that are used in nearly every application. As you
know, Visual Basic can be extended using additional Microsoft ActiveX Controls
(formerly known as OCX controls, or OLE custom controls) either provided in the
Visual Basic package or available as commercial, shareware, or even freeware
third-party products

Extrinsic Controls
These controls we have to add these from the components windows by selecting
it from the project menu. These controls are the files having, OCX extension.

Intrinsic Controls
Controls
Pointer

Prefix Description
-Selects controls.

Label

lbl

Displays static text.

Frame

Frm

Serves a container for other

Check Box

chk

Enables users to select or deselect an

Combo Box

cbo

Enables users to select from a list of items or

Hscroll Box

hsb

add a new

controls.
option.

item.

Allows users to scroll horizontally through a


list of data in another control.

SUBJECT: VISUAL BASIC 6.0


9/119
Timer
tmr
Lets the program to perform actions in

real

time without user interaction.


Dir List Box

Dir

Enables you to select a dir or a

Shape

shp

Displays a shape on a form.

folder.

Image

Img

Displays graphics on a form.

Picture Box

Pic

Displays graphics on a form & serves as a

SUBJECT: VISUAL BASIC 6.0


10/
10/119
You create a new form at design time using the Add Form command from the
Project menu or by clicking on the corresponding icon on the standard toolbar.
You can create forms from scratch, or you can take advantage of the many form
templates
provided
by
Visual
Basic
6.

container.
Text Box

Txt

Can be used to display enter and

edit text

Command Button cmd

Enables users to initiate action

Options Button

Lets user select one option from a group.

Opt

List Box

Lst

Enables user to select from a list of items.

Vscroll Bar

vsb

Enables users to scroll vertically through a list


data in another control.

Drive List Box

Drv

Lets user select a drive.

File list Box

fil

Lets user select a file.

Line

Lin

Displays a line on a form.

Data

Dat

Connects user program to a database.

Extrinsic Controls
 Rich Text Box  Common Dialog Control  Microsoft Windows Common
Control
 Microsoft ActiveX Data Control  Microsoft Flex Grid Control etc.,

LECTURE 3
The Form Object
After this long introductory description of properties, methods, and events that
are common to most Visual Basic objects, it's time to see the particular features
of all of them individually. The most important visible object is undoubtedly the
Form object because you can't display any control without a parent Form.
Conversely, you can write some moderately useful applications using only forms
that have no controls on them. In this section, I'll show a number of examples
that are centered on forms' singular features.

Basic Form Properties


After creating a form and resizing it to meet your requirements, you'll probably
want to set a few key properties. BorderStyle is one of the properties that
largely affects the form's behavior. Its default value is 2-Sizable, which creates
a resizable window. To create a nonresizable form, you should set it to 1-Fixed
Single or 3-Fixed Dialog: the only difference between the two settings is that the
latter can't show Minimize and Maximize buttons. If you're creating a floating,
toolboxlike form, you should use the values 4-Fixed Toolwindow or 5-Sizable
Toolwindow. Theoretically, you can also use the value 0-None to exclude any
type of border and caption, but you'll rarely find a use for such borderless
forms.

Properties:
 Name: The name property is very important property in VB. This is the
name of the control that VB refers to when the program runs. In order to
know exactly what your forms are you should give them a descriptive
name and prefix it with letters form.
 Back Color: The Back Color property sets the background color of the
form.
 Border Style: The Border Style property determines how the border of a
form behaves. A form can have fixed borders that cannot be stretched or
resizable borders that can be stretched by dragging them with name.

SUBJECT: VISUAL BASIC 6.0


11/
11/119
 Caption: A caption is the text that appears on the title bar of the form. If
you set the border style property to none, then the caption is hidden.
 Height: This property is used to change the height of a form.
 Width: This property is used to change the width of a form.
 Window Style: The window style property is responsible for how the form
starts up. There are three options.

A Form's Life Cycle


To understand how Form objects really work, the best approach is having a look
at the sequence of events that they raise. This sequence is shown in the
illustration below. I'll describe each event in turn.

The Initialize event


The first event in the life of any form is the Initialize event. This event fires as
soon as you reference the form's name in your code, even before Visual Basic
creates the actual window and the controls on its surface. You usually write code
in this event to correctly initialize the form's variables:
Public CustomerName As String
Public NewCustomer As Boolean
Private Sub Form_Initialize()
CustomerName = ""
' This isn't really needed.
NewCustomer = True
' This is necessary.
End Sub
When a form is initialized, all its module-level variables (CustomerName and
NewCustomer, in the preceding example) are assigned their default values. So it
isn't strictly necessary to assign a value to a variable if the value is 0 or an
empty string. In the code above, for example, there's no need for the
assignment to the CustomerName variable, but you might want to leave it there
for better readability

The Load event

SUBJECT: VISUAL BASIC 6.0

12/
12/119

Private Sub Form_Load()


' You can initialize child controls.
txtName.Text = CustomerName
If NewCustomer Then chkNewCustomer.Value = vbChecked
End Sub
Loading a form doesn't necessarily mean that the form is going to become
visible. A form becomes visible only if you invoke its Show method or if the form
is the application's startup form. You can decide to load a form and keep it
hidden until you set some of its properties, as follows:
' The Load method is optional: Visual Basic loads the form
' when you reference the form or one of its controls.
Load frmCustomer
' Directly assign a control's property.
' (Not recommended, but this is just an example.)
frmCustomer.txtNotes.Text = gloCustomerNotes
frmCustomer.Show

The Resize event


One instant before the form becomes visible, Visual Basic fires a Resize event.
You usually take advantage of this event to rearrange the controls on the form
so that they fit the available space in a nice layout. For example, you might
want the txtCustomer control to extend to the right border and the multiline
txtNotes control to extend to both the right and the bottom border:
Private Sub Form_Resize()
txtCustomer.Width = ScaleWidth _ txtCustomer.Left
txtNotes.Width = ScaleWidth _ txtNotes.Left
txtNotes.Height = ScaleHeight _ txtNotes.Top
End Sub

What happens after the Initialize event depends on how you referenced the form
in your code. If you referenced only one of its public variables (or, more
correctly, its Public properties), as in the following line of code,

The Resize event also fires when the user resizes the form manually and when
you programmatically alter the form's size.

frmCustomer.CustomerName = "John Smith"

Soon after the first Resize event comes the Activate event. This event also fires
whenever the form becomes the active form in the current application but not if
it loses and then regains the focus because the user switched to another
application. The Activate event is most useful when you need to update the
form's contents with data that might have been modified in another form. When
the focus returns to the current form, you refresh its fields:

nothing else happens and execution flow goes back to the caller. Your code is
now able to set the CustomerName variable/property to the new value because
in the meantime Visual Basic has created a new instance of the frmCustomer
object. On the other hand, if your code had referenced a form's own property or
a control on the form itself, Visual Basic can't complete the operation until it
actually creates the window and its child controls. When this step is completed,
a Load event is fired:

The Activate event

Private Sub Form_Activate()


' Refresh displayed information from global variables.

SUBJECT: VISUAL BASIC 6.0

13/
13/119

txtTotalOrders.Text = gloTotalOrders
...
End Sub

The Paint event


Another event might fire before the form becomes fully functionalthe Paint
event. This event doesn't fire if you set the form's AutoRedraw property to True.
In a Paint event procedure, you're expected to redraw the form's contents using
graphic methods, such as Print, Line, Circle, Point, Cls, and so on. Here's an
example that draws a colorful circular target:
Private Sub Form_Paint()
Dim r As Single, initR As Single
Dim x As Single, y As Single, qbc As Integer
' Start with a clean surface.
Cls
' The center of all circles
x = ScaleWidth / 2: y = ScaleHeight / 2
' Initial radius is the lower of the two values.
If x < y Then initR = x Else initR = y
FillStyle = vbFSSolid
' Circles are filled.
' Draw circles, from the outside in.
For r = initR To 1 Step -(initR / 16)
' Use a different color for each circle.
FillColor = QBColor(qbc)
qbc = qbc + 1
Circle (x, y), r
Next
' Restore regular filling style.
FillStyle = vbFSTransparent
End Sub
The Paint event procedure is executed whenever the form needs to be
refreshedfor example, when the user closes or moves away a window that
partially or totally covered the form. The Paint event also fires when the user
resizes the form and uncovers new areas. But it does not fire if the user shrinks
the form. To complete the example above, you may want to manually force a
Paint event from within the Resize event so that concentric circles are always in
the center of the form:
Private Sub Form_Resize()
Refresh
End Sub

SUBJECT: VISUAL BASIC 6.0

14/
14/119

The Unload event


If you don't cancel the unload operation, Visual Basic eventually raises the
Unload event and gives you a last chance to prevent the closure of the form. In
most cases, you take this opportunity to alert the user that data needs to be
saved:
' This is a module-level variable.
Dim Saved As Boolean
Private Sub Form_Unload(Cancel As Integer)
If Not Saved Then
MsgBox "Please save data first!"
Cancel = True
End If
End Sub

The Deactivate event


As I mentioned previously, when you switch to another form in your application,
the form receives a Deactivate event and another Activate event when it regains
the input focus. The same sequence occurs if you temporarily make a form
invisible by setting its Visible property to False or by invoking its Hide method.

Textbox
TextBox controls offer a natural way for users to enter a value in your program.
For this reason, they tend to be the most frequently used controls in the
majority of Windows applications. TextBox controls, which have a great many
properties and events, are also among the most complex intrinsic controls. In
this section, I guide you through the most useful properties of TextBox controls
and show how to solve some of the problems that you're likely to encounter.
After you place a TextBox control on a form, you must set a few basic
properties. The first thing I do as soon as I create a new TextBox control is clear
its Textproperty. If this is a multiline field, I also set the MultiLineproperty to
True.
You can set the Alignment property of TextBox controls to left align, right align,
or center the contents of the control. Right-aligned TextBox controls are
especially useful when you're displaying numeric values. But you should be
aware of the following quirk: while this property always works correctly when
the Multiline property is set to True, it works with single-line controls only under
Microsoft Windows 98, Microsoft Windows NT 4 with Service Pack 3, or later
versions. Under previous versions of Windows 9x or Windows NT, no error is
raised but single-line TextBox controls ignore the Alignment property and always
align their contents to the left.

SUBJECT: VISUAL BASIC 6.0

15/
15/119

SUBJECT: VISUAL BASIC 6.0

16/
16/119

Run-Time Properties
The Text property is the one you'll reference most often in code, and
conveniently it's the default property for the TextBox control. Three other
frequently used properties are these:
The SelStart property sets or returns the position of the blinking caret (the
insertion point where the text you type appears). Note that the blinking cursor
inside TextBox and other controls is named caret, to distinguish it from the
cursor (which is implicitly the mouse cursor). When the caret is at the beginning
of the contents of the TextBox control, SelStart returns 0; when it's at the end
of the string typed by the user, SelStart returns the value Len(Text). You can
modify the SelStart property to programmatically move the caret.
The SelLength property returns the number of characters in the portion of text
that has been highlighted by the user, or it returns 0 if there's no highlighted
text. You can assign a nonzero value to this property to programmatically select
text from code. Interestingly, you can assign to this property a value larger than
the current text's length without raising a run-time error.
The SelText property sets or returns the portion of the text that's currently
selected, or it returns an empty string if no text is highlighted. Use it to directly
retrieve the highlighted text without having to query Text, SelStart, and
SelLength properties. What's even more interesting is that you can assign a new
value to this property, thus replacing the current selection with your own. If no
text is currently selected, your string is simply inserted at the current caret
position.

Properties Of TextBox Control:


 Name: This property is used to set the name of the text box. By
convention this begins with the txt prefix.
 BackColor: Returns/sets the background color used to display text.
 Locked: It has two states i.e. true/false. Which determines whether a
control can be edited or not.
 MaxLength: Returns or sets the maximum no of characters can be
entered in a text box.
 MultiLine: No of characters that can be entered in a text box. This
properly has true values true or false. It makes the textbox to accept
multiple lines of text.
 PasswordChar: Sets a password char for the character entered in the
text box.
 Text: This property returns or sets for the character entered in the text
box.

Events Of TextBox Control:

 Click: Generated when user click the mouse on the control


 Change: The change event occurs every time the user inserts, replaces or
deletes & character in a text box.
 GotFocus: Generated when user selects the text box control.
 LostFocus: Generated when the focus is shifted from the control.
Method:
 SetFocus: set focus sets the focus to the text box.

Label
Most people use Label controls to provide a descriptive caption and possibly an
associated hot key for other controls, such as TextBox, ListBox, and ComboBox,
that don't expose the Caption property. In most cases, you just place a Label
control where you need it, set its Caption property to a suitable string
(embedding an ampersand character in front of the hot key you want to assign),
and you're done. Caption is the default property for Label controls. Be careful to
set the Label's TabIndex property so that it's 1 minus the TabIndex property of
the companion control.

Properties:





Caption: Used to get/display the text in the label.


Name: Sets/gets the name of the label.
BackColor: Sets the background colors to the label text.
Font: This option is used to set the font style, size, and color of the text.

Command Button
Using CommandButton controls is trivial. In most cases, you just draw the
control on the form's surface, set its Caption property to a suitable string
(adding an & character to associate a hot key with the control if you so choose),
and you're finished, at least with user-interface issues. To make the button
functional, you write code in its Click event procedure, as in this fragment:
Private Sub Command1_Click()
' Save data, then unload the current form.
Call SaveDataToDisk
Unload Me
End Sub
You can use two other properties at design time to modify the behavior of a
CommandButton control. You can set the Default property to True if it's the
default push button for the form (the button that receives a click when the user
presses the Enter keyusually the OK or Save button). Similarly, you can set

SUBJECT: VISUAL BASIC 6.0


17/
17/119
the Cancel property to True if you want to associate the button with the Escape
key.

Properties:
 Name: This name is used by your code and visual basic to distinguish it
from the rest of controls.
 Caption: Displays the text on the button.
 Enabled: It has two values True/False, whether the button is in working
at run time or not.
 Visible: Sets the visibilities to true/false.
 Picture: Allows the user to set a picture for the button.

Events:
 Click: invoked on mouse click
 GotFocus: This event is generated when the button gets the to us.
 LostFocus: Generated when the control lost the focus.

Hot Key
To give the user keyboard access to a control, insert an ampersand (&) before a
letter in caption property. At run time, this letter is underlined (the ampersand
is not visible), and the user can access the command by pressing ALT and the
letter. If you need an ampersand to show in the caption, put two consecutive
ampersands in the caption.

LECTURE 4
Variable
A variable is a name that references an area of memory, which holds a
temporary value. This value can change while an application is running.

Declaring Variables
In VB there are two types of declaration
Implicit Declaration: It is a default declaration there is no need to
declare variables before its used.
Explicit Declaration: This means that we must use a statement to
declare a variable. These statements describe the scope of the variable.
DIM variablename AS datatype

Naming Variables





The name must start with a letter.


It cant contain a period (.) and blank space.
The name must be unique within a current procedure.
Special symbols are not allowed within variable name expect underscore(_)

SUBJECT: VISUAL BASIC 6.0


18/
18/119
The name cannot be longer than 255 characters.

Scope and Lifetime of Variables


Not all variables are born equal. Certain variables live for the entire life of the
application, and others are created and destroyed a thousand times every
second. A variable could be visible only from within a procedure or a module or
could be in existence only during well-defined time windows over the lifetime of
the application. To better define these concepts, I need to introduce two formal
definitions.
The scope (or visibility) of a variable is the portion of code from which that
variable can be accessed. For example, a variable declared with the Public
attribute in a BAS module is visibleand can therefore be read from and written
tofrom anywhere in the application, whereas if the variable is declared Private,
it's visible only from within that BAS module.
The lifetime of a variable is the time period during which that variable stays
alive and uses memory. The lifetime of the Public variable described in the
previous paragraph coincides with the application's life, but in general this isn't
always the case. For instance, a local dynamic variable in a procedure is created
each time Visual Basic executes that procedure and is destroyed when the
procedure exits.

Global Variables
In Visual Basic jargon, global variables are those variables declared using the
Public keyword in BAS modules. Conceptually, these variables are the simplest
of the group because they survive for the life of the application and their scope
is the entire application. (In other words, they can be read and modified from
anywhere in the current program.) The following code snippet shows the
declaration of a global variable:
' In a BAS module
Public InvoiceCount as Long

' This is a global variable.

Module-Level Variables
If you declare a variable using a Private or a Dim statement in the declaration
section of a modulea standard BAS module, a form module, a class module,
and so onyou're creating a private module-level variable. Such variables are
visible only from within the module they belong to and can't be accessed from
the outside. In general, these variables are useful for sharing data among
procedures in the same module:
' In the declarative section of any module
Private LoginTime As Date
' A private module-level variable
Dim LoginPassword As String ' Another private module-level variable
You can also use the Public attribute for module-level variables, for all module
types except BAS modules. (Public variables in BAS modules are global

SUBJECT: VISUAL BASIC 6.0


19/
19/119
variables.) In this case, you're creating a strange beast: a Public module-level
variable that can be accessed by all procedures in the module to share data and
that also can be accessed from outside the module. In this case, however, it's
more appropriate to describe such a variable as a property:

Sub PrintInvoice()
Static InProgress As Boolean
...
End Sub

' In the declarative section of Form1 module


Public CustomerName As String
' A Public property

Alternatively, you can declare the entire procedure to be Static, in which case all
variables declared inside it are considered to be Static:

You can access a module property as a regular variable from inside the module
and as a custom property from the outside:

Static Sub PrintInvoice()


Dim InProgress As Boolean
...
End Sub

' From outside Form1 module...


Form1.CustomerName = "John Smith"
The lifetime of a module-level variable coincides with the lifetime of the module
itself. Private variables in standard BAS modules live for the entire life of the
application, even if they can be accessed only while Visual Basic is executing
code in that module. Variables in form and class modules exist only when that
module is loaded in memory. In other words, while a form is active (but not
necessarily visible to the user) all its variables take some memory, and this
memory is released only when the form is completely unloaded from memory.
The next time the form is re-created, Visual Basic reallocates memory for all
variables and resets them to their default values (0 for numeric values, "" for
strings, Nothing for object variables).

Dynamic Local Variables


Dynamic local variables are defined within a procedure; their scope is the
procedure itself, and their lifetime coincides with that of the procedure:
Sub PrintInvoice()
Dim text As String
...
End Sub

' This is a dynamic local variable.

Each time the procedure is executed, a local dynamic variable is re-created and
initialized to its default value (0, an empty string, or Nothing). When the
procedure is exited, the memory on the stack allocated by Visual Basic for the
variable is released. Local variables make it possible to reuse code at the
procedure level. If a procedure references only its parameters and its local
variables (it relies on neither global nor module-level variables), it can be cut
from one application and pasted into another without any dependency problem.

Static Local Variables


Static local variables are a hybrid because they have the scope of local variables
and the lifetime of module-level variables. Their value is preserved between
calls to the procedure they belong to until their module is unloaded (or until the
application ends, as is the case for procedures inside standard BAS modules).
These variables are declared inside a procedure using the Static keyword:

SUBJECT: VISUAL BASIC 6.0

20/
20/119
' This is a Static local variable.

' This is a Static local variable.

Static local variables are similar to private module-level variables, to the extent
that you can move a Static declaration from inside a procedure to the
declaration section of the module (you only need to convert Static to Dim,
because Static isn't allowed outside procedures), and the procedure will
continue to work as before. In general, you can't always do the opposite:
Changing a module-level variable into a Static procedure-level variable works if
that variable is referenced only inside that procedure. In a sense, a Static local
variable is a module-level variable that doesn't need to be shared with other
procedures. By keeping the variable declaration inside the procedure
boundaries, you can reuse the procedure's code more easily.
Static variables are often useful in preventing the procedure from being
accidentally reentered. This is frequently necessary for event procedures, as
when, for example, you don't want to process user clicks of the same button
until the previous click has been served, as shown in the code below.
Private Sub cmdSearch_Click()
Static InProgress As Boolean
' Exit if there is a call in progress.
If InProgress Then MsgBox "Sorry, try again later": Exit Sub
InProgress = True
' Do your search here.
...
' Then reenable calls before exiting.
InProgress = False
End Sub

Data types available in VB


Overview of Native Data Types

SUBJECT: VISUAL BASIC 6.0


21/
21/119
Visual Basic for Applications supports several native data types, including
integer and floating point numbers, strings, date and time values, and so on.
You can store data in a variable of the proper type, or you can use the Variant
data typethe default type in VBAwhich is a sort of jolly data type that's able
to host any type of data.

The Integer Data Type


Integer variables can hold integer values (whole numbers) included in the range
from -32,768 through 32,767. These variables are also known as 16-bit integers
because each value of this type takes 2 bytes of memory.

The Long Data Type


Long variables can hold integer values in the range from -2,147,483,648
through 2,147,483,647 and are also known as 32-bit integers because each
value takes 4 bytes of memory. As I mentioned previously, you're encouraged
to use Longs in your applications as the preferred data type for integer values.
Long variables are as fast as Integer variables, and in most cases they prevent
the program from breaking when dealing with numbers larger than expected.
One example is when you have to process strings longer than 32,767
characters: In this case, you must use a Long index instead of an Integer
variable. Watch out for this quirk when you convert code written for older Visual
Basic versions.

The Boolean Data Type


Boolean variables are nothing but Integers that can hold only values 0 and -1,
which stand for False and True, respectively. When you use a Boolean, you are
actually wasting 15 out of 16 bits in the variable, because this information could
be easily held in one single bit.

The Byte Data Type


Byte variables can hold an integer numeric value in the range 0 through 255.
They take only one byte (8 bits) each and are therefore the smallest data type
allowed by Visual Basic. Visual Basic 4 introduced the Byte data type to ease the
porting of 16-bit applications to Windows 95 and Microsoft Windows NT.
Specifically, while Visual Basic 4 for the 32-bit platform and later versions are
source-code compatible with Visual Basic 3 and Visual Basic 4 for the 16-bit
platform applications, they store their strings in Unicode instead of ANSI format.
This difference raised a problem with strings passed to API functions because
Visual Basic 3 programmers used to store binary data in strings for passing it to
the operating system, but the Unicode-to-ANSI automatic conversion performed
by Visual Basic makes it impossible to port this code to 32-bit without any
significant change.

The Single Data Type


Single variables can hold decimal values in the range from -3.402823E38
through -1.401298E-45 for negative values and 1.401298E-45 through

SUBJECT: VISUAL BASIC 6.0


22/
22/119
3.402823E38 for positive values. They take 4 bytes and are the simplest (and
least precise) of the floating point data types allowed by Visual Basic.

The Double Data Type


Double variables can hold a floating point value in the range 1.79769313486232E308 through -4.94065645841247E-324 for negative values
and 4.9406564581247E-324 through 1.79769313486232E308 for positive
values. They take 8 bytes and in most cases are the preferable choice when
you're dealing with decimal values. A few built-in Visual Basic functions return
Double values. For example, the Val function always returns a Double value,
even if the string argument doesn't include a decimal point. For this reason, you
might want to store the result from such functions in a Double variable, which
saves Visual Basic an additional conversion at run time.

The String Data Type


All 32-bit flavors of Visual BasicVisual Basic 4 for 32-bit platforms, 5, and 6
store strings of characters in Unicode format, while all previous versions used
the ANSI format. The difference is that Unicode uses two bytes for each
character, so theoretically a Unicode character can assume as many as 65,536
different values. Visual Basic manages two different types of strings:
conventional variable-length strings and fixed-length strings. You declare them
in different ways:
Dim VarLenStr As String
Dim FixedLenStr As String * 40
The first, obvious difference is that in any given moment a variable-length string
takes only the memory that it needs for its characters (actually, it takes 10
additional bytes for holding other information about the string, including its
length), whereas a fixed-length string always takes a fixed amount of memory
(80 bytes, in the preceding example).
If you are a performance-savvy programmer, you should remember that
conventional strings are usually faster than fixed-length string. This happens
because all VBA native string functions can deal only with variable-length
strings. In a sense, a fixed-length string is something that VBA isn't even aware
of: When you pass a fixed-length string to a VBA function, the compiler
generates hidden statements that convert that argument into a temporary
variable-length string.

The Currency Data Type


Currency variables can hold decimal values in a fixed-point format, in the range
from -922,337,203,685,477.5808 through 922,337,203,685,477.5807. They
differ from floating-point variables, such as Single and Double, in that they
always include four decimal digits. You can think of a currency value as a big
integer that's 8 bytes long and whose value is automatically scaled by a factor of

SUBJECT: VISUAL BASIC 6.0


23/
23/119
10,000 when it's assigned to the variable and when it's read back and displayed
to the user.

SUBJECT: VISUAL BASIC 6.0


24/
24/119
After the assignment, you can use the object variable to access the original
object's properties and methods:

The Date Data Type

frm.Caption = "Welcome to Visual Basic 6"


txtSalary.Text = Format(99000, "currency")

Date variables can hold any date between January 1, 100, through December
31, 9999, as well as any time value. They take 8 bytes, exactly like Double
variables. This isn't a casual resemblance because internally these date/time
values are stored as floating-point numbers, in which the integer part stores the
date information and the decimal part stores the time information. (For
example, 0.5 means 12 A.M., 0.75 means 6 P.M., and so on.) Once you know
how Date variables store their values, you can perform many meaningful math
operations on them. For example, you can truncate date or time information
using the Int function, as follows:
MyVar = Now
' MyVar is a Date variable.
DateVar = Int(MyVar)
' Extract date information.
TimeVar = MyVar - Int(MyVar) ' Extract time information.
You can also add and subtract dates, as you would do with numbers:
MyVar = MyVar + 7
MyVar = MyVar - 365

' Advance one week.


' Go back one (nonleap) year.

The Object Data Type


Visual Basic uses object variables to store reference objects. Note that here we
are talking about storing a reference to an object, not storing an object.
' Examples of generic object variables
Dim frm As Form
' A reference to any form
Dim midfrm As MDIForm
' A reference to any MDI form
Dim ctrl As Control
' A reference to any control
Dim obj As Object
' A reference to any object
' Examples of specific object variables
Dim inv As frmInvoice
' A reference to a specific type of form
Dim txtSalary As TextBox ' A reference to a specific type of control
Dim cust As CCustomer
' A reference to an object defined by a
' class module in the current project
Dim wrk As Excel.Worksheet ' A reference to an external object
The most evident difference when dealing with object variables (as opposed to
regular variables) is that you assign object references to them using the Set
keyword, as in the following code:
Set frm = Form1
Set txtSalary = Text1

The Variant Data Type


Variant variables were introduced in Visual Basic 3, but their internal format
changed in version 4, where their capabilities were greatly enhanced. The
Variant format is defined by OLE, and so it's highly unlikely that it will be
modified again in the future. Variant variables can hold any type of data
described so far, and then some. Variables of this type take 16 bytes, in this
format:
Variant is the default data type for Visual Basic. In other words, if you use a
variable without declaring its type, as in the following line of code:
Dim MyVariable
this will be a Variant variable, unless this line is preceded by a Deftype directive
that sets a different default data type. Likewise, if you use a variable without
first declaring it (and you don't use a Deftype directive), Visual Basic creates a
Variant variable.

The Decimal Data Type


Decimal is a floating-point data type with a higher precision than Double, but it
has a smaller range. In fact, you can store values in the range plus or minus
79,228,162,514,264,337,593,543,950,335 with no decimal point, or plus or
minus 7.9228162514264337593543950335 with 28 places to the right of the
decimal point. The smallest nonzero number is plus or minus
0.0000000000000000000000000001. Decimal is a singular case among the
data types supported by Visual Basic in that you can't explicitly declare a
variable using As Decimal. Instead, you assign a value to a Variant variable
using the CDec conversion function, for example:
Dim v As Variant
v = CDec(Text1.Text)
Once you have assigned a Decimal value to a Variant, you can perform all the
usual math operations. You don't need to ensure that both operands are of
Decimal type because Visual Basic will do the necessary conversions for you.
Decimal is an exception among Variant subtypes in that it exploits all the bytes
in the Variant structure, that is, all 14 bytes that follow the subtype identifier. If
you apply the VarType function to a Variant containing a Decimal value, you get
the return value of 14-vbDecimal.

SUBJECT: VISUAL BASIC 6.0


25/
25/119
Data
Memory
Range
type
(Bytes)
Byte
1
0 to 255
Integer
2
-32,768 to +32767
Long
4
-2147483648 to 2147483647
Single
4
-3.402823-103 to 1.401298-1045 for
negative values
1.4401298-10-45 to 3.402823-1038 for
positive values.
Double
8
-1.79-10 to 4.94-10 for negative values
4.94-10 to 1.79-10 for positive values
Currency 8
-922,337,203,685,477.5808
to
922,337,203,685,477.5807
Boolean 2
True or False
Date
8
January 1, 100 to December 31, 9999
String
1
0 to approx. 2 billion character.
Variant
16
A general-purpose variable that can hold
most other types of variable values.
Object
4
A variable declared as an Object can have
any object reference assigned to it.

Some Data Type Conversion


Conversion
Boolean
Byte
Date
Integer
Long
Single
String
Variant
Currency

Function
Cbool
Cbyte
Cdate
Cint
CLng
CSng
CStr
Cvar
Ccur

Operators

Arithmetic Operators
The arithmetic operators perform mathematical manipulations. There are seven
of them. The first four, listed in Table 4.3, are the common operations that Im
sure you are familiar with.

SUBJECT: VISUAL BASIC 6.0


26/
26/119
The last three arithmetic operators may be more obscure. Integer division,
represented by the \ symbol, divides two numbers and returns an integer result,
discarding any fractional part of the answer. Thus, 7 \ 2 evaluates to 3, as does
6 \ 2. No rounding occurs; any fractional part of the answer is simply discarded.
Thus, both 21 \ 10 and 29 \ 10 evaluate to 2.
The exponentiation operator raises a number to a power. The symbol for this
operation is ^. In Basic, therefore, X ^ Y means the same as the more common
notation XY. If X is negative, then Y must be an integer; otherwise, both X and Y
can be floating point values.
The modulus operator, represented by the keyword Mod, divides two numbers
and returns only the remainder. The expression 7 Mod 2 evaluates to 1, 23
Mod 4 evaluates to 3, and 25 Mod 5 evaluates to 0. Any fractional part of the
answer is truncated, so 23.5 Mod 4 evaluates to 3, not 3.5.

String Manipulation
The only operator that works with string data is called the concatenation
operator, represented by the symbol &. Concatenation simply means to tack one
string onto the end of another. For example, if MyString is a string variable,
then executing the statement
MyString = Visual & Basic
results in the string Visual Basic being stored in the variable. You can also use
the + symbol for string concatenation. It is provided for compatibility with old
Basic programs, but its best to stick with & for new programs.
Table 4.3 Arithmetic operators.
Operation
Addition
Subtraction
Multiplication
Division

Symbol
+
*

Example
2+5
18 - 10
2*5

Result
7
8
10

Operator Precedence
What happens if an expression contains more than one operator? What
difference does it make? An example will illustrate. Consider this expression:
5+3*2
What does it evaluate to? If we perform the addition first, it evaluates to 16 (5
+ 3 = 8, 8 * 2 = 16); but if we perform the multiplication first, the result is 11
(3 * 2 = 6, 5 + 6 = 11). Which is correct? Because of such potentially
ambiguous expressions, Visual Basic includes strict rules of operator

SUBJECT: VISUAL BASIC 6.0


27/
27/119
precedence. This is just a fancy way of determining which operations are
performed first. The precedence of Visual Basics operators is given in Table 4.4.
Operators with low precedence numbers are performed first.
Returning to the original example, we can see that the expression 5 + 3 * 2 will
evaluate to 11, because multiplication has a higher precedence than addition
and thus will be performed first. For operators that have the same precedence
level, such as multiplication and division, the order of execution is always left to
right.
What if the order of execution specified by the operator precedence rules isnt
what you want? Lets say you would like to add variables A and B, then multiply
the sum by variable C. Can this be done? Yes. Parentheses come to the rescue.
By including parentheses in an

Table 4.4 Operator precedence.


Operator
Exponentiation ^
Multiplication (*), division (/)
Integer division (\)
Modulus (MOD)
Addition (+), subtraction (-)
String concatenation (&)

Precedence
1
2
3
4
5
6

expression, you force operators inside parentheses to be evaluated first


regardless of precedence. If you write
A+B*C
the precedence rules will cause the multiplication to be performed first, and the
result will not be what you want. If, however, you write the expression like this
(A + B) * C
the parentheses force the addition to be performed first, and the expression
evaluates properly. You can use as many parentheses in an expression as you
need, as long as they always come in pairs; each left parenthesis must have a
matching right parenthesis. If you create an expression with an unmatched
parenthesis, Visual Basic displays an error message when you try to move the
editing cursor off the line. When parentheses are nested (one set inside another
set), execution starts with the innermost set and proceeds outward.
You can use parentheses in an expression even when they are not needed to
modify the order of operator precedence. Particularly with long, complex
expressions, parentheses can help make the expression easier to read and
understand.

SUBJECT: VISUAL BASIC 6.0

28/
28/119

Comparison Operators
Visual Basic provides a number of operators you can use to construct logical
expressions by asking questions about the data in your programs. Specifically,
these comparison operators perform comparisons between expressions,
returning a value of True or False, depending on the result of the comparison.
Table 4.5 lists the comparison operators.
We can see that if X is equal to 10 and Y is equal to 5, then the expression X <
Y will evaluate as False and X <> Y will evaluate as True. Assuming both Q and
Z have been declared as type Integer, we can use the numerical value of a
logical expression like this
Q=X<Y
Z = X <> Y
which would result in the variable Q having the value 0 and Z having the value 1. More often, however, logical expressions are used in program control, as
youll see soon. But first, we need to take a look at how to combine two or more
logical expressions to arrive at a single True/False answer.

Table 4.5 Comparison operators.


Operator
=
>

Comparison
Equal to
Greater than

<
>=

Less than
X
Greater than or X
equal to
Less than or equal X
to
Not equal to
X

<=
<>

Example
X=Y
X>Y
<Y
>= Y
<= Y
<> Y

Meaning
Is X equal to Y?
Is X greater than
Y?
Is X less than Y?
Is X greater than or
equal to Y?
Is X less than or
equal to Y?
Is X not equal to Y?

Logical Operators
The logical operators work to combine two or more logical expressions into a
single True or False answer. Why would we want to do this? Heres an example
from everyday life. You receive a call inviting you to join a group of friends for
dinner. If Mary is coming along, youd like to go, because youre a bit sweet on
her; otherwise, youll pass. This is a single logical condition, and easy to
understand. Now, assume for a moment that you also like Helen; if shes
coming with the group, youd also like to go. But if both Mary and Helen are
coming, the situation will get a bit too complicated, so you again will pass. In

SUBJECT: VISUAL BASIC 6.0


29/
29/119
this situation, we have two True/False questions (Is Mary coming? Is Helen
coming?) that you need to combine in some way before answering the
True/False question: Are you going?
Similar situations arise in computer programming. For example, you need an
answer to the question: Are X and Y both greater than aero? Heres where the
logical operators come in, letting you combine and manipulate logical
expressions to get the answer you need. The six logical operators (shown in
Table 4.6) are each designated by a keyword. As you review this table, assume
that X and Y are both logical expressions.
Now we can cast the earlier question using the comparison operators and the
logical operators. The expression
(X > 0) And (Y > 0)
will evaluate as True if, and only if, both X and Y are greater than zero.
Likewise, if you need to know whether at least one of these two variables is
greater than zero, you would write:
(X > 0) Or (Y > 0)
Table 4.6 Logical operators.
Operator
And

Example
X And Y

Or

X Or Y

Xor (exclusive Or)

X Xor Y

Eqv (Equivalence)

X Eqv Y

Imp (Implication)

X Imp Y

Not

Not X

Evaluation
True if both X and Y are True;
False otherwise
True if X or Y, or both of them,
are True; False only if both X
and Y are False
True if X and Y are different
(one True and the other False);
False if both are True or both
are False
True if X and Y are the same
(both True or both False); False
otherwise
False only if X is True and Y is
False; True otherwise
True if X is False, False if X is
True

Of course, you can use the comparison and logical operators to ask questions
about object properties, too. Lets say you have two Check Box controls on a
form and want to determine if one or both of them are checked. Heres the
expression to do so:

SUBJECT: VISUAL BASIC 6.0


30/
30/119
(Check1.Value = True) Or (Check2.Value = True)
I have been talking about comparison and logical operators for a while now, but
I havent really demonstrated how they can be useful. Dont worry; thats our
next topic: how to use logical expressions in conjunction with Basics decision
and loop structures to control program execution.
Operator Precedence
 Exponents (^)
 Negation (-)
 Multiplication (*)
 Division (/ or \)
 Module (MOD)
 Addition (+)
 Subtraction (-)
 String Concatenation (&)
 Equality (=)
 Inequality (<>)
 Less than (<)
 Greater then (>)
 Less than or equal to (<=)
 Greater than or equal to (>=)
 Negation (NOT)
 Conjunction (AND)
 Disjunction (OR)

LECTURE 5
Library Functions
Library Functions are the in-built functions those are available with VB type
specification that we can use in different forms by writing the proper syntax
they are of different types for e.g.
InputBox: The input box, function display a model dialog box that asks the
uses to enter some data. The dialog box contains a message with two buttons
Ok and Cancel.
E.g. I = Input Box ( Enter a Date, Date Demo)
Msgbox: The Msgbox function is used to display a dialog box, it contains
message with Ok button only (by default). You can also set required Icons
(vbCritical, vbInformation etc) and Buttons (vbYesNo, vbOkCancel etc).

SUBJECT: VISUAL BASIC 6.0


31/
31/119
E.g. I = Msgbox (Invalid Date, vbCritical+vbYesNo)
Example: Creating simple applications like sum, subtract two no's etc.
Follow the instructions Add new form to menu at the end of Activity 1 to create
a new form with a menu heading on the main form. Call this Message and
Input Boxes
Make the Form.Caption = Message and Input Boxes
Put a label on the top of the form Computer Conversation. Underneath
have a
command button with the caption Talk to me! Name the command
button cmdTalk.
Double click the command button to add the following code sequence.

SUBJECT: VISUAL BASIC 6.0


32/
32/119
vbAbortRetryIgnore 2
Displays the Abort, Retry and
Ignore buttons.
vbYesNoCancel
3
Displays the Yes, No and Cancel
buttons.
vbYesNo
4
Displays the Yes and No buttons.
vbRetryCancel
5
Displays the Retry and Cancel
buttons.

Icons in Message Boxes


Named Literal

Value Description

VbCritical

16

Displays Critical Message icon

Private Sub cmdTalk_Click()

VbQuestion

32

Displays Warning Query icon.

Dim strQuestion As String


Dim intAnswer As Integer
First you must declare your variables
Then use the input and message box functions
strQuestion = InputBox(Type in your name!, Ebeneezer)
intAnswer = MsgBox(Hello there & strQuestion, vbOKCancel, Chat)

VbExclamation
VbInformation

48
64

VbSystemModal

4096

Displays Warning Message icon.


Displays
Information
message
icon.
Displays a System Modal dialog
box. The user must acknowledge
this box before doing anything
else.

End Sub
Add a return button, called cmdBack as you did in the ColourChanger,
using the code
Private Sub cmdBack_Click()
Form1.Show
End Sub

Remarks are added in code to explain the purpose of a section of code or to add
information for code maintenance. If Rem or is placed in front of the remark,
that line
of code is ignored completely.

Run your program using <F5>. Dont forget to save your work.

LECTURE 6

Here are some handy literals (values that dont change). You dont have to learn
them
as the help prompt supplies a drop down list as you start to type.

Decision Control Structure


Visual Basic procedures can test conditions and then, depending on the results
of that test, perform different operations. The decision structures that Visual
Basic supports include:

Buttons in Message Boxes


Named Literal
vbOKOnly
vbOKCancel

Value Description
0
Displays the OK button
1
Displays the OK button and Cancel
buttons

 If-----Then----End If
 If-----Then---Else---End If
 Select Case

SUBJECT: VISUAL BASIC 6.0


33/
33/119
Visual Basics decision structures control program execution based on whether
certain logical conditions are met. In other words, program statements are
either executed or not executed, based on the evaluation of logical expressions.
These logical expressions typically evaluate the state of program data or user
input, so the execution of the program can be controlled according to the
specific needs of the application.
If...Then...Else
The If structure executes a block of one or more statements only if a specified
logical expression evaluates as True. Optionally, you can include a second block
of statements that is executed only if the logical expression is False. An If
structure has the following form (in these examples, X stands for any logical
expression):
If X Then
...
Statements to be executed if X is TRUE go here.
...
Else
...
Statements to be executed if X is FALSE go here.
...
End If
The Else keyword and the block of statements between it and the End If
keyword are optional. If no statements are to be executed when X is False, you
can write as follows:
If X Then
...
Statements to be executed if X is TRUE go here.
...
End If
If your blocks of statements are only single statements, you can use the concise
single-line form of the If structure:
If X then Statement1 Else Statement2
For more involved situations, you can include the ElseIf keyword to create what
are effectively nested If structures:
If X Then
...
Statements to be executed if X is TRUE go here.
...
ElseIf Y Then
...
Statements to be executed if Y is TRUE go here.
...
Else

SUBJECT: VISUAL BASIC 6.0


34/
34/119
...
Statements to be executed if both X and Y are FALSE go here.
...
End If
You can have as many ElseIf statements as you like. Keep in mind, however,
that, at most, one of the blocks of statements in an If structure will be
executed. In the preceding example, if both X and Y are True, only the
statements associated with the X condition are executed. The rule is that only
the statements associated with the first True condition are executed. Note,
however, that for situations that would require more than one or two ElseIf
clauses, you are usually better off using the Select Case structure, which Ill
cover next.

You might have noticed the indentation style in the previous code
samples; within each block, all statements are indented with respect to
the statements that mark the beginning and the end of the block. This is
not required by Visual Basic, but in my opinion it makes the code more
readable.
And heres an example showing how to use the various parts of this
popular statement:
Dim intInput
intInput = -1
While intInput < 0
intInput = InputBox("Enter a positive number")
Wend
If intInput = 1 Then
MsgBox ("Thank you.")
ElseIf intInput = 2 Then
MsgBox ("That's fine.")
ElseIf intInput >= 3 Then
MsgBox ("Too big.")
End If

LECTURE 7
Select Case Statement
Select Case Structure is an alternative of If----Then----Else End If, for
selectively executing a single block of statements from among multiple blocks of

SUBJECT: VISUAL BASIC 6.0


35/
35/119
statements. The select case statement identifies the variable to be evaluated
and then a series of case statement specify the possible values.
You will find that the Select Case structure is more appropriate than the If
structure when you have more than a couple of conditions to be tested:
Select Case TestExpression
Case Comparison1
...
Block1
...
Case Comparison2
...
Block2
...
Case Else
...
ElseBlock
...
End Select
TestExpression is any numeric or string expression. Select Case goes through
the list of Case statements, comparing TestExpression with each Comparison
until a match is found. At that point, the statements in the associated block are
executed. If no match is found, the statements associated with the optional
Case Else statement are executed. If there is no Case Else and no match, none
of the statements is executed. The number of Case statements allowed in a
Select Case structure has no limit.
In the simplest situation, each Comparison is a numeric or string expression
against which TestExpression is compared for equality. You can also use the To
keyword to check TestExpression against a range of values, and the Is keyword
in conjunction with one of the comparison operators to make a relational
comparison. Thus, if you want a match when TestExpression is between 1 and
5, you would write
Case 1 To 5
and if you want a match when TestExpression is greater than 10, you would
write:
Case Is > 10
You can use multiple Comparison expressions that are associated with one Case
statement by separating them with commas. For example, heres a Case
statement that would match TestExpression if it is equal to -1 or -2, between 8
and 12, or greater than 100:
Case -1, -2, 8 To 12, Is > 100

SUBJECT: VISUAL BASIC 6.0


Syntax
Select Case TestExpr
Case Expr1
Statements
Case Expr2
Statements
Case Expr3
Statements
End Select
Examples
Select Case Index
Case 0
Statements
Case 1
Statements
Case 2
Statements
End Select

Select Case Index


Case 1 to 10
Statements
Case 11 to 50
Statements
Case 51 to 100
Statements
End Select

36/
36/119

Select Case String


Case
apple,
mango
Statements
Case crow
Statements
Case
A,B,C,D
Statements
End Select

Example
Dim intInput
intInput = -1
While intInput < 0
intInput = InputBox("Enter a positive number")
Wend
Const intMax = 100
Select Case intInput
Case 1:
MsgBox ("Thank you.")
Case 2:
MsgBox ("That's fine.")
Case 3:
MsgBox ("Your input is getting pretty big now...")
Case 4 To 10:
MsgBox ("You are approaching the maximum!")
Case Is > intMax:
MsgBox ("Too big, sorry.")
Case Else:

SUBJECT: VISUAL BASIC 6.0


MsgBox ("Please try again.")
End Select

37/
37/119

LECTURE 8
CheckBox Controls
CheckBox controls are useful when you want to offer your users a yes or no,
true or false choice. Anytime you click on this control, it toggles between the yes
state and the no state. This control can also be grayed when the state of the
CheckBox is unavailable, but you must manage that state through code.
When you place a CheckBox control on a form, all you have to do, usually, is set
its Caption property to a descriptive string. You might sometimes want to move
the little check box to the right of its caption, which you do by setting the
Alignment property to 1-Right Justify, but in most cases the default setting is
OK. If you want to display the control in a checked state, you set its Value
property to 1-Checked right in the Properties window, and you set a grayed
state with 2-Grayed.
The only important event for CheckBox controls is the Click event, which fires
when either the user or the code changes the state of the control. In many
cases, you don't need to write code to handle this event. Instead, you just query
the control's Value property when your code needs to process user choices. You
usually write code in a CheckBox control's Click event when it affects the state
of other controls. For example, if the user clears a check box, you might need to
disable one or more controls on the form and reenable them when the user
clicks on the check box again. This is how you usually do it (here I grouped all
the relevant controls in one frame named Frame1):
Private Sub Check1_Click()
Frame1.Enabled = (Check1.Value = vbChecked)
End Sub
Note that Value is the default property for CheckBox controls, so you can omit it
in code. I suggest that you not do that, however, because it would reduce the
readability of your code.

OptionButton Controls
OptionButton controls are also known as radio buttons because of their shape.
You always use OptionButton controls in a group of two or more because their
purpose is to offer a number of mutually exclusive choices. Anytime you click on
a button in the group, it switches to a selected state and all the other controls in
the group become unselected.

SUBJECT: VISUAL BASIC 6.0


38/
38/119
Preliminary operations for an OptionButton control are similar to those already
described for CheckBox controls. You set an OptionButton control's Caption
property to a meaningful string, and if you want you can change its Alignment
property to make the control right aligned. If the control is the one in its group
that's in the selected state, you also set its Valueproperty to True. (The
OptionButton's Value property is a Boolean value because only two states are
possible.) Value is the default property for this control.
At run time, you typically query the control's Value property to learn which
button in its group has been selected. Let's say you have three OptionButton
controls, named optWeekly, optMonthly, and optYearly. You can test which one
has been selected by the user as follows:
If optWeekly.Value Then
' User prefers weekly frequency.
ElseIf optMonthly.Value Then
' User prefers monthly frequency.
ElseIf optYearly.Value Then
' User prefers yearly frequency.
End If
Strictly speaking, you can avoid the test for the last OptionButton control in its
group because all choices are supposed to be mutually exclusive. But the
approach I just showed you increases the code's readability.
A group of OptionButton controls is often hosted in a Frame control. This is
necessary when there are other groups of OptionButton controls on the form. As
far as Visual Basic is concerned, all the OptionButton controls on a form's
surface belong to the same group of mutually exclusive selections, even if the
controls are placed at the opposite corners of the window. The only way to tell
Visual Basic which controls belong to which group is by gathering them inside a
Frame control. Actually, you can group your controls within any control

Frame Controls
Frame controls are similar to Label controls in that they can serve as captions
for those controls that don't have their own. Moreover, Frame controls can also
(and often do) behave as containers and host other controls. In most cases, you
only need to drop a Frame control on a form and set its Caption property. If you
want to create a borderless frame, you can set its BorderStyle property to 0None.
Controls that are contained in the Frame control are said to be child controls.
Moving a control at design time over a Frame controlor over any other
container, for that matterdoesn't automatically make that control a child of the
Frame control. After you create a Frame control, you can create a child control
by selecting the child control's icon in the Toolbox and drawing a new instance
inside the Frame's border. Alternatively, to make an existing control a child of a
Frame control, you must select the control, press Ctrl+X to cut it to the

SUBJECT: VISUAL BASIC 6.0


39/
39/119
Clipboard, select the Frame control, and press Ctrl+V to paste the control inside
the Frame. If you don't follow this procedure and you simply move the control
over the Frame, the two controls remain completely independent of each other,
even if the other control appears in front of the Frame control.
Frame controls, like all container controls, have two interesting features. If you
move a Frame control, all the child controls go with it. If you make a container
control disabled or invisible, all its child controls also become disabled or
invisible. You can exploit these features to quickly change the state of a group
of related controls.

LECTURE 9
ListBox Controls
Once you have dropped a ListBox control on a form's surface, you might need to
assign a few properties. For example, you set the Sorted attribute to True to
create ListBox controls that automatically sort their items in alphabetical order.
By acting on the Columns property, you create a different type of list box, with
several columns and a horizontal scroll bar. instead of the default list box with a
single column and a vertical scroll bar along its right border. You can make
assignments for both these properties only at design time, and you can't change
the style of the ListBox control while the program is running.
Both ListBox and ComboBox controls expose the AddItem method, which lets
you add items when the program is executing. You usually use this method in
the Form_Load event procedure:
Private Sub Form_Load()
List1.AddItem "First"
List1.AddItem "Second"
List1.AddItem "Third"
End Sub
Now we can refer to the items in the list box by index using the List property as
List(0), List(1), and so on. When the user clicks the list, causing a Click
event, we can display the item number the user clicked with the ListIndex
property, which holds the index of the currently selected item:
Private Sub List1_Click()
MsgBox "You clicked item " & Str(List1.ListIndex)
End Sub
You can also change an items index with its Index property like this:
List(index).Index = 3

Multiple-selection ListBox controls

SUBJECT: VISUAL BASIC 6.0

40/
40/119

The ListBox control is even more flexible than I've shown so far because it lets
users select multiple items at the same time. To enable this feature, you assign
the MultiSelect property the values 1-Simple or 2-Extended. In the former case,
you can select and deselect individual items only by using the Spacebar or the
mouse. In extended selection, you can also use the Shift key to select ranges of
items. Most popular Windows programs use extended selection exclusively, so
you shouldn't use the value 1-Simple unless you have a good reason to do so.
The MultiSelect property can't be changed when the program is running, so this
is a design-time decision.
If your list box is a multiselect box, you can determine which items the user has
selected by using the Selected property this way:
For intLoopIndex = 0 To List1.ListCount - 1
If List1.Selected(intLoopIndex) Then
...
End If
Next intLoopIndex

Properties of ListBox
List: Returns/Sets the items contained in a control & list portion, used to enter
the item at a design time.
List Count: Returns the total no. Of items present in the combo box.
List index: Returns the index of the currently selected item in the control.
New index: Returns the index of the item most recently added to control.
Selected: Returns the status of an item whether it is selected or not.
Multiselect: It allows the user to select more than one value from the list.
Columns: Sets a value that determines whether a list box. Scrolls vertically in a
single column (value of 0) or horizontally in shaping columns (values great, than
0).

Events of ListBox
Click: Generalized the user presses and then releases a mouse button on
control.
DblClick: It occurs when the user presses and releases a mouse button and
then presses and releases it again over an object,

Methods of ListBox
AddItem: Used to add an item to Combo Box.
Clear: Clear the contents of the Combo Box.
RemoveItem: Removes an item from a Combo Box by using its index no.

SUBJECT: VISUAL BASIC 6.0

41/
41/119

Combo Box
ComboBox controls are very similar to ListBox controls, so much of what I have
explained so far applies to them as well. More precisely, you can create
ComboBox controls that automatically sort their items using the Sorted
property, you can add items at design time using the List item in the Properties
window, and you can set a ComboBox control's IntegralHeight property as your
user interface dictates. Most run-time methods are common to both kinds of
controls too, including AddItem, RemoveItem, and Clear, as are the ListCount,
ListIndex, List, ItemData, TopIndex, and NewIndex properties and the Click,
DblClick, and Scroll events. ComboBox controls don't support multiple columns
and multiple selections, so you don't have to deal with the Column, MultiSelect,
Select, and SelCount properties and the ItemCheck event.
The ComboBox control is a sort of mixture between a ListBox and a TextBox
control in that it also includes several properties and events that are more
typical of the latter, such as the SelStart, SelLength, SelText, and Locked
properties and the KeyDown, KeyPress, and KeyUp events. I've already
explained many things that you can do with these properties and won't repeat
myself here. Suffice it to say that you can apply to ComboBox controls most of
the techniques that are valid for TextBox controls, including automatic
formatting and deformatting of data in GotFocus and LostFocus event
procedures and validation in Validate event procedures.
The most characteristic ComboBox control property is Style, which lets you pick
one among the three styles available, as you can see in Figure 3-11. When you
set Style = 0-DropDown Combo, what you get is the classic combo; you can
enter a value in the edit area or select one from the drop-down list. The setting
Style = 1-Simple Combo is similar, but the list area is always visible so that in
this case you really have a compounded TextBox plus ListBox control. By
default, Visual Basic creates a control that's only tall enough to show the edit
area, and you must resize it to make the list portion visible. Finally, Style = 2Dropdown List suppresses the edit area and gives you only a drop-down list to
choose from
When you have a ComboBox control with Style = 0-Dropdown Combo or 2Dropdown List, you can learn when the user is opening the list portion by
trapping the DropDown event. For example, you can fill the list area just one
instant before the user sees it (a sort of just-in-time data loading):
Heres an example; in this case, we add four items to a combo boxs list:
Private Sub Form_Load()
Combo1.AddItem ("Item 0")
Combo1.AddItem ("Item 1")
Combo1.AddItem ("Item 2")
Combo1.AddItem ("Item 3")

SUBJECT: VISUAL BASIC 6.0


End Sub

42/
42/119

Private Sub Combo1_DropDown()


Dim i As Integer
' Do it only once.
If Combo1.ListCount = 0 Then
For i = 1 To 100
Combo3.AddItem "Item #" & i
Next
End If
End Sub

Properties of ComBox:
Style: Returns or sets a value that specifies the behavior and/or appearance of
the control.
List: Returns/Sets the items contained in a control & list portion, used to enter
the item at a design time.
List Count: Returns the total no. Of items present in the combo box.
List index: Returns the index of the currently selected item in the control.
New index: Returns the index of the item most recently added to control.
Text: Returns/Sets the text contained in the control.

Events of ComboBox
Click: Generalized the user presses and then releases a mouse button on
control.
DblClick: It occurs when the user presses and releases a mouse button and
then presses and releases it again over an object,

Methods of ComboBox
AddItem: Used to add an item to Combo Box.
Clear: Clear the contents of the Combo Box.
RemoveItem: Removes an item from a Combo Box by using its index no.

LECTURE 10
ScrollBars

SUBJECT: VISUAL BASIC 6.0


43/
43/119
The HScrollBar and the VScrollBar controls are perfectly identical, apart from
their different orientation. After you place an instance of such a control on a
form, you have to worry about only a few properties: Min and Max represent the
valid range of values, SmallChange is the variation in value you get when
clicking on the scroll bar's arrows, and LargeChange is the variation you get
when you click on either side of the scroll bar indicator. The default initial value
for those two properties is 1, but you'll probably have to change LargeChange to
a higher value. For example, if you have a scroll bar that lets you browse a
portion of text, SmallChange should be 1 (you scroll one line at a time) and
LargeChange should be set to match the number of visible text lines in the
window.
The most important run-time property is Value, which always returns the
relative position of the indicator on the scroll bar. By default, the Min value
corresponds to the leftmost or upper end of the control:
' Move the indicator near the top (or left) arrow.
VScroll1.Value = VScroll1.Min
' Move the indicator near the bottom (or right) arrow.
VScroll1.Value = VScroll1.Max
There are two key events for scrollbar controls: the Change event fires when
you click on the scroll bar arrows or when you drag the indicator; the Scroll
event fires while you drag the indicator. The reason for these two distinct
possibilities is mostly historical. First versions of Visual Basic supported only the
Change event, and when developers realized that it wasn't possible to have
continuous feedback when users dragged the indicator, Microsoft engineers
added a new event instead of extending the Change event. In this way, old
applications could be recompiled without unexpected changes in their behavior.
At any rate, this means that you must often trap two distinct events:
' Show the current scroll bar's value.
Private VScroll1_Change()
Label1.Caption = VScroll1.Value
End Sub
Private VScroll1_Scroll()
Label1.Caption = VScroll1.Value
End Sub

SUBJECT: VISUAL BASIC 6.0


44/
44/119
meaningful properties: Interval and Enabled. Interval stands for the number of
milliseconds between subsequent pulses (Timer events), while Enabled lets you
activate or deactivate events. When you place the Timer control on a form, its
Interval is 0, which means no events. Therefore, remember to set this property
to a suitable value in the Properties window or in the Form_Load event
procedure:
Private Sub Form_Load()
Timer1.Interval = 500
End Sub

' Fire two Timer events per second.

Timer controls let you write interesting programs with just a few lines of code.
The typical (and abused) example is a digital clock. Just to make things a bit
more compelling, I added flashing colons:
Private Sub Timer1_Timer()
Dim strTime As String
strTime = Time$
If Mid$(lblClock.Caption, 3, 1) = ":" Then
Mid$(strTime, 3, 1)= " "
Mid$(strTime, 6, 1) = " "
End If
lblClock.Caption = strTime
End Sub

Shape and Line


The Line Control
The Line control is a decorative control whose only purpose is let you draw one
or more straight lines at design time, instead of displaying them using a Line
graphical method at run time. This control exposes a few properties whose
meaning should sound familiar to you by now: BorderColor (the color of the
line), BorderStyle (the same as a form's DrawStyle property), BorderWidth (the
same as a form's DrawWidth property), and DrawMode. While the Line control is
handy, remember that using a Line method at run time is usually better in
terms of performance.

The Shape Control

The Timer Control


A Timer control is invisible at run time, and its purpose is to send a periodic
pulse to the current application. You can trap this pulse by writing code in the
Timer's Timer event procedure and take advantage of it to execute a task in the
background or to monitor a user's actions. This control exposes only two

In a sense, the Shape control is an extension of the Line control. It can display
six basic shapes: Rectangle, Square, Oval, Circle, Rounded Rectangle, and
Rounded Square. It supports all the Line control's properties and a few more:
BorderStyle (0-Transparent, 1-Solid), FillColor, and FillStyle (the same as a
form's properties with the same names). The same performance considerations
I pointed out for the Line control apply to the Shape control.

SUBJECT: VISUAL BASIC 6.0

45/
45/119

LECTURE 11
Iteration Control Structure (Loops)
Loops are used to perform repetitive tasks. We places our code in the loop and if
repeats it till some condition.

Loop Structures
Youve seen that Basics decision structures determine whether a block of
statements is executed. In contrast, Basics loop structures control how many
times a block of statements is executed. You can accomplish looping in one of
two ways: by executing a block of statements a fixed number of times or by
executing the block repeatedly until a specified condition is met.
For...Next
In its most common use, the For...Next loop executes a block of statements a
fixed number of times:
For Counter = Start To Stop
...
statement block
...
Next Counter
Counter is a numeric variable that can be any type, although you would
generally use type Integer unless you have a specific reason to use another
type. Start and Stop are the values that specify the start and stop of the loop;
they can be any numeric expression. A For...Next loop begins by setting Counter
equal to Start. It then follows these steps:
1. Counter is compared with Stop. If Counter is greater than Stop, execution
passes to the first statement after the ForNext loop.
2. The statements in the loop are executed.
3. Counter is incremented by 1.
4. Return to Step 1.
Note that if Stop is equal to Start, the loop executes only once; if Stop is less
than Start, it does not execute at all.
Heres an example of a For...Next loop that will execute the number of times
specified by the variable X.
For Count = 1 to X
...
Next X
You are not limited to starting the loop at 1, of course. You can also use the
Step keyword to specify that the Counter variable be incremented by a value

SUBJECT: VISUAL BASIC 6.0


46/
46/119
other than 1 with each cycle of the loop. Heres a loop that will execute four
times, with the Counter variable taking the values 4, 7, 10, and 13:
For I = 4 To 13 Step 3
...
Next I
You can use negative Step values to count backward, which, of course, requires
that the Stop value be smaller than Start. You can also use fractional values as
long as the Counter variable is a floating point type. The following loop will
count backward from 4 to 1 by increments of 0.25 (4, 3.75, 3.5, ... , 1.25, 1):
For I = 4 To 1 Step -0.25
...
Next I
If you want to terminate a loop earlythat is, before the Counter variable
exceeds Stopyou can use the Exit For statement. This is an extremely useful
statement, because it lets you specify a variety of conditions that will terminate
the loop in addition to the loops own count programming. Heres a loop that will
execute 10 times or until the variable X is less than 0:
For I = 1 to 10
...
If X < 0 Then Exit For
...
Next I
Strictly speaking, you do not have to include the name of the Counter variable
in the Next statement. Basic will automatically associate each Next statement
with the immediately preceding For statement. I suggest, however, that you
develop the habit of always including the Counter variable name with Next, to
improve readability of the code.

Do...Loop
The Do...Loop structure is the most flexible of Basics loops. It allows the loop to
execute until a specified condition is either True or False, and it allows the
condition to be evaluated either at the start or the end of the loop. In its
simplest form, a Do...Loop executes as long as a condition is True:
Do While Condition
...
statement block
...
Loop
Condition is any logical expression. When execution first reaches the Do
statement, Condition is evaluated. If it is False, execution passes to the
statement following the Loop statement. If it is True, the block of statements is
executed, execution returns to the Do statement, and Condition is evaluated
again. You can also replace the While with the Until keyword to continue
execution for as long as Condition is False, as shown here:

SUBJECT: VISUAL BASIC 6.0

47/
47/119

Do Until Condition
...
statement block
...
Loop
Both of the previous examples perform the comparison at the start of the loop,
which means it is possible for the statement block not to be executedeven
once. For example, if Condition is False to begin with, a Do While
Condition...Loop will not execute even once. If you want to be sure the loop
executes at least once, you can place the Condition at the end of the loop. As
before, you can use either the While or the Until keyword:
Do
...
statement block
...
Loop While Condition
Do
...
statement block
...
Loop Until Condition
To terminate the loop early, use Exit Do. Heres a loop that will execute until Y is
greater than zero or X is less than zero:
Do
...
If X < 0 Then Exit Do
...
Loop Until Y > 0
You may be thinking that we could have obtained the same result by writing the
loop like this:
Do
...
Loop Until Y > 0 Or X < 0
You are correct, but a subtle difference exists between these two loops. In the
first example, the statements between the If X < 0 statement and the Loop
statement are not executed during the last loop iteration, when X becomes less
than zero. In the second example, all of the statements in the loop are executed
during the last execution.

While...Wend
The While...Wend loop executes a block of statements as long as a specified
Condition is True, but it is not nearly as flexible as Do...Loop. In fact, anything

SUBJECT: VISUAL BASIC 6.0


48/
48/119
that While...Wend can do, Do...Loop can also accomplish. You may find
While...Wend in older Basic programs, simply because earlier versions of Basic
did not support Do...Loop.
Heres the way to write a While...Wend loop:
While Condition
...
statement block
...
Wend
You can write all of your Basic programs without ever needing a While...Wend
loop. Take a look at the following variant of Do...Loop, which does exactly the
same thing as a While...Wend loop:
Do While Condition
...
statement block
...
Loop
Because of its added flexibility, I recommend that you use Do...Loop rather than
the While...Wend structure found in older programs.

Nested And Infinite Loops


A nested loop is a loop contained within another loop. There is no limit to
nesting of loops in Visual Basic, although nesting beyond four or five levels is
rarely necessary or even advisable. If your program seems to need such deep
nesting, you should probably reexamine its structure to see if you can
accomplish the same task more simply. The only restriction on nesting loops is
that each inner loop must be enclosed entirely within the outer loop. The
following example is illegal, because the For...Next loop is not contained entirely
within the Do...Loop loop:
Do While X > 0
For I = 1 to 10
...
Loop
Next I
The next example, however, is okay:
Do While X > 0
For I = 1 to 10
...
Next I
Loop
An infinite loop is one that executes forever (or until you halt the program).
Clearly, if a loops terminating condition is never met, it will loop indefinitely.
This situation can arise from faulty program logic or from unexpected user input.

SUBJECT: VISUAL BASIC 6.0


49/
49/119
Keep a sharp eye out for this sort of problem. If your program seems to hang
during execution, you might want to examine your loops.

WithEnd With
The WithEnd With statement provides a convenient shorthand when you want
to access more than one property or method of an object. The syntax is:
With object
.Property1 = ...
.Property2 = ...
.Method1
End With
The preceding code has the same effect as the following:
object.Property1 = ...
object.Property2 = ...
object.Method1
When used simply as a shorthand, the WithEnd With statement is at best a
minor convenience. It is more useful when used in procedures that take an
object as a parameter. Here, for example, is a procedure that will change
several font-related properties of any object that is passed to it:
Public Sub ChangeFont(ob As Object)
With ob
.Font.Bold = True
.Font.Italic = True
.ForeColor = RGB(255, 0, 0)
End With
End Sub

LECTURE 12
Explain Some Built-In Functions
1. Numeric Functions: Abs(), Round(), Sqrt(), Rnd, Int(), Fix() etc.
2. String Functions: Chr(), Len(), Str(), Lcase(), Ucase(), strReverse(),
Ltrim(), Rtrim(), Trim(), Left(), Right(), Mid() etc.
3. Date/Time Functions: Month(), Day(), Year() etc.
4. Also explain some other important functions like Format(), RGB(),
QBColor() etc.

LECTURE 13
DriveListBox, DirListBox, and FileListBox Controls

SUBJECT: VISUAL BASIC 6.0

50/
50/119

In a nutshell, the DriveListBox control is a combobox-like control that's


automatically filled with your drive's letters and volume labels. The DirListBox is
a special list box that displays a directory tree. The FileListBox control is a
special-purpose ListBox control that displays all the files in a given directory,
optionally filtering them based on their names, extensions, and attributes.
These controls often work together on the same form; when the user selects a
drive in a DriveListBox, the DirListBox control is updated to show the directory
tree on that drive. When the user selects a path in the DirListBox control, the
FileListBox control is filled with the list of files in that directory.
After you place a DriveListBox and a DirListBox control on a form's surface, you
usually don't have to set any of their properties; in fact, these controls don't
expose any special property, not in the Properties window at least. The
FileListBox control, on the other hand, exposes one property that you can set at
design timethe Pattern property. This property indicates which files are to be
shown in the list area: Its default value is *.* (all files), but you can enter
whatever specification you need, and you can also enter multiple specifications
using the semicolon as a separator. You can also set this property at run time,
as in the following line of code:
File1.Pattern = "*.txt;*.doc;*.rtf"
After these preliminary steps, you're ready to set in motion the chain of events.
When the user selects a new drive in the DriveListBox control, it fires a Change
event and returns the drive letter (and volume label) in its Drive property. You
trap this event and set the DirListBox control's Path property to point to the root
directory of the selected drive:
Private Sub Drive1_Change()
' The Drive property also returns the volume label, so trim it.
Dir1.Path = Left$(Drive1.Drive, 1) & ":\"
End Sub
When the user double-clicks on a directory name, the DirListBox control raises a
Change event; you trap this event to set the FileListBox's Path property
accordingly:
Private Sub Dir1_Change()
File1.Path = Dir1.Path
End Sub
Finally, when the user clicks on a file in the FileListBox control, a Click event is
fired (as if it were a regular ListBox control), and you can query its Filename
property to learn which file has been selected. Note how you build the complete
path:

SUBJECT: VISUAL BASIC 6.0

51/
51/119

Filename = File1.Path
If Right$(Filename, 1) <> "\" Then Filename = Filename & "\"
Filename = Filename & File1.Filename
The DirListBox and FileListBox controls support most of the properties typical of
the control they derive fromthe ListBox controlincluding the ListCount and
the ListIndex properties and the Scroll event. The FileListBox control supports
multiple selection; hence you can set its MultiSelect property in the Properties
window and query the SelCount and Selected properties at run time.

SUBJECT: VISUAL BASIC 6.0

52/
52/119

Loading images
Once you place a PictureBox on a form, you might want to load an image in it,
which you do by setting the Picture property in the Properties window. You can
load images in many different graphic formats, including bitmaps (BMP), device
independent bitmaps (DIB), metafiles (WMF), enhanced metafiles (EMF), GIF
and JPEG compressed files, and icons (ICO and CUR). You can decide whether a
control should display a border, resetting the BorderStyle to 0-None if
necessary. Another property that comes handy in this phase is AutoSize: Set it
to True and let the control automatically resize itself to fit the assigned image.
You might want to set the Align property of a PictureBox control to something
other than the 0-None value. By doing that, you attach the control to one of the
four form borders and have Visual Basic automatically move and resize the
PictureBox control when the form is resized. PictureBox controls expose a Resize
event, so you can trap it if you need to move and resize its child controls too.
You can do more interesting things at run time. To begin with, you can
programmatically load any image in the control using the LoadPicture function:
Picture1.Picture = LoadPicture("c:\windows\setup.bmp")
and you can clear the current image using either one of the following
statements:
' These are equivalent.
Picture1.Picture = LoadPicture("")
Set Picture1.Picture = Nothing

Figure 3-16. A minimal but completely functional Image Preview utility that
also supports bitmap tiling.

PictureBox and Image Controls


Both PictureBox and Image controls let you display an image, so let's compare
them and see when it makes sense to choose one or the other.

The PictureBox Control


PictureBox controls are among the most powerful and complex items in the
Visual Basic Toolbox window. In a sense, these controls are more similar to
forms than to other controls. For example, PictureBox controls support all the
properties related to graphic output, including AutoRedraw, ClipControls, HasDC,
FontTransparent, CurrentX, CurrentY, and all the Drawxxxx, Fillxxxx, and
Scalexxxx properties. PictureBox controls also support all graphic methods, such
as Cls, PSet, Point, Line, and Circle and conversion methods, such as ScaleX,
ScaleY, TextWidth, and TextHeight

The Image Control


Image controls are far less complex than PictureBox controls. They don't
support graphical methods or the AutoRedraw and the ClipControls properties,
and they can't work as containers, just to hint at their biggest limitations.
Nevertheless, you should always strive to use Image controls instead of
PictureBox controls because they load faster and consume less memory and
system resources.
When you're working with an Image control, you typically load a bitmap into its
Picture property either at design time or at run time using the LoadPicture
function. Image controls don't expose the AutoSize property because by default
they resize to display the contained image (as it happens with PictureBox
controls set at AutoSize = True). On the other hand, Image controls support a
Stretch property that, if True, resizes the image (distorting it if necessary) to fit
the control. In a sense, the Stretch property somewhat remedies the lack of the
PaintPicture method for this control. In fact, you can zoom in to or reduce an
image by loading it in an Image control and then setting its Stretch property to
True to change its width and height:

SUBJECT: VISUAL BASIC 6.0

53/
53/119

' Load a bitmap.


Image1.Stretch = False
Image1.Picture = LoadPicture("c:\windows\setup.bmp")
' Reduce it by a factor of two.
Image1.Stretch = True
Image1.Move 0, 0, Image1.Width / 2, Image1.Width / 2
Image controls support all the usual mouse events. For this reason, many Visual
Basic developers have used Image controls to simulate graphical buttons and
toolbars. Now that Visual Basic natively supports these controls, you'd probably
better use Image controls only for what they were originally intended.

OLE(Object Linking and Embedding)


If a component supports object linking and embedding (OLE), you can link or
embed an object into your application without writing any code by using the
component's visual interface. You can use a component's visual interface in one
of two ways:
 By adding an OLE container control to your application, then inserting
an object into the control.
 By adding the object's class to the Toolbox, then adding an object of
that class to your application just as you would add a control to a form.

LECTURE 14
Arrays
Arrays are a form of variable, but you use them to hold more than one value at
a time. Or you can say that array is a group of variables of some data type all
the elements in an array are differentiated by using their index no.
Arrays have Upper and Lower bounds and the elements have to be within these
bounds. We can disclose an array of any of the basic data types.
Following are the two types of arrays in VB.

Fixed Size Arrays


The size of the array always remains the same. Fixed arrays can be declared by
giving a name to the array with the upper limit in the parentheses. Array
deceleration in the generate declares section of a module or procedure is as
shown in this example.
Dim length (I) as integer
In the above example the name of the array is length and the number I included
in the parentheses is the upper limit of the array and the lower limit is by

SUBJECT: VISUAL BASIC 6.0


54/
54/119
default set to 0. If you count to selects lower limit then you have to give the
lower limit and upper limit in the parentheses e.g.
Dim Length (1 to 10) as integer.
Here lower limit is 1 and upper limit is 10.

Dynamic Arrays
The arrays I have discussed so far are known as static arrays. Their size
number of dimensions and number of elementsis set when the array is
declared and cannot be changed. Another type of array, called dynamic, does
not have these limitations. When you first declare a dynamic array, you specify
its data type, but thats all. For example, the following statement declares a
dynamic array of type Integer:
Dim MyArray() As Integer
Then, when you know the required size of the array, use ReDim to specify it.
Here are some examples:
ReDim MyArray(100)
ReDim MyArray(10,10,20)
ReDim MyArray (1 to 100)
Once you have applied ReDim, you can use the array like any static array. Even
more flexibility is provided by the fact that you can ReDim a dynamic array as
many times as needed, changing the number of dimensions and/or elements to
suit the programs needs. ReDim is permitted only in procedure-level code.
Dynamic arrays follow the same scope rules as static arrays. In other words, if
you declare the array at the module level with Dim, its scope is limited to that
module. To make the dynamic array visible outside the module, use the Public
keyword:
Public MyArray() As Integer
Of course, if you declare a dynamic array at the procedure level its scope is local
to that procedure.
When you use ReDim to change the size of a dynamic array, the default is for
all data in the array to be lost. This means that all elements in the newly sized
array will be initialized to zero (numeric arrays), an empty string (string arrays),
the Empty value (Variant arrays), or Nothing (object arrays). If you want to
change the arrays size while preserving its data, you can do so (with some
limitations) by using the Preserve keyword. Clearly this is applicable only the
second and subsequent times the arrays size is changed with ReDim, otherwise
there will be no data in it to save. Heres how to use Preserve:
ReDim Preserve MyArray(100)
There are some limitations on using Preserve:
If you increase the number of elements in the array, data in the existing
elements will be preserved, and the new elements will be initialized by the usual
rules.

SUBJECT: VISUAL BASIC 6.0


55/
55/119
With a multidimensional array, you can use Preserve only to change the last
dimension of the array. Thus, after ReDim X(5, 5) you could execute ReDim
Preserve X(5,10) but not ReDim Preserve X(10, 5).
You cannot use Preserve when you are changing the number of array
dimensions.

Multidimensional Arrays
Sometimes you need to keep track of related information in an array. For
example, to keep track of each pixel on your computer screen, you need to refer
to its X and Y coordinates. This can be done using a multidimensional array to
store the values.
You can declare arrays of multiple dimensions. For example, the following
statement declares a two-dimensional 10-by-10 array within a procedure:
Dim MatrixA(9, 9) As Double
Either or both dimensions can be declared with explicit lower bounds:
Dim MatrixA(1 To 10, 1 To 10) As Double
You can extend this to more than two dimensions. For example:
Dim MultiD(3, 1 To 10, 1 To 15)
This declaration creates an array that has three dimensions with sizes 4 by 10
by 15. The total number of elements is the product of these three dimensions,
or 600.
Array example: Merging and Finding arrays values & adding arrays etc.

LECTURE 15
Control Arrays
So far, we've dealt with individual controls, each one with a distinctive name
and a distinct set of properties and events. In addition to these, Visual Basic
embodies the concept of control arrays, in which multiple controls share the
same set of event procedures even though each individual element in the array
can have different values for its properties. A control array can be created only
at design time, and at the very minimum at least one control must belong to it.
You create a control array following one of these three methods:
You create a control and then assign a numeric, non-negative value to its Index
property; you have thus created a control array with just one element.
You create two controls of the same class and assign them an identical Name
property. Visual Basic shows a dialog box warning you that there's already a
control with that name and asks whether you want to create a control array.
Click on the Yes button.
You select a control on the form, press Ctrl+C to copy it to the clipboard, and
then press Ctrl+V to paste a new instance of the control, which has the same

SUBJECT: VISUAL BASIC 6.0


56/
56/119
Name property as the original one. Visual Basic shows the warning mentioned in
the previous bullet.
Control arrays are one of the most interesting features of the Visual Basic
environment, and they add a lot of flexibility to your programs:
Controls that belong to the same control array share the same set of event
procedures; this often dramatically reduces the amount of code you have to
write to respond to a user's actions.
You can dynamically add new elements to a control array at run time; in other
words, you can effectively create new controls that didn't exist at design time.
Elements of control arrays consume fewer resources than regular controls and
tend to produce smaller executables. Besides, Visual Basic forms can host up to
256 different control names, but a control array counts as one against this
number. In other words, control arrays let you effectively overcome this limit.

Sharing Event Procedures


Event procedures related to items in a control array are easily recognizable
because they have an extra Index parameter, which precedes all other
parameters. This extra parameter receives the index of the element that's
raising the event, as you can see in this example:
Private Sub Text1_KeyPress(Index As Integer, KeyAscii As Integer)
MsgBox "A key has been pressed on Text1(" & Index & ") control"
End Sub
The fact that multiple controls can share the same set of event procedures is
often in itself a good reason to create a control array. For example, say that you
want to change the background color of each of your TextBox controls to yellow
when it receives the input focus and restore its background color to white when
the user clicks on another field:
Private Sub Text1_GotFocus(Index As Integer)
Text1(Index).BackColor = vbYellow
End Sub
Private Sub Text1_LostFocus(Index As Integer)
Text1(Index).BackColor = vbWhite
End Sub

Creating Controls at Run Time


Once you have created a control array at design time, even with just one item,
it's straightforward to create new items at run time using the Load command:
' Suppose you created Text(0) at design time.
Load Text1(1)
' Move the new control where you need it, and resize it.

SUBJECT: VISUAL BASIC 6.0

57/
57/119

Text1(1).Move 1200, 2000, 800, 350


' Set other properties as required.
Text1(1).MaxLength = 10
...
' Finally make it visible.
Text1(1).Visible = True
The Load command creates the new control with exactly the same set of
properties that the first item of the arrayText1(0) in the preceding example
had at design time, including the position on the form. The only exception to
this rule is that the Visible property for a control created in this way is always
False because Visual Basic correctly expects that you want to move the new
control to a different position before making it visible. Once you have
dynamically added a control, it belongs to the control array and can be treated
exactly like those controls created at design time.
Creating a Control Array at Design Time
Add a command button to the form and name it CMD.
Add another command button to the form and name it CMD again. A dialog box
will appear asking whether you want to create a control array. Click Yes.
Now goto the properties window and display the index property of each button.
Both the command buttons will have the same name CMD but different index
numbers CMD (0) and CMD (1)

LECTURE 16
Types of Interfaces
SDI: Single Document Interface.
MDI: Multiple Document Interface.
SDI: An application that supports only one document at a time called SDI
application. In SDI we cannot use multiple documents simultaneous, Paintbrush,
Notepad and WordPad are the examples of SDI applications.
MDI: Application such a MS-Excel and MS-Word have multiple documents
interface. To add a MDI forms click on project menu, and then the option ADD
MDI Form. It allows you to create an application that maintains multiple forms
within single contain form. They allow you to display multiple documents at the
same time, with each document displayed in its own window. Documents or
Child windows are contained in a parent window, which provides a workspace
for all the child windows in the application. For example, Microsoft Excel allows
you to create and display multiple-document windows of different types. Each
individual window is confined to the area of the Excel parent window. When you

SUBJECT: VISUAL BASIC 6.0


58/
58/119
minimize Excel, all of the document windows are minimized as well; only the
parent window's icon appears in the task bar.
A child form is an ordinary form that has its MDIChild property set to True. Your
application can include many MDI child forms of similar or different types.
At run time, child forms are displayed within the workspace of the MDI parent
form (the area inside the form's borders and below the title and menu bars).
When a child form is minimized, its icon appears within the workspace of the
MDI form instead of on the taskbar.
An MDI form is similar to an ordinary form with one restriction. You can't place a
control directly on a MDI form unless that control has an Align property (such as
a picture box control) or has no visible interface (such as a timer control).
You can recognize a MDI application by the inclusion of a Window menu item
with submenus for switching between windows or documents.

Visual Basic Multiple Document Interface (MDI)


In the previous section, we looked at using multiple forms in a Visual Basic
application. Visual Basic actually provides a system for maintaining multipleform applications, known as the Multiple Document Interface (MDI). MDI
allows you to maintain multiple forms within a single container form.
Examples of MDI applications are Word, Excel, and the Windows Explorer
program.
An MDI application allows the user to display many forms at the same time.
The container window is called the parent form, while the individual forms
within the parent are the child forms. Both parent and child forms are
modeless, meaning you can leave one window to move to another. An
application can have only one parent form. Creating an MDI application is a
two-step process. You first create the MDI form (choose Add MDI Form
from Project menu) and define its menu structure. Next, you design each of
the applications child forms (set MDIChild property to True).
Design-Time Features of MDI Child Forms:
At design time, child forms are not restricted to the area inside the parent
form. You can add controls, set properties, write code, and design the
features of child forms anywhere on the desktop.
You can determine whether a form is a child by examining its MDIChild
property, or by examining the project window. The project window uses
special icons to distinguish standard forms, MDI child forms, and MDI
parent forms:

SUBJECT: VISUAL BASIC 6.0

59/
59/119

SUBJECT: VISUAL BASIC 6.0

60/
60/119

where style can take on these values:


Standard form
Child form
Parent form

Run-Time Features of MDI Child Forms:


At run-time, the parent and child forms take on special characteristics and
abilities. Some of these are:
1. At run-time all child forms are displayed within the parent forms
internal area. The user can move and size child forms like any other
form, but they must stay in this internal area.
2. When a child is minimized, its icon appears on the MDI parent form
instead of the users desktop. When the parent form is minimized,
the entire application is represented by a single icon. When restored,
all forms are redisplayed as they were.
3. When a child form is maximized, its caption is combined with the
parent forms caption and displayed in the parent title bar.
4. By setting the AutoShowChildren property, you can display child
forms automatically when forms are loaded (True), or load child
forms as hidden (False).

Style Symbolic Constant


Effect
0
vbCascade
Cascade all nonminimized MDI
forms.
1
vbTileHorizontal Horizontally tile all nonminimized
child forms.
2
vbTileVertical
Vertically tile all nonminimized MDI
forms.
3
vbArrangeIcons Arrange icons for minimized MDI
forms.
Multiple-Document Application (MDI) Example:

child
MDI
child
child

Well create an MDI application which uses a simple, text box-based, editor as
the child application. There are a lot of steps, even for a simple example.
Start a new application. Create a parent form by selecting MDI Form from
the Insert menu. At this point, the project will contain an MDI parent form
(MDIForm1) and a standard form (Form1) which we will use as a child
form. Make MDIForm1 the startup form. We work with the parent form first:
1. Set the following properties:
Caption
Name
WindowState

MDI Example
frmParent
2-Maximized

2. Set up the following menu structure:


5. The active child forms menus (if any) are displayed on the parent
forms menu bar, not the child form.
6. New child forms can be created at run-time using a special form of
the Dim statement and the Show statement (the example illustrates
this process).
7. The parent forms ActiveForm property indicates which child form is
currently active. The ActiveControl property indicates which control
on the active child form has focus.
8. The Arrange command can be used to determine how the child
forms and their icons (if closed) are displayed. The syntax is:
Arrange style

Caption
&File
&New
&Arrange
&Cascade
&Horizontal Tile
&Vertical Tile
&Arrange Icons

Name
Indented
mnuFile
No
mnuFileNew
Yes
mnuArrange
No
mnuArrangeItem
Yes Index
mnuArrangeItem
Yes Index
mnuArrangeItem
Yes Index
mnuArrangeItem
Yes Index

=
=
=
=

0
1
2
3

3. Attach this code to the mnuFileNew_Click procedure. This code


creates new child forms (named frmChild - developed next).
Private Sub mnuFileNew_Click()
Dim NewDoc As New frmChild

SUBJECT: VISUAL BASIC 6.0


NewDoc.Show
End Sub

61/
61/119

4. Attach this code to the mnuArrangeItem_Click procedure.


establishes how child forms are displayed.

SUBJECT: VISUAL BASIC 6.0

This

Private Sub mnuArrangeItem_Click(Index As Integer)


Arrange Index
End Sub

62/
62/119

Private Sub Form_Resize()


Text1.Height = ScaleHeight
Text1.Width = ScaleWidth
End Sub
Run the application. Create new forms by selecting New from the File
menu. Try resizing forms, maximizing forms (notice how the parent
form title bar changes), minimizing forms, closing forms. Try all the
Arrange menu options.

Now, well work with Form1 which will hold the child application:
5. Draw a text box on the form.
form and the text box:
Form1:
Caption
MDIChild
Name
Visible

Child Form
True
frmChild
False

Text1:
Left
MultiLine
ScrollBars
Text
Top

0
True
2-Vertical
[Blank]
0

Set the following properties for the

My form resembles this:

6. Attach this code to the Form_Resize procedure. This insures that


whenever a child window is resized, the text box fills up the entire
window.

Menu: 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. Menu option can be enabled,
disabled,
checked and even popped-up on an object.
The
menus are created using the menu editor.
The
menu editor is where you design your menu.
A menu
consists of one or more menu tiles (e.g. File,
Edit)
access the menu. Each menu will on the
menu bar
contains one or more menu items. (Eg.open,
clear,
exit) etc.
When you create an MDI application, the menu bar on the MDI child form
replaces the menu bar on the MDIForm object when the child form is active.

Creating a menu using Menu-Editor.


What will our editor need in the way of menu commands? To keep the project
simple, well create only two menus: a File menu and an Edit menu. The File
menu will contain the New,
Open,
Save, Save As, and Exit
commands. The Edit menu will
contain
the Copy, Cut, Paste, and Font
commands. Lets get to work.
Display the projects form,
press
Ctrl+E
or
select
Tools|Menu Editor to display
Editor. Because this form does
have a menu, the editor is
We will start by adding the first
command to display on the
bar. Because were following

then
the Menu
not
yet
blank.
menu
menu
Windows

SUBJECT: VISUAL BASIC 6.0


63/
63/119
conventions, this will be the File menu. In the Caption box, enter &File and
youll see the menu caption appear in the large box at the bottom of the dialog
box. Next, tab to the Name box and enter mnuFile, then click on the Next
button. The highlight will move down a line in the menu outline, and the Text
Boxes will be cleared, ready for you to enter the next menu item.
First, let me point out two things:
Menu items can have access keys. In the menu displayed in the program,
an access key is designated by the underlined letter in the menu
command. The user can quickly access the menu command by pressing
that key when the menu is displayed. As with other control captions, you
specify the access key by preceding it with &.
In addition, each menu item has a Name property. As with other types of
controls, the Name property is used in the event procedures associated
with the item. I have developed the habit of beginning all menu item
names with mnu, then completing the name with the menu caption(s).
Thus, the File menu is named mnuFile, and the Open command on the File
menu will be named mnuFileOpen. This naming convention removes any
possibility of confusion when dealing with menus.
Now, on to the next menu item. Enter &New in the Caption box and
mnuFileNew in the Name box. Before clicking on the Next button, however,
click on the right arrow button. Youll see the New captionnow displayed with
an ellipsis in front of itmove over in the outline box. Essentially, weve made
the New command subsidiary to the File command. In other words, New will
appear as an item on the File menu, not as a separate menu item on the menu
bar.
Now click on Next. The new menu item (which is currently blank) is inserted at
the same level as the item immediately preceding it (in this case, the New
command). Enter &Open as the caption and mnuFileOpen as the name for
this menu item. Open the Shortcut Key list and scroll down, selecting Ctrl+O to
specify that the Ctrl+O key combination will be the shortcut for the File|Open
command. Notice that Ctrl+O is displayed in the menu outline next to the Open
caption.
Add the remaining two commands to the File menu:
&Save, with the name mnuFileSave and the Ctrl+S shortcut key
Save File &As, with the name mnuFileSaveFileAs and no shortcut key
At this point, your Menu Editor should look like Figure 11.3.
The next item we need to add to the File menu is not a menu command at all,
but rather a separator a horizontal line separating one section of the menu
from another. To add a separator, create a menu item with a caption consisting
of just a single dash, or hyphen. Because all menu items must be named, well
assign the name mnuFileSeparator to this item. After clicking on Next, add the
last item on the File menu, using the caption E&xit and the name mnuFileExit.

SUBJECT: VISUAL BASIC 6.0

64/
64/119

Figure 11.3 The Menu Editor after partially completing the File menu.
After entering the Exit command and clicking on Next, you are ready to start
with the Edit menu. At this point, any entry you make will be subsidiary to the
File menu. Because we want Edit to be a top-level menu, you need to click on
the left arrow button to move up one level on the outline. Assign the caption
&Edit and the name mnuEdit to this menu item, then click on Next. Click on the
right arrow to move down one level on the outline, and add the commands
shown in Table 11.1 to the Edit menu.
Thats itthe menu is finished. Your Menu Editor will look like the one shown in
Figure 11.4. Click on OK to close the Menu Editor and return to the form. You
will see the menus on the form during design and when the program runs. You
can open the menus and select commandsalthough nothing happens, because
we havent written event code for the menu commands yet.
Table 11.1 Edit menu commands.
Caption
&Copy
Cu&t
&Paste
-

Name
mnuEditCopy
mnuEditCut
mnuEditPaste
mnuEdit Separator

Shortcut Key
Ctrl+C
Ctrl+X
Ctrl+V

SUBJECT: VISUAL BASIC 6.0


&Font
mnuEditFont

65/
65/119
Ctrl+F

SUBJECT: VISUAL BASIC 6.0


66/
66/119
Click on the Insert button to add a new, blank menu item above the current
item.
Click on the Delete button to delete the current menu item.
A few items in the Menu Editor remain to be covered. Ill let you explore them
on your own.

Pop-up Menu
Visual Basic also supports pop-up menus, those context-sensitive menus that
most commercial applications show when you right-click on an user interface
object. In Visual Basic, you can display a pop-up menu by calling the form's
PopupMenu method, typically from within the MouseDown event procedure of
the object:
Private Sub List1_MouseDown(Button As Integer, Shift As Integer, _
X As Single, Y As Single)
If Button And vbRightButton Then
' User right-clicked the list box.
PopupMenu mnuListPopup
End If
End Sub

Figure 11.4. The completed menu displayed in the Menu Editor.

Other Menu Editor Options


The Menu Editor contains checkboxes for setting several menu item properties.
These properties control how the menu item is displayed when the program is
running and the user pulls down the menu:
CheckedDisplays a check mark next to the menu item when the menu is
displayed.
EnabledIndicates that a menu item is available. If a menu item is disabled,
it is grayed out, indicating it is unavailable to the user.
VisibleToggles the display of a menu item. You can hide a menu command
by setting its Visible property to False.
You can also edit the structure of a menu as follows:
Click on the up or down arrow to move the current menu item (the one
highlighted in the hierarchical list) without changing its left-right position.
Click on the left or right arrow to change a menu items position in the
hierarchy. You can have as many as four levels in a menu system.

The argument you pass to the PopupMenu method is the name of a menu that
you have defined using the Menu Editor. This might be either a submenu that
you can reach using the regular menu structure or a submenu that's intended to
work only as a pop-up menu. In the latter case, you should create it as a toplevel menu in the Menu Editor and then set its Visible attribute to False. If your
program includes many pop-up menus, you might find it convenient to add one
invisible top-level entry and then add all the pop-up menus below it. (In this
case, you don't need to make each individual item invisible.) The complete
syntax of the PopupMenu method is quite complex:
PopupMenu Menu, [Flags], [X], [Y], [DefaultMenu]

LECTURE 17
ActiveX control (Extrinsic controls)
An ActiveX control is an extension to the VB Toolbox. You are the active controls
just as you would do in any of the standard
built in
control such as the check control.
ActiveX controls have the file name extension
You can use the ActiveX controls provided

.OCX.
with

SUBJECT: VISUAL BASIC 6.0


67/
67/119
Visual Basic or obtain additional controls from third-party developers.
You can use ActiveX controls and other insertable objects to your project by
adding them to the Toolbox.
To add a control to a project's Toolbox
1. On the Project menu, click Components to display the Components
dialog box, as seen in figure. You can also display the dialog box by right
clicking on the Toolbox.
2. Items listed in this dialog box include all registered insertable objects,
designers, and ActiveX controls.
3. To add an ActiveX control to the Toolbox, select the check box to the left
of the control name.
4. Click OK to close the Components dialog box. All of the ActiveX controls
that you selected will now appear in the Toolbox.
The Visual Basic Professional and Enterprise Editors include the windows
common controls that allow you to create applications with the look and feel of
windows like, Toolbars, Status bar, and Tree windows of directory structures.

Toolbars
The toolbar control makes it easy to build toolbars into your project. Toolbars
are an extremely useful enhancement to menus. They provide mouse driver
short to menu option. Normally the toolbars appears on the top, so the align
property deputes to 1 (top).
If you want images to appear in your toolbar, you must first store them in an
image list control. If you intend to set the images at design time, the associated
imagers control must be on the same form as the toolbar after the images are
stored in an image list control. You set the image list properties of the toolbar
control to be the name of the image list control.

Toolbar Control

Almost all Windows applications these days use toolbars. A toolbar provides
quick access to the most frequently used menu commands in an application.
The toolbar control is a mini-application in itself. It provides everything you
need to design and implement a toolbar into your application. This control is
part of a group of controls loaded by selecting the Microsoft Windows
Common Controls from the Components dialog box.

SUBJECT: VISUAL BASIC 6.0


Possible uses for this control include:

68/
68/119

Provide a consistent interface between applications with matching


toolbars.
Place commonly used functions in an easily-accessed space.
Provide an intuitive, graphical interface for your application.
To create a basic toolbar, you need to follow a sequence of steps. You
add buttons to a Button collection - each button can have optional
text and/or an image, supplied by an associated ImageList control
(another custom control).
Buttons can have tooltips.
In more
advanced applications, you can even allow your user to customize the
toolbar to their liking!
After setting up the toolbar, you need to write code for the ButtonClick
event. The index of the clicked button is passed as an argument to this
event. Since toolbar buttons provide quick access to already coded
menu options, the code in this event is usually just a call to the
respective menu items Click procedure.

Toolbar Control Example


Well look at the simplest use of the toolbar control - building a fixed
format toolbar (pictures only) at design time. Well create a toolbar with
five buttons: one to create a new file, one to open a file, one to save a
file, one to print a file, and one for help. Place a toolbar and imagelist
control on a form. Right click on the imagelist control to set the pictures
to be used. Using the Images tab, assign the following five images:
Image 1 - NEW.BMP, Image 2 - OPEN.BMP, Image 3 - SAVE.BMP, Image
4 - PRINT.BMP, and Image 5 - HELP.BMP
When done, the image control should look like this:

SUBJECT: VISUAL BASIC 6.0

69/
69/119

SUBJECT: VISUAL BASIC 6.0


70/
70/119
A new button is added to the toolbar by clicking Insert Button. At a
minimum, for each button, specify the ToolTipText property, and the
Image number. Values I used are:
Index
1
2
3
4
5
6

ToolTipText Image
New File
1
Open File
2
Save File
3
Print File
4
-None0
Help me!
5

Note button 5 is a placeholder (set Style property to tbrPlaceholder) that


puts some space between the first four buttons and the Help button. When
done, my form looked like this:
Click OK to close this box. Now, right mouse click on the toolbar
control. The Property Pages dialog box will appear. Using the
General tab, select the imagelist control just formed. Now, choose the
Buttons tab to define each button:

Save and run the application. Note the buttons just click - we didnt write
any code (as mentioned earlier, the code is usually just a call to an existing
menu items click event). Check out how the tool tips work.
Quick Note on Tooltips:
Many of the Visual Basic controls support tooltips to inform the user of what a
particular control. Simply set individual controls ToolTipText property to a
non-blank text string to enable this capability.

Status bar
The statues bar control gives you a window that you can use to display the
status the application. Each status bar can be divided into cat most 16 panels.
At design item you can add the individual panels by using the panels page of the
custom property dialog box. You can add both text and a picture to the panel by
working with this dialog box.
The StatusBar control exposes a Panels collection, which in turn contains Panel
objects. A Panel object is an area of the status bar that can hold a piece of

SUBJECT: VISUAL BASIC 6.0


71/
71/119
information in a given style. The StatusBar control offers several automatic
styles (such as date, time, and state of shift keys), plus a generic Text style that
lets you show any string in a Panel object. You can also have a StatusBar
control work in SimpleText mode, whereby individual Panel objects are replaced
by a wider area in which you can display long text messages.

Setting Design-Time Properties


The General tab of the Properties dialog box doesn't contain many interesting
properties. In theory, you can set the Style property to 0-sbrNormal (the
default) or 1-sbrSimpleText, and you can specify the SimpleText property itself,
which will therefore appear as is in the StatusBar. In practice, however, you
never change the default settings because you rarely need to create a StatusBar
control merely to show a text message. In that case, in fact, you'd be better off
with a simpler Label control or a PictureBox control with Align = vbAlignBottom.
The only other custom property that appears on this tab is ShowTips, which
enables the ToolTipText property of individual Panel objects.
Move on to the Panels tab of the Property Pages dialog box to create one or
more Panel objects, as shown in Figure 10-22. Each Panel object has a number
of properties that finely determine its appearance and behavior. The most
interesting property is Style, which affects what's shown inside the Panel. The
default value is 0-sbrText, which displays the string assigned to the Text
property. You can use a Panel object as an indicator of the status of a particular
shift key using one of the settings 1-sbrCaps, 2-sbrNum, 3-sbrIns, or 4-sbrScrl.
You can also automatically display the current time or date using the 5-sbrTime
or 6-sbrDate setting.

SUBJECT: VISUAL BASIC 6.0

72/
72/119

LECTURE 18
Progress Bar
The progress bar control enables the users to get a feedback about a lengthy
operation by pictorially displaying a moving colored bar.
The ProgressBar control is used to inform the user about the progress state of a
lengthy operation. This control is the simplest one among those contained in the
MsComCtl.OCX file because it doesn't have any dependent objects and it doesn't
expose any custom events.
Setting Design-Time Properties
You have to set up a few properties at design time after you drop a ProgressBar
control on a form; in most cases, you can accept the default values. The most
important properties are Min and Max, which determine the minimum and
maximum values that can be displayed by the progress bar.
The ProgressBar control that comes with Visual Basic 6 includes two new
properties, Orientation and Scrolling. The former lets you create vertical
progress bars; the latter lets you alternate between a standard segmented bar
and a smoother bar, as you can see in Figure 10-24. You can change these
values even at run time.

Slider Control
The slider control is similar to a scroll bar yet allows the ability to select
a range of values, as well as a single value. This control is part of a group
of controls loaded by selecting the Microsoft Windows Common
Controls from the Components dialog box.
Possible uses for this control include:
To set the value of a point on a graph.
To select a range of numbers to be passed into an array.
To resize a form, field, or other graphics object.
Slider Control Properties:

Figure 10-22. The Panels tab of the Property Pages dialog box of a StatusBar
control.

Value
Current slider value.
Min, Max
Establish upper and lower slider limits.
TickFrequency
Determines how many ticks appear on
slider.

SUBJECT: VISUAL BASIC 6.0

73/
73/119

SUBJECT: VISUAL BASIC 6.0

TickStyle
Determines how and where ticks appear.
SmallChange Amount slider value changes when user presses
left or right arrow keys.
LargeChange Amount slider value changes when user clicks
the slider or presses PgUp or PgDn arrow keys.
SelectRange Enable selecting a range of values.
SelStart
Starting selected value.
SelLength
Length of select range of values.

Run the application. Establish a starting value for the selected range by
moving the slider to a desired point. Then, click the slider thumb while
holding down the Shift key and move it to the desired upper value.

Slider Control Example:


Well build a slider that lets us select a range of number somewhere
between the extreme values of 0 to 100. Put two label boxes and a
slider on a form:

Set the slider control SmallChange to 1, LargeChange to 10, Min to


0, Max to 100, TickFrequency to 10, and SelectRange to True. Use
the following in the Slider1_MouseDown event:
Private Sub Slider1_MouseDown(Button As Integer, Shift As
Integer, x As Single, y As Single)
If Shift = 1 Then
Slider1.SelStart = Slider1.Value
Label1.Caption = Slider1.Value
Slider1.SelLength = 0
Label2.Caption = ""
End If
End Sub
and this code in the Slider1_MouseUp event:
Private Sub Slider1_MouseUp(Button
Integer, x As Single, y As Single)
On Error Resume Next

74/
74/119

If Shift = 1 Then
Slider1.SelLength = Slider1.Value - Slider1.SelStart
Label2.Caption = Slider1.Value
Else
Slider1.SelLength = 0
End If
End Sub

As

Integer,

Shift

As

Common Dialog Control


The common dialog control provides a standard set of dialog boxes for
operations such as opening and saving files, setting print options, and selecting
colors and fonts. The control also has the ability to display Help by running the
Windows Help engine.
At run time, use the appropriate method, as listed in the following table, to
display the desired dialog.
Method
ShowOpen
ShowSave
ShowColor
ShowFont
ShowPrinter
ShowHelp

Dialog displayed
Open
Save As
Color
Font
Print
Invokes Windows Help

The Color Dialog


The Color common dialog box lets users select a color. It also permits them to
define new custom colors, but you can keep this privilege from users by
assigning the 4cdlCCPreventFullOpen value to the Flags property. Alternatively,
you can display the custom color section of the dialog box when the dialog
appears by setting the 2cdlCCFullOpen bit. (Custom color choices take up the
right half of the dialog box shown in Figure 12-2.) You can initially highlight a
color in the dialog box by assigning its RGB value to the Color property and
setting the 1-cdlCCRGBInit bit in the Flags property, as in the following
example:
' Let the user change the ForeColor of the Text1 control.
With CommonDialog1
' Prevent display of the custom color section
' of the dialog.

SUBJECT: VISUAL BASIC 6.0

75/
75/119

.Flags = cdlCCPreventFullOpen Or cdlCCRGBInit


.Color = Text1.ForeColor
.CancelError = False
.ShowColor
Text1.ForeColor = .Color
End With

The Font Dialog


The Font dialog box lets users select font names and attributes. You can
initialize the value shown in the dialog box, and you can decide which attributes
can be modified. Of course, it's also up to you to apply the new attributes to
controls and objects in your application.
The following piece of code lets the user modify the font attributes of a TextBox
control. It limits the user's selection to existing screen fonts and forces the font
size in the range from 8 to 80 points:
With CommonDialog1
.Flags = cdlCFScreenFonts Or cdlCFForceFontExist Or cdlCFEffects _
Or cdlCFLimitSize
.Min = 8
.Max = 80
.FontName = Text1.FontName
.FontSize = Text1.FontSize
.FontBold = Text1.FontBold
.FontItalic = Text1.FontItalic
.FontUnderline = Text1.FontUnderline
.FontStrikethru = Text1.FontStrikethru
.CancelError = False
.ShowFont
Text1.FontName = .FontName
Text1.FontBold = .FontBold
Text1.FontItalic = .FontItalic
Text1.FontSize = .FontSize
Text1.FontUnderline = .FontUnderline
Text1.FontStrikethru = .FontStrikethru
End With

SUBJECT: VISUAL BASIC 6.0

76/
76/119

LECTURE 19
Procedures & Functions
Event procedures: Much of the programmers code in visual basic that tells you
program how to respond to such as mouse clicks occurs in what visual basic
calls event procedure. An event procedure is nothing more than the code
needed to tell visual basic how to respond to event. E.g.. Click event of a
command button.
Private Sub command_Click ()
Statements
End Sub
Sub Procedures: Sub procedures or just subs, are procedures that can
accept arguments, execute code, and change the values of passed arguments.
Arguments are variables that are passed to a sub so that the sub can process
the data stored in the argument.
Public Sub procedureName ()
Statements
End Sub

Function Procedures: Functions are much like subs except they return a
value to the calling procedure. They are especially useful for taking one or more
pieces of data, called arguments, and performing since tasks with them. Then
the function returns a value that indicates the result of the tasks completed
within the function e.g.
Public Function Sum (A as integer) As Integer
Statements
End Function

Passing Arguments
By Reference: The ByRef prefix indicates that the parameters are passed by
reference, which is the defaults method in VB. When a variable is passed by
reference, the memory address of the variable is passed to the function. This
allows the functions or sub to modify the actual value of the variable. Syntax:
Function FunctionName (ByRef variable as dataType) as dataType.
Statements
End Function

SUBJECT: VISUAL BASIC 6.0


77/
77/119
By Value: The ByVal prefix specifies that parameters be passed by value. VB
will actually pass a copy of the contents of the variable rather than the memory
address of the variable. This prevents the function or sub from directly
modifying the contents of the original variable. Syntax.
Function FunctionName (ByVal variable as dataType) as dataType.
Statements
End Function

Private Procedures: Private is an optional keyword that defines the


procedure as being available only to other procedures in the form or module
form where it is declared. These procedures are declared private because they
are private to the form they cannot be called from outside that form.
Public Procedures: Indicates that the Function procedure is accessible to all
other procedures in all modules.

The ImageList Control


The ImageList control is most often used as a container for images and icons
that are employed by other controls, such as TreeView, ListView, TabStrip, and
ImageCombo controls. For this reason, it makes sense to describe it before any
other controls. The ImageList control is invisible at run time, and to display one
of the images it contains you must draw it on a form, a PictureBox control, or an
Image control, or associate it with another control.
Using the ImageList control as a repository for images that are then used by
other controls offers a number of advantages. Without this control, in fact, you
would have to load images from disk at run time using a LoadPicture function,
which slows down execution and increases the number of files to be distributed
with your program, or an array of Image controls, which slows down form
loading. It's much easier and more efficient to load all the images in the
ImageList control at design time and then refer to them from the other controls
or in source code.

Adding images at design time


An ImageList control contains a collection called ListImages containing one or
more ListImage objects. As with all collections, each object is identified by a 1based Index property, giving its position in the collection, as well as by an
optional Key property. You can add images to an ImageList control at design
time or runtime. At design time, display the controls property pages and select
the Images tab. Browse your disk for the image file, and optionally specify a

SUBJECT: VISUAL BASIC 6.0


78/
78/119
Key property for the image. Repeat until you have added all the required
images.

TreeView Control
The TreeView control lets you display and manipulate items in a hierarchical
view. An example that most of us see every day is Windows Explorer, which
uses a TreeView control to display folders and file names. You can select single
or multiple items, open and close branches on the tree, and control the way
items are displayed. Each item in a TreeView can have an icon associated with
it, such as the file folder and page icons used in Windows Explorer. Youre not
limited to disk-related items, thougha TreeView control can be used for any
information that is arranged hierarchically.
To be honest, the TreeView control is not all that easy to understand and use. It
is a complicated control, and it doesnt provide the almost-instant gratification
that we Visual Basic programmers have perhaps become too accustomed to.
Youll have to exercise your noggin a bit before you can get a TreeView control
doing just what you want it to.
The main reason for the TreeView controls complexity is its structure. It is not,
as are most Visual Basic controls, just a single object with a set of properties
and methods. Oh no, that would make life too easy. Let me explain:
Each item on a TreeVieweach twig on the treeis a Node object. Each of
these Node objects has its own set of properties and methods.
All of the Node objects belonging to a particular TreeView are organized in
the Nodes collection, which is itself an object with methods and
properties. One of the Nodes collections methods is Item, which is used
to access the individual Node objects in the collection.
The TreeView control itself is an object with methods and properties. One
of its properties is Nodes, which refers to its Nodes collection.
The TreeView object is (optionally) associated with an ImageList object
that holds the images to be displayed at the tree nodes.
You can probably see where the confusion comes from. When you want to do
something with a TreeView object, its not always clear whether you use the
methods and properties of the TreeView object itself, or whether you must
manipulate its associated Nodes collection or, perhaps, work directly with a
Node object.
While the TreeView control by itself can be useful, it really comes into its own
when you associate each node in the tree with something else. When TreeView
is used for a folder/file display, the association is automatic. What about other
associations? Ill be showing you how to associate a Text Box with each node in
a tree, and you can use the same or similar techniques to associate other
objects with TreeView nodes. I cant show all the details of using the TreeView
control, but I can get you started so you can explore further on your own. Ill
include a sample application that illustrates the techniques I cover.

SUBJECT: VISUAL BASIC 6.0


79/
79/119
Adding Nodes To A Tree
A TreeView object starts its life with no nodes. In form design, youll see a few
sample nodes displayed on the control, but these are present only so you can
view the effect of changing properties that determine how the nodes are
displayed. They are not present when you run the program. Nodes exist at
various levels. The topmost level is the root. Two nodes at the same level are
siblings. A node that is subsidiary to another is the child, while the other is the
parent. While a program is executing, the user can open a node, displaying all of
its children (if any), or close it, hiding any child nodes. You can also open and
close nodes in code, so with a single command, you can perform such useful
tasks as opening or closing all branches on a given tree.
Nodes must be added programmatically using the Add method of the Nodes
collection. Heres the syntax:
NewNode = TV.Nodes.Add(relative, relationship, key, text, image,
selectedImage)
TV is the name of the TreeView control. All of the method arguments except one
are optional, although its pretty rare to use this method without using at least
some of the optional arguments. Lets take a look at them:
RelativeRequired when you want to insert the new node in a relationship to
an existing node. You specify the relative node by either its Index property or
Key property (explained in a moment).
RelationshipUsed only when you specify relative. It determines the
relationship that the new node has to the existing node. Your choices are:
tvwLastThe new node becomes a sibling of the node named in relative
and is placed after all other siblings.
tvwNextThe new node becomes a sibling of the node named in relative
and is placed immediately after it.
tvwPreviousThe new node becomes a sibling of the node named in
relative and is placed immediately before it.
tvwChildThe node becomes a child node of the node named in relative
(this is the default).
KeyA unique string that identifies the node. If you specify this argument,
you can later refer to specific nodes by using the Item method with the key
value.
TextThe node label displayed in the TreeView control. This is the only
required argument for the Add method.
ImageThe Key or Index property of the image in the associated ImageList
control that will be displayed as part of the node.
SelectedImageSpecifies the image that will be displayed when the node is
selected. If this argument is omitted, the image specified by image will be
displayed, whether the node is selected or not.
Each node added to a tree is automatically assigned a unique Index property.
These are nothing more than sequential integers that uniquely identify each

SUBJECT: VISUAL BASIC 6.0


80/119
node. Each node in a tree, therefore, can always be uniquely identified by its
Index property, as well as by its Key property, if you assigned one. As we will
see, the Index property provides a method of linking each node to some other
object. Note also that each Node object has the Tag property, which can
provide another way of both identifying and linking nodes.
Displaying Images At Nodes
To display images along with the text in TreeView nodes, you must associate an
ImageList control with the TreeView object. This is one of the relatively simple
aspects of working with a TreeView control. You need only to place an ImageList
control on your form, then include code to load it with the needed images,
assigning each one a unique Key property. (You learned about the ImageList
control earlier in this chapter.) Then, associate the ImageList control with
TreeView by setting the appropriate property. You can do this at design time,
using the TreeView controls Custom Properties dialog box, or at runtime, as
follows:
TreeView1.ImageList = ImageList1
Finally, each time you add a node to the tree, specify which image is to be
displayed with the node, using the images Key property to refer to it. You can
also specify a different image to be used when the node is open and displaying
its child nodes, just as Windows Explorer displays open or closed file folder
images as appropriate. This is done by setting the SelectedImage property to
the desired image when the node is open.
Where do you get the images? You can create your own, or you can use those
supplied by Visual Basic, designed specifically for use with the TreeView control.
They are installed in a subfolder off the main Visual Basic folder. Installation of
these and other graphics is optional when Visual Basic is installed, so if you
cannot find these images, you may need to repeat the Visual Basic installation.
Here are the available images:
OPEN.BMPAn open file folder
CLOSED.BMPA closed file folder
LEAF.BMPA document page
PLUS.BMPA plus sign
MINUS.BMPA minus sign

LECTURE 20
The Main Benefits of OOP
Encapsulation
Encapsulation is probably the feature that programmers appreciate most in
object-oriented programming. In a nutshell, an object is the sole owner of its
own data. All data is stored inside a memory area that can't be directly accessed

SUBJECT: VISUAL BASIC 6.0


81/
81/119
by another portion of the application, and all assignment and retrieval
operations are performed through methods and properties provided by the
object itself

Polymorphism
Informally, Polymorphism is the ability of different classes to expose similar (or
identical) interfaces to the outside. The most evident kind of polymorphism in
Visual Basic is forms and controls. TextBox and PictureBox controls are
completely different objects, but they have some properties and methods in
common, such as Left, BackColor, and Move. This similarity simplifies your job
as a programmer because you don't have to remember hundreds of different
names and syntax formats. More important, it lets you manage a group of
controls using a single variable (typed as Control, Variant, or Object) and create
generic procedures that act on all the controls on a form and therefore
noticeably reduce the amount of code you have to write.

Inheritance
Inheritance is the ability, offered by many OOP languages, to derive a new class
(the derived or inherited class) from another class (the base class). The derived
class automatically inherits the properties and methods of the base class. For
example, you could define a generic Shape class with properties such as Color
and Position and then use it as a base for more specific classes (for example,
Rectangle, Circle, and so on) that inherit all those generic properties. You could
then add specific members, such as Width and Height for the Rectangle class
and Radius for the Circle class. It's interesting to note that, while polymorphism
tends to reduce the amount of code necessary to use the class, inheritance
reduces the code inside the class itself and therefore simplifies the job of the
class creator. Unfortunately, Visual Basic doesn't support inheritance, at least
not in its more mature form of implementation inheritance.

SUBJECT: VISUAL BASIC 6.0


82/
82/119
Declarations: You can place constant, type, variable, and dynamic-link library
(DLL) procedure declarations at the module level of form, class or standard
modules.
Procedures: A Sub, Function, or Property procedure contains pieces of code
that can be executed as a unit.

Form Modules
Form modules (.FRM file name extension) are the foundation of most Visual
Basic applications. They can contain procedures that handle events, general
procedures, and form-level declarations of variables, constants, types, and
external procedures. If you were to look at a form module in a text editor, you
would also see descriptions of the form and its controls, including their property
settings. The code that you write in a form module is specific to the particular
application to which the form belongs; it might also reference other forms or
objects within that application.

Standard Modules
Standard modules (.BAS file name extension) are containers for procedures and
declarations commonly accessed by other modules within the application. They
can contain global (available to the whole application) or module-level
declarations of variables, constants, types, external procedures, and global
procedures. The code that you write in a standard module isn't necessarily tied
to a particular application; if you're careful not to reference forms or controls by
name, a standard module can be reused in many different applications.

Class Modules
Class modules (.CLS file name extension) are the foundation of object-oriented
programming in Visual Basic. You can write code in class modules to create new
objects. These new objects can include your own customized properties and
methods.

Code Module
Code in Visual Basic is stored in modules. There are three kinds of modules:
form, standard, and class.
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 might find that
there is common code you want to execute in several forms. You don't want to
duplicate the code in both forms, so you create a separate module containing a
procedure that implements the common code. This separate module should be a
standard module. Over time, you can build up a library of modules containing
shared procedures.

Each standard, class, and form module can contain:

LECTURE 21
Error Handling
Error: Any bug is a program (code) is called an error. It effects the execution of
the code adversely programming errors can of the following three types.
Syntax Error: Occurs when we enter an incorrect line of code such as a
mistake in typing a keyword. A punctuation is mirror as an incorrectly speeded
variable.

SUBJECT: VISUAL BASIC 6.0


83/
83/119
Run-Time Errors: Occurs when a command attempts to perform an action that
is not valid. E.g. a own=line error occurs if we try to assign a strong to a
numeric variable. Error handles execute only if a run-time error is occurred.
Logical Error: Occurs when an application executes without syntax error or
run-time errors, but the result is not what we intended.
Error Trapping
If just want your program to degrade gracefully and not just roll over, youll
want to prevent total error. The command that activates (enables) error
trapping with in a given procedure is.
On Error Statement
Enables an error-handling routine and specifies the location of the routine within
a procedure; can also be used to disable an error-handling routine.
Syntax
On Error GoTo lineNumber
On Error Resume Next
On Error GoTo 0
The On Error statement syntax can have any of the following forms:
Statement

Description

On Error GoTo line

Enables the error-handling routine that starts at line


specified in the required line argument. The line
argument is any line label or line number. If a run-time
error occurs, control branches to line, making the error
handler active. The specified line must be in the same
procedure as the On Error statement; otherwise, a
compile-time error occurs.

On Error Resume Next Specifies that when a run-time error occurs, control
goes to the statement immediately following the
statement where the error occurred where execution
continues. Use this form rather than On Error GoTo
when accessing objects.
On Error GoTo 0

Disables any enabled error handler in the current


procedure.

If you don't use an On Error statement, any run-time error that occurs is fatal;
that is, an error message is displayed and execution stops.
Error-handling routines rely on the value in the Number property of the Err
object to determine the cause of the error. The error-handling routine should

SUBJECT: VISUAL BASIC 6.0


84/
84/119
test or save relevant property values in the Err object before any other error can
occur or before a procedure that might cause an error is called. The property
values in the Err object reflect only the most recent error. The error message
associated with Err.Number is contained in Err.Description.

The Resume Statement


The Resume statement is used within error-handling code to instruct the
program where to continue execution after the error has been handled.
Resume can be used only within error-handling code; otherwise, an error
occurs. There are several variants of Resume. When used by itself, it means
try again to execute the statement that caused the error. This is appropriate in
situations where the cause of the error has been fixed. In other circumstances,
however, this is not possible. If you want execution to continue somewhere
other than the statement that caused the error, you have the following two
choices:
Resume Next continues execution immediately after the statement that
caused the error.
Resume label continues execution with the program line identified by label.
The line identified by label must be in the same procedure as the Resume
statement (the same procedure where the error occurred).
On Error GoTo 0 disables error handling in the current procedure. It doesn't
specify line 0 as the start of the error-handling code, even if the procedure
contains a line numbered 0. Without an On Error GoTo 0 statement, an error
handler is automatically disabled when a procedure is exited.
Note: To prevent error-handling code from running when no error has
occurred, place an Exit Sub, Exit Function, or Exit Property statement
immediately before the error-handling routine, as in the following
fragment:

The ERR Object


Much of Visual Basics ability to deal with errors comes from the ERR object.
Each Visual Basic program automatically has a single ERR object associated with
it. ERR has global scope, meaning it can be accessed from anywhere in a
program. At any moment, ERR contains (in its properties) information about the
most recent error that has occurred. The properties youll need most often are
these:
NumberA type Long value identifying the specific error that occurred.
DescriptionA brief text description of the error.
SourceA string identifying the name of the object or application that
generated the error.

SUBJECT: VISUAL BASIC 6.0


85/
85/119
The first two properties of the ERR object provide the same numerical code and
text description displayed in the error dialog box when an untrapped error
occurs. As such, they do not provide a great deal of information. The value of
these properties lies in giving your program access to this information in code,
enabling it to determine which error occurred and then to take appropriate
action. The Source property is not much use in a self-contained application,
because it will return only the name of the Visual Basic project

Raising Errors
When working on your projects error-handling code, mimicking the occurrence
of certain runtime errors is often useful, so you can see exactly how your errorhandling routines work. You can mimic errors in code using the ERR objects
Raise method. The syntax is as follows:
Err.Raise number, source, description, helpfile, helpcontext
The only required argument is number, which is a Long integer that identifies
the error. To mimic a specific Visual Basic error, use the number associated with
the error, as indicated in the Help information. The other arguments are
optional:
sourceString expression naming the object or application that generated
the error. When setting this property for an object, use the form project.class. If
source is not specified, the programmatic ID of the current Visual Basic project
is used.
descriptionString expression describing the error. If unspecified, the value
in number is examined. If it can be mapped to a Visual Basic runtime error
code, the string that would be returned by the Error function is used as
description. If no Visual Basic error corresponds to number, the Applicationdefined or object-defined error message is used.
helpfileThe fully qualified path to the Microsoft Windows Help file in which
help on this error can be found. If unspecified, Visual Basic uses the fully
qualified drive, path, and file name of the Visual Basic Help file.
helpcontextThe context ID identifying a topic within helpfile that provides
help for the error. If omitted, the Visual Basic Help file context ID for the error
corresponding to the Number property is used, if it exists.

Visual Basic Debugging Tools.


Whats A Bug?
A bug is a code error that prevents your program from operating correctly.
Were not talking about an error that prevents the program from executing or
that can be caught by Visual Basics error-trapping mechanisms. Rather, a bug
is a logical mistake in the programs source code that causes the program to
behave incorrectly. Here are some examples of the kinds of problems bugs can
cause:
A financial program that calculates and displays incorrect loan payments

SUBJECT: VISUAL BASIC 6.0


86/
86/119
A graphics program that applies improper colors to images
Any program that does not respond properly to user commands
Here are some of the most essential guidelines to follow when it comes to
avoiding program bugs:
Always use Option Explicit, so variable declaration is required. This prevents
the pernicious misspelled variable name error that is perhaps the most
common cause of bugs in Visual Basic.
Divide your code into relatively small, manageable procedures. Large,
complex procedures are more prone to bugs, and more difficult to debug, than
short, simple ones.
Use global and public variables sparingly. Stick with local variables within
pro-cedures as much as possible, resorting to global and public variables only
when unavoidable.
Use the proper data type for your programs data. Using type Integer for
certain calculations can result in rounding errors, which can cause bugs.

The Immediate Window


The Immediate window is automatically displayed in the Visual Basic
environment when you run a program. It does not display anything at first, and
in fact, it will remain blank if you do not use it. It is called the Immediate
window, because any code you type into it is executed immediately. You can use
the Immediate window whether or not a program is executing. To display it
when no program is executing, select Immediate Window from the View menu
or press Ctrl+G.
When a program is not executing, the primary use for the Immediate window is
to evaluate Basic expressions. If you type a line of Basic code in the Immediate
window (or copy and paste it from the Code Editing window) and then press
Enter, the code is executed immediately. Typically, you will use the Print
statement to evaluate the value of expressions. Thus, if you enter
print cos(.5)
and press Enter, Visual Basic will display 0.877582561890373 in the Immediate
window.
The Immediate window is much more useful in break mode, when program
execution is paused.
The Debug Object: You can also add lines of code to your program that prints
values directly to the immediate windows. For this you use a predefined visual
basic object called debug in the following form.
Debug.Print variable
Debug.Print expression

SUBJECT: VISUAL BASIC 6.0


87/
87/119
Watch Window: In debugging terms, a watch is a variable of object that is
specifically monitored or watched in real-time as the program executes. You can
view the properties of watches in the watch window. The watch window can be
called up by pressing the watch window button or by adding a watch to the
window.

LECTURE 22-23
Component Object Model (COM)
COM is the basis for all OCX controls. COM is a specification. It doesnt tell the
user hw to implement a control; rather it concentrates on the way in which two
processes communicate with each other and defines some standard interfaces
for them to communicate. COM allows software components to communicate
with each other. It is a binary standard that allow any two components to
communicate regardless of the language the components are written in. The
only way to access and interact with a COM object is through interfaces. An
open architecture for cross-platform development of client/server applications
based on object-oriented technology. Clients have access to an object through
interfaces implemented on the object. COM is language neutral, so any language
that produces ActiveX components can also produce COM applications.
Distributed Component Object Model (DCOM)
It allows information exchange over the Internet, the local intranet or any other
network. While COM is the basis for OCX controls, DCOM is the basis for ActiveX
controls-as ActiveX itself is nothing but Internet enabled OCX. OCX supports
links to other machines, but the code for that link would be executed locally.
DCOM allows the user to create OLE links that rely on code stored on the
machines. In many cases the code will also execute remotely.
Constituents of ActiveX Control
An ActiveX control can be developed in a way similar to that of developing
applications. The ActiveX Control Interface Wizard takes care of intricate parts of
the code and generates an outline to which the code can be added to implement
unique functions.
Types of ActiveX Controls
Visual Basic offers the user three different types of controls. The techniques for
authorizing all ActiveX controls are the same. The different types of ActiveX
controls offered by Visual Basic are as follows.
User Drawn Controls: These controls are developed from scratch. The
user is responsible for designing the controls interface and is in control of
its appearance and interface. These implementation of thee controls is

SUBJECT: VISUAL BASIC 6.0


88/
88/119
very difficult as every bit of functionality starting from the controls
interface to its appearance has to be written by developers. They also are
the most flexible ones, as the user does not have to put up with limitations
of other controls.
Existing Visual Basic Controls: The simplest of custom ActiveX control
is one that is based on an existing control. The user can keep most or all of
the original controls functionality and then add custom members.
Constituent Controls: In cases where most of the functionality we want
to include in our custom control already exists, a new control can be
designed that includes existing controls. The controls that form part of the
newly developed custom control are called constituent controls.
ActiveX Controls (UserControl)
The ActiveX Control created in Visual Basic is always composed in a container
called a UserControl object, just as a Visual Basic application is always
composed in a Form object container. Like a Visual Basic Form Object, a
UserControl has a code module and Visual Designer. Note that you can also use
class modules inside an ActiveX Control project. An ActiveX control in Visual
Basic can have any other controls called constituent control that you choose to
place on the user control object. This type of control can then be used in other
visual basic projects as well as other ActiveX complaint programs such as
Microsoft excel. Their controls can also be embedded and distributed through
HTML WebPages.
UserControl objects are stored in a plain text file with a .CTL extension,
containing the source code and property setting of the UserControl object and
any constituent controls that may be present. If the UserControl object and any
constituent controls use graphical elements such as bitmaps which cannot be
stored as plain text, Visual Basic stores those elements in a .CTX file with the
same name as the .CTL file.

Steps to create an ActiveX control


1. Start a new project. Select ActiveX control as the project type.
2. Set the name property of the Project.
3. Set the name property of the UserControl
4. From the toolbox add the controls for your ActiveX control.
5. Set the properties of the controls according to the function you want to be
performed.
6. Code for your UserControl.
7. Save the UserControl form and Project
8. Before a control can be used, appropriate entries must be created for it in
the Windows registration database. Selecting the FileMake menu

SUBJECT: VISUAL BASIC 6.0


89/
89/119
command can do compilation. After it is compiled, the Control is registered
on the computer.

SUBJECT: VISUAL BASIC 6.0


90/
90/119
accessing the same EXE can overwrite global data, but that doesnt happen if
they each have their own in-process server.

To use this controls in other VB application add it to toolbox from components.

LECTURE 25-26

LECTURE 24
Introduction to ActiveX DLLs and ActiveX EXE
Visual Basic can be used to compile class-based projects such as ActiveX
components. These components can either take the form of DLLs and EXEs. The
components offer us the ability to provide the functionality of objects without
having to redistribute or duplicate the source code of our classes. When an
object variable is created to access the properties and methods of a class, we
are actually invoking an executable file (DLL or EXE) that runs in the
background and waits to be contacted. This is activated every time a property
value is set or read or a method is called.

Database
A database is a collection of information, or data, arranged in a particular
manner. The basic unit of information in a database is called a record. Each
record in a database contains two or more fields that hold specific types of
information. Perhaps the most common example of a database is an address
list. Each entry in the database constitutes one record: an individuals name and
address information. Each record in the database contains fields that hold
separate items of information: first name, last name, address, city, and so on.
These fields are the same for every record in the database, and they are
assigned names identifying the data they contain.

ActiveX DLLs
ActiveX DLL (Dynamic Link Library) always run a In-Process servers as they are
given space in the calling programs address space. It gets linked with your code
at run time and provides functionalities to your code. This increases the
performance considerably. Since DLLs run in another applications process space
so can never be run alone.

Data Access in Visual Basic

ActiveX EXE
ActiveX EXE always run in their process space (out-of-process server) therefore
always there is an overhead as data needs to be transferred access the
application boundaries. The advantage of EXEs is that they can run as standard
applications and they act as code component for other application.

OLE DB

ActiveX Document DLLs Vs. EXEs


You can create both ActiveX document EXEs and DLLs. Heres the difference: if
an ActiveX document is written as an executable file (EXE file), it is an out-ofprocess server and runs in its own process; if it has been implemented as a
dynamic link library (DLL file), it is an in-process server and runs in the same
process as the client application.
Although ActiveX documents are usually built as EXE projects, the benefit of
DLLs is that applications that use in-process servers usually run faster than
those that use out-of-process servers because the application doesnt have to
cross process boundaries to use an objects properties, methods, and events. In
addition, the performance of an in-process component, or DLL file, surpasses
that of the same component compiled as an EXE. Also, multiple programs

Visual Basic provides a variety of options to access remote Client/Server


databases. They are
Data Control: It binds data-aware controls to Microsoft Access and other ODBC
data sources.

OLE DB is a set of Component Object Model (COM) interfaces that provide


programmers with access to a variety of information sources. The goal of OLE
DB is to provide universal data accessaccess that can deal with any type of
data, regardless of its format, and that is not restricted to certain data sources.
The OLE DB interfaces support the data management capabilities of each type of
data source. OLE DB is not accessed directly from Visual Basic, but instead is
accessed indirectly via ActiveX Data Objects (ADO).

ADO
ActiveX Data Objects provide Visual Basic programmers with an application-level
interface to OLE DB. You rarely, if ever, need to worry about OLE DBits just
there doing its jobso you can think of ADO as an interface directly to the data
source. ADO is new in this release of Visual Basic and is considered by Microsoft
to be its premier data access technology. If you have used earlier versions of
Visual Basic for database programming, you may be familiar with the older
technologies: Remote Data Objects (RDO) and Data Access Objects (DAO).
These technologies are still supported by Visual Basic. In fact, the Data control,
used in the sample application developed in Chapter 19, makes use of these

SUBJECT: VISUAL BASIC 6.0


91/
91/119
older technologies. However, for new projects, you should use ADO. Two ways
exist to use ADO: directly in code or indirectly via the ADO Data Control

ODBC
Open Database Connectivity (ODBC) provides an Applications Programming
Interface (API) that contains procedures for performing various datamanipulation tasks. A program calls these API procedures, as needed, and the
ODBC Driver Manager passes the calls to the appropriate driver. Appropriate
means the driver that is designed for the particular data source that is in use.
This is where the open part of the ODBC name comes from. Any data source
publisher can write an ODBC driver for its own data format.
ODBC is generally considered obsolete. The only reason to use ODBC in a new
database project is if you need to access a data source that is in an obscure
format, unsupported by ADO, for which an ODBC driver exists. Even in this
situation, you probably are better off opting to use DAO, because it supports
ODBC databases.

DAO
Data Access Objects (DAO) is similar to ODBC in that it provides an API that
your program can call to perform data-manipulation tasks. DAO differs from
ODBC in that it uses the Microsoft Jet Database Engine rather than a driver
provided by the data source publisher. DAO is optimized to work with data
source files in the MDB format (the same format used by the Microsoft Access
database program). However, DAO also supports ODBC databases, as well as
data sources in a variety of formats, including Paradox, FoxPro, dBase, Excel,
and Lotus 1-2-3.

SUBJECT: VISUAL BASIC 6.0


92/
92/119
2. DatabaseName
3. RecordSource
The Data control is automatically initialized when your application starts before
the initial Form_Load procedure. If the Connect, DatabaseName, RecordSource
and RecordsetType properties are valid, or if you set these Data control
properties at run time and use the Refresh method, the Microsoft Jet database
engine attempts to create a new Recordset object based on those properties.
This Recordset is accessible through the Data control's Recordset property. If,
however, one or more of these properties is set incorrectly at design time, an
untrappable error occurs when Visual Basic attempts to use the properties to
open the specified database and create the Recordset object.

Adding Records To Databases


You can add a new record to a database with the AddNew method of the
Recordset property of a data or ADO data control, or of the Resultset property
of a remote data control. Lets see an example. When the user clicks the Add
button in the dbmethods example were developing in this and the previous few
topics, we can add a new record like this:
Private Sub cmdAdd_Click()
Data1.Recordset.AddNew
End Sub
This adds a new, blank record. You can enter the data you want in the records
fields, and to update the database, you click the Update button.

Deleting Records In Databases

The Remote Data Objects (RDO) programming model was developed specifically
to deal with the special requirements of accessing the data source via a
network, referred to as remote data access. RDO works by adding a layer on top
of ODBC to handle the special needs of remote access, such as establishing
connections and creating results sets. In some situations, RDO works with DAO
to perform the required tasks. RDO can be implemented totally in code or via
the RemoteData control.
Implementing RDO in a Visual Basic application is very similar to using DAO. In
fact, a Visual Basic application that uses the Data control and DAO can easily be
converted to use the RemoteData control and RDO. The few differences arise
primarily because RDO is designed for use only with strictly relational databases.
RDO relies on the data source to process queries because RDO has no query
processor of its own.

You can delete a record in a database with the Delete method of the
Recordset property of a data or an ADO data control, or of the Resultset
property of a remote data control. Lets see an example. When the user clicks
the Delete button in the dbmethods example were developing in this and the
previous few topics, we can delete a record like this:
Private Sub cmdDelete_Click()
Data1.Recordset.Delete
...
End Sub
To avoid displaying a blank record, we also move to the next record this way:
Private Sub cmdDelete_Click()
Data1.Recordset.Delete
Data1.Recordset.MoveNext
End Sub

Using Data Control

Updating A Database With Changes

Properties to be set: 1. Connect

After changing the fields in a record, you can update a database with the
UpdateRecord method of the data, ADO data control, or remote data control.

RDO

SUBJECT: VISUAL BASIC 6.0


93/
93/119
Lets see an example. When the user clicks the Update button in the dbmethods
example were developing in this and the previous few topics, we can update the
database with the new record like this:
Private Sub cmdUpdate_Click()
Data1.UpdateRecord
End Sub

Moving To The Next Record


You can move to the next record of a database with the MoveNext method of
the Recordset property of a data or ADO data control, or of the Resultset
property of a remote data control. Lets see an example. When the user clicks
the Next button in the dbmethods example were developing in this and the
previous few topics, we can move to the next record like this:
Private Sub cmdNext_Click()
Data1.Recordset.MoveNext
End Sub

SUBJECT: VISUAL BASIC 6.0


End Sub

94/
94/119

Recordset: Record sets are objects that represent collectors of records from
one of more tables. Recordset are equivalent of variables in regular
programming you can access the tables of database only by manipulating the
Recordset objects. A Recordset is a view of some data in the database, selected
from the database according to user specified criteria. In other word, A
Recordset represents the entire set of records from a table in a database or that
result from an executed command. A Recordset is a set of rows in which each
row has columns of data.
There are three types of Recordset namely.
(i)
Dynasets, which are updateable views of data.
(ii) Snapshots which are static (Read-only) views of data
(iii) Table, which are direct views of table.

Moving To The Previous Record

Data Access Object: DAO was the first object-oriented interface that

You can move to the previous record of a database with the MovePrevious
method of the Recordset property of a data or ADO data control, or of the
Resultset property of a remote data control. Lets see an example. When the
user clicks the Previous button in the dbmethods example were developing in
this and the previous few topics, we can move to the previous record like this:
Private Sub cmdPrevious_Click()
Data1.Recordset.MovePrevious
End Sub

exposed the Microsoft Jet database engine and allowed Visual Basic developers
to directly connect to Access tables - as well as other databases - through
ODBC. DAO is suited best for either single-system applications or for small, local
deployments. DAO enables you to use a programming language to access and
manipulate data in local or remote databases, and to manage databases, their
objects, and their structure. DAO supplies a hierarchical set of objects that use
the Microsoft Jet database engine to access data and database structure in:

Moving To The First Record


You can move to the first record of a database with the MoveFirst method of
the Recordset property of a data or ADO data control, or of the Resultset
property of a remote data control. Lets see an example. When the user clicks
the First button in the dbmethods example were developing in this and the
previous few topics, we can move to the first record like this:
Private Sub cmdFirst_Click()
Data1.Recordset.MoveFirst
End Sub

Moving To The Last Record


You can move to the last record of a database with the MoveLast method of the
Recordset property of a data or ADO data control, or of the Resultset property
of a remote data control. Lets see an example. When the user clicks the Last
button in the dbmethods example were developing in this and the previous few
topics, we can move to the last record like this:
Private Sub cmdLast_Click()
Data1.Recordset.MoveLast

Microsoft Jet (.MDB) databases


ODBC data sources, using an ODBC driver
Installable ISAM databases, such as dBase, Paradox and Microsoft
FoxPro which the database engine can read directly

Remote Data Object: RDO is an object-oriented data access interface to


ODBC combined with the easy-to-use style of DAO, providing an interface that
exposes virtually all of ODBCs low-level power and flexibility. RDO is limited,
though, in that it doesn't access Jet or ISAM databases very well, and that it can
access relational databases only through existing ODBC drivers. However, RDO
has proven to be the interface of choice for a large number of SQL Server,
Oracle, and other large relational database developers. RDO provides the
objects, properties, and methods needed to access the more complex aspects of
stored procedures and complex result sets.

SUBJECT: VISUAL BASIC 6.0

95/
95/119

LECTURE 27-28
ActiveX Data Objects (ADO): ADO enables you to write a client application to
access and manipulate data in a data source through a provider. ADO is ideally
suited to consume data exposed by OLE DB providers. OLE DB provides highperformance access to any data source, including relational and non-relational
databases, email and file systems, text and graphics, custom business objects,
and more. ADO connects to a database by means of OLEDB provides OLEDB
provides is a Microsoft lower-level database interface that provides access to
many different kinds of data. It expresses their database of ADO.
Possible Uses
Connect to a local or remote database.
Open a specified database table or define a set of records based on a
Structured Query Language (SQL) query or stored procedure or view of the
tables in that database.
Pass data field values to data-bound controls, where you can display or
change the values.
Add new records or update a database based on any changes you make to
data displayed in the bound controls.

SUBJECT: VISUAL BASIC 6.0


96/
96/119
7. Repeat steps 6, 7, and 8 for each additional field you want to access.
8. Press F5 to run the application. You can use the four arrow buttons on the
ADO Data control to move to the beginning of the data, to the end of the
data, or from record to record through the data.
Setting the ConnectionString, RecordSource, DataSource, and DataField
Programmatically
The code below shows how to set these four properties programmatically. Note
that setting the DataSource property requires the Set statement.
Private Sub Form_Load()
With ADODC1
.ConnectionString =
.RecordSource = Select * From Titles Where AuthorID = 7
End With
Set Text1.DataSource = ADODC1
Text1.DataField = "Title"
End Sub
Example of ADO Data Control Programmatically in which the addition,
deletion and navigation between the records is displayed.
Design the Following Form and Code

To create a client, or front-end database application, add the ADO Data control
to your forms just as you would any other Visual Basic control. You can have as
many ADO Data controls on your form as you need.
To create a simple front-end database application
1. Draw an ADO Data Control on a form.
If the control is not available in the Toolbox, press CTRL+T to display the
Components dialog box. In the Components dialog, click Microsoft ADO
Data Control 6.0 (OLEDB).
2. On the Toolbox, click the ADO Data Control to select it. Then press F4 to
display the Properties window.
3. In the Properties window, set the RecordSource property to a Table or
SQL statement. For example: SELECT * FROM Titles WHERE AuthorID = 72
4. Draw a TextBox control on the form to display the database information.
5. In the Properties window, set the DataSource property for Text1 to the
name of the ADO Data control (ADODC1). This binds the text box to the
ADO Data control.
6. In the Properties window, click DataField and a list of available fields will
drop down. Click the name of the field you want to display.

Option Explicit
Dim msgRes As VbMsgBoxResult
Private Sub cmdAdd_Click()
Text1.Locked = False
Text2.Locked = False
Text3.Locked = False

SUBJECT: VISUAL BASIC 6.0


Text4.Locked = False
Text5.Locked = False

97/
97/119

cmdSave.Enabled = True
cmdCancel.Enabled = True
cmdAdd.Enabled = False
cmdFirst.Enabled = False
cmdLast.Enabled = False
cmdNext.Enabled = False
cmdPrev.Enabled = False
cmdDelete.Enabled = False
cmdClose.Enabled = False
Text1.SetFocus
Adodc1.Recordset.AddNew
End Sub
Private Sub cmdCancel_Click()
On Error GoTo errMess
Adodc1.Recordset.CancelUpdate
ButtonSettings
Exit Sub
errMess:
MsgBox Err.Description, vbCritical
ButtonSettings
End Sub
Private Sub cmdClose_Click()
Unload Me
End Sub
Private Sub cmdDelete_Click()
msgRes = MsgBox("Are you sure?", vbQuestion + vbYesNo)
If msgRes = vbYes Then
Adodc1.Recordset.Delete
ButtonSettings
End If
End Sub
Private Sub cmdFirst_Click()
Adodc1.Recordset.MoveLast

SUBJECT: VISUAL BASIC 6.0


cmdFirst.Enabled = False
cmdPrev.Enabled = False
cmdNext.Enabled = True
cmdLast.Enabled = True
End Sub
Private Sub cmdLast_Click()
Adodc1.Recordset.MoveLast
cmdFirst.Enabled = True
cmdPrev.Enabled = True
cmdNext.Enabled = False
cmdLast.Enabled = False
End Sub
Private Sub cmdNext_Click()
Adodc1.Recordset.MoveNext
If Adodc1.Recordset.EOF Then
cmdLast_Click
Else
cmdFirst.Enabled = True
cmdNext.Enabled = True
cmdPrev.Enabled = True
cmdLast.Enabled = True
End If
End Sub
Private Sub cmdPrev_Click()
Adodc1.Recordset.MovePrevious
If Adodc1.Recordset.BOF Then
cmdFirst_Click
Else
cmdFirst.Enabled = True
cmdNext.Enabled = True
cmdPrev.Enabled = True
cmdLast.Enabled = True
End If
End Sub
Private Sub cmdSave_Click()
On Error GoTo errMess
Adodc1.Recordset.Update
ButtonSettings
Exit Sub

98/
98/119

SUBJECT: VISUAL BASIC 6.0

99/
99/119

errMess:
MsgBox Err.Description, vbCritical
End Sub
Private Sub Form_Load()
Adodc1.ConnectionString = "Provider=Microsoft.Jet.OLEDB.4.0;Data
Source=C:\Program Files\Microsoft Visual
Studio\VB98\Database\Nwind.mdb;Persist Security Info=False"
Adodc1.RecordSource = "Select * from Employees"
Set
Set
Set
Set
Set

Text1.DataSource
Text2.DataSource
Text3.DataSource
Text4.DataSource
Text5.DataSource

Text1.DataField
Text2.DataField
Text3.DataField
Text4.DataField
Text5.DataField

=
=
=
=
=

=
=
=
=
=

Adodc1
Adodc1
Adodc1
Adodc1
Adodc1

"FirstName"
"LastName"
"Address"
"BirthDate"
"HomePhone"

ButtonSettings
End Sub
Public Sub ButtonSettings()
On Error Resume Next
cmdAdd.Enabled = True
cmdClose.Enabled = True
cmdSave.Enabled = False
cmdCancel.Enabled = False
Adodc1.Recordset.MoveLast
Adodc1.Recordset.MoveFirst
If Adodc1.Recordset.RecordCount = 0 Then
cmdFirst.Enabled = False
cmdLast.Enabled = False
cmdNext.Enabled = False
cmdPrev.Enabled = False
cmdDelete.Enabled = False
ElseIf Adodc1.Recordset.RecordCount = 1 Then
cmdFirst.Enabled = False

SUBJECT: VISUAL BASIC 6.0


cmdLast.Enabled = False
cmdNext.Enabled = False
cmdPrev.Enabled = False
cmdDelete.Enabled = True
Else
cmdFirst.Enabled = False
cmdLast.Enabled = True
cmdNext.Enabled = True
cmdPrev.Enabled = False
cmdDelete.Enabled = True
End If
Text1.Locked
Text2.Locked
Text3.Locked
Text4.Locked
Text5.Locked
End Sub

=
=
=
=
=

100/
100/119

True
True
True
True
True

LECTURE 29-30
Cursor
In database technology, a piece of software that returns rows of data to the
requesting application. A cursor keeps track of the position in the result set, and
multiple operations can be performed row by row against a result set with or
without returning to the original table. In other words, cursors conceptually
return a result set based on tables within the databases. The cursor is so named
because it indicates the current position in the result set, just as the cursor on a
computer screen indicates current position.
Sets or returns the location of the cursor engine.
Settings And Return Values
Sets or returns a Long value that can be set to one of the following constants.
Constant

Description

AdUseNone

No cursor services are used. (This constant is


obsolete and appears solely for the sake of
backward compatibility.)

AdUseClient

Uses client-side cursors supplied by a local cursor


library. Local cursor engines often will allow
many features that driver-supplied cursors may
not, so using this setting may provide an
advantage with respect to features that will be

SUBJECT: VISUAL BASIC 6.0

101/
101/119

SUBJECT: VISUAL BASIC 6.0

enabled.
For
backward
compatibility,
the
synonym adUseClientBatch is also supported.
AdUseServer Default. Uses data-provider or driver-supplied
cursors. These cursors are sometimes very
flexible and allow for additional sensitivity to
changes others make to the data source.
However, some features of the Microsoft Client
Cursor
Provider
(such
as
disassociated
recordsets) cannot be simulated with server-side
cursors and these features will be unavailable
with this setting.

102/
102/119

all types of movement through the


recordset are allowed, except for
bookmarks if the provider doesn't
support them.
AdOpenStatic

Static cursor. A static copy of a set of


records that you can use to find data or
generate reports. Additions, changes, or
deletions by other users are not visible.

The CursorLocation property allows you to choose between various cursor


libraries accessible to the provider. Usually, you can choose between using a
client-side cursor library or one that is located on the server.
This property setting affects connections established only after the property has
been set. Changing the CursorLocation property has no effect on existing
connections.
This property is read/write on a Connection or a closed Recordset, and read-only
on an open Recordset.

Use the CursorType property to specify the type of cursor that should be used
when opening the Recordset object. The CursorType property is read/write when
the Recordset is closed and read-only when it is open.
Only a setting of adUseStatic is supported if the CursorLocation property is set
to adUseClient. If an unsupported value is set, then no error will result; the
closest supported CursorType will be used instead.
If a provider does not support the requested cursor type, the provider may
return another cursor type. The CursorType property will change to match the
actual cursor type in use when the Recordset object is open. To verify specific
functionality of the returned cursor, use the Supports method. After you close
the Recordset, the CursorType property reverts to its original setting.

The type of cursor used in a Recordset object.


Settings and Return Values
Sets or returns one of the following CursorTypeEnum values.

Indicates the type of locks placed on records during editing.


Settings and Return Values
Sets or returns one of the following LockTypeEnum values.

Constant

Constant

Description

AdLockReadOnly

Default. Read-onlyyou cannot alter


the data.

AdLockPessimistic

Pessimistic locking, record by record


the provider does what is necessary
to ensure successful editing of the
records, usually by locking records at
the data source immediately upon
editing.

AdLockOptimistic

Optimistic locking, record by record


the provider uses optimistic locking,
locking records only when you call the
Update method.

Description

AdOpenForwardOnly Forward-only cursor. Default. Identical


to a static cursor except that you can
only scroll forward through records. This
improves performance in situations
when you need to make only a single
pass through a recordset.
AdOpenKeyset

AdOpenDynamic

Keyset cursor. Like a dynamic cursor,


except that you can't see records that
other users add, although records that
other users delete are inaccessible from
your recordset. Data changes by other
users are still visible.
Dynamic cursor. Additions, changes, and
deletions by other users are visible, and

AdLockBatchOptimistic Optimistic batch updatesrequired


for batch update mode as opposed to

SUBJECT: VISUAL BASIC 6.0

103/
103/119

immediate update mode.


Set the LockType property before opening a Recordset to specify what type of
locking the provider should use when opening it. Read the property to return the
type of locking in use on an open Recordset object. The LockType property is
read/write when the Recordset is closed and read-only when it is open.
Providers may not support all lock types. If a provider cannot support the
requested LockType setting, it will substitute another type of locking. To
determine the actual locking functionality available in a Recordset object, use
the Supports method with adUpdate and adUpdateBatch.
The adLockPessimistic setting is not supported if the CursorLocation property is
set to adUseClient. If an unsupported value is set, then no error will result; the
closest supported LockType will be used instead.
Object Interface (ADODB)
Using ADO objects in VB brings in the real power. The objects that make up the
ADO object model are listed below.
Object
RecordSet
Connection
Command
parameter

error

Disrupter
Contains the records that made us the
resets of query
Allows control over the connection to
the data source.
field Executes database commands and
cursor determines errors from ADO.
Represents a piece of data in Recordset
works with the command object to set
up a parameters in a query or stored
procedure.

A reference to the project must be added to use these ADO objects, by choosing
projects. References place a check mark to the Microsoft. ActiveX Data objects
2.6 library and click the ok button.
Option Explicit
Dim msgRes As VbMsgBoxResult
Dim cn As New ADODB.Connection
Dim rs As New ADODB.Recordset
Private Sub cmdAdd_Click()
Text1.Locked = False
Text2.Locked = False

SUBJECT: VISUAL BASIC 6.0


Text3.Locked = False
Text4.Locked = False
Text5.Locked = False

104/
104/119

cmdSave.Enabled = True
cmdCancel.Enabled = True
cmdAdd.Enabled = False
cmdFirst.Enabled = False
cmdLast.Enabled = False
cmdNext.Enabled = False
cmdPrev.Enabled = False
cmdDelete.Enabled = False
cmdClose.Enabled = False
Text1.Text = ""
Text2.Text = ""
Text3.Text = ""
Text4.Text = ""
Text5.Text = ""
Text1.SetFocus
rs.AddNew
End Sub
Private Sub cmdCancel_Click()
On Error GoTo errMess
rs.CancelUpdate
ButtonSettings
Exit Sub
errMess:
MsgBox Err.Description, vbCritical
ButtonSettings
End Sub
Private Sub cmdClose_Click()
Unload Me
End Sub
Private Sub cmdDelete_Click()
msgRes = MsgBox("Are you sure?", vbQuestion + vbYesNo)
If msgRes = vbYes Then
rs.Delete
ButtonSettings
RecordPrint

SUBJECT: VISUAL BASIC 6.0


End If
End Sub
Private Sub cmdFirst_Click()
rs.MoveFirst
RecordPrint
cmdFirst.Enabled = False
cmdPrev.Enabled = False
cmdNext.Enabled = True
cmdLast.Enabled = True
End Sub

105/
105/119

SUBJECT: VISUAL BASIC 6.0


RecordPrint
End If
End Sub

106/
106/119

Private Sub cmdSave_Click()


On Error GoTo errMess
rs!FirstName = Text1.Text
rs!LastName = Text2.Text
rs!Address = Text3.Text
rs!BirthDate = Text4.Text
rs!HomePhone = Text5.Text

Private Sub cmdLast_Click()


rs.MoveLast
RecordPrint
cmdFirst.Enabled = True
cmdPrev.Enabled = True
cmdNext.Enabled = False
cmdLast.Enabled = False
End Sub

rs.Update
ButtonSettings
RecordPrint
Exit Sub

Private Sub cmdNext_Click()


rs.MoveNext
If rs.EOF Then
cmdLast_Click
Else
cmdFirst.Enabled = True
cmdNext.Enabled = True
cmdPrev.Enabled = True
cmdLast.Enabled = True
RecordPrint
End If
End Sub

Private Sub Form_Load()


cn.Open
"Provider=Microsoft.Jet.OLEDB.4.0;Data
Source=C:\Program
Files\Microsoft
Visual
Studio\VB98\Database\Nwind.mdb;Persist
Security
Info=False"

Private Sub cmdPrev_Click()


rs.MovePrevious
If rs.BOF Then
cmdFirst_Click
Else
cmdFirst.Enabled = True
cmdNext.Enabled = True
cmdPrev.Enabled = True
cmdLast.Enabled = True

errMess:
MsgBox Err.Description, vbCritical
End Sub

rs.CursorType = adOpenDynamic
rs.LockType = adLockOptimistic
rs.ActiveConnection = cn
rs.Open "Select * from Employees"
'or: rs.open "Select * from Employees",cn,adOpenDynamic,adLockOptimistic
RecordPrint
ButtonSettings
End Sub
Public Sub ButtonSettings()
On Error Resume Next
cmdAdd.Enabled = True
cmdClose.Enabled = True
cmdSave.Enabled = False
cmdCancel.Enabled = False

SUBJECT: VISUAL BASIC 6.0


rs.MoveLast
rs.MoveFirst
If rs.RecordCount = 0 Then
cmdFirst.Enabled = False
cmdLast.Enabled = False
cmdNext.Enabled = False
cmdPrev.Enabled = False
cmdDelete.Enabled = False
ElseIf rs.RecordCount = 1 Then
cmdFirst.Enabled = False
cmdLast.Enabled = False
cmdNext.Enabled = False
cmdPrev.Enabled = False
cmdDelete.Enabled = True
Else
cmdFirst.Enabled = False
cmdLast.Enabled = True
cmdNext.Enabled = True
cmdPrev.Enabled = False
cmdDelete.Enabled = True
End If
Text1.Locked
Text2.Locked
Text3.Locked
Text4.Locked
Text5.Locked
End Sub

=
=
=
=
=

True
True
True
True
True

Public Sub RecordPrint()


Text1.Text = rs!FirstName
Text2.Text = rs!LastName
Text3.Text = rs!Address
Text4.Text = rs!BirthDate
Text5.Text = rs!HomePhone
End Sub

LECTURE 31
DBGrid Control

107/
107/119

SUBJECT: VISUAL BASIC 6.0


108/
108/119
The DBGrid control displays retrieved data. It can hold text data, but not linked
or embedded objects. The AllowAddNew, AllowDelete, and AllUpdate properties
allow the DBGrid to modify data.
DataGrid Control
Displays and enables data manipulation of a series of rows and columns
representing records and fields from a Recordset object.

The data-aware DataGrid control appears similar to the Grid control; however,
you can set the DataGrid control's DataSource property to a Data control so
that the control is automatically filled and its column headers set automatically
from a Data control's Recordset object. The DataGrid control is really a fixed
collection of columns, each with an indeterminate number of rows.
Each cell of a DataGrid control can hold text values, but not linked or
embedded objects. You can specify the current cell in code, or the user can
change it at run time using the mouse or the arrow keys. Cells can be edited
interactively, by typing into the cell, or programmatically. Cells can be selected
individually or by row.
If a cell's text is too long to be displayed in the cell, the text wraps to the next
line within the same cell. To display the wrapped text, you must increase the
cell's Column object's Width property and/or the DataGrid control's
RowHeight property. At design time, you can change the column width
interactively by resizing the column or by changing the column's width in the
Column object's property page.
Use the DataGrid control's Columns collection's Count property and the
Recordset object's RecordCount property to determine the number of
columns and rows in the control. A DataGrid control can have as many rows as
the system resources can support and up to 32767 columns.
When you select a cell, the ColIndex property is set, thus selecting one of the
Column objects in the DataGrid object's Columns collection. The Text and
Value properties of the Column object reference the contents of the current
cell. The data in the current row can be accessed using the Bookmark property,
which provides access to the underlying Recordset object's record. Each
column of the DataGrid control has its own font, border, word wrap, and other
attributes that can be set without regard to other columns. At design time, you

SUBJECT: VISUAL BASIC 6.0


109/
109/119
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.
Note: If you use the Move method to position the DataGrid control, you
may need to use the Refresh method to force it to repaint.
The DataGrid control functions similarly to the DBGrid control except that
it doesn't support an unbound mode.
MSFlexGrid Control
The Microsoft FlexGrid (MSFlexGrid) control displays and operates on tabular
data. It allows complete flexibility to sort, merge, and format tables containing
strings and pictures. When bound to a Data control, MSFlexGrid displays readonly data.
You can put text, a picture, or both, in any cell of an MSFlexGrid. The Row and
Col properties specify the current cell in an MSFlexGrid. The Text property
references the contents of the current cell. If the text in a cell is too long to
display in the cell, and the WordWrap property is set to True, the text wraps to
the next line within the same cell. To display the wrapped text, you may need to
increase the cells column width (ColWidth property) or row height (RowHeight
property).
Use the Col and Row properties to determine the number of columns and rows
in an MSFlexGrid.

LECTURE 32-33

SUBJECT: VISUAL BASIC 6.0


110/
110/119
Drag-and-drop functionality that allows you to drag fields and tables from
your Data Environment designer onto a form or the Data Report ActiveX
designer. Data-bound controls are automatically created on the form. You
can also specify the default control type that is created.
Execution of commands included in your Data Environment as
programmatic run-time methods.
Programmatic access to a Data Environment that is bound to controls on a
form without a variable reference, such as moving to a new record.
The ability to relate Command objects to create a relation hierarchy, or to
group Command objects to create a grouped hierarchy.
The ability to create aggregates that automatically calculates values within
any Command hierarchy.
The ability to manually bind data-aware controls to Field objects within a
Command object.

To add a Data Environment designer object to a new Visual Basic


project
1. From the New tab of the New Project dialog box, choose Standard EXE
project, and then click Open.
2. From the Project menu, choose More ActiveX Designer
Add Data
Environment.
The Data Environment designer is added to your Visual Basic project, the
Data Environment designer window appears, and a Connection object is
added to your Data Environment.

Designing a DataEnvironment Object

Connection Objects

At design time, you can use the Data Environment designer to create a
DataEnvironment object. The DataEnvironment object can include Connection
and Command objects, hierarchies (relationships between Command objects),
groupings, and aggregates. Before designing your DataEnvironment object, you
should determine what information you want to present, identify the databases
that contain the information, and determine your run-time objective (for
example, creating a Data Report or Hierarchical FlexGrid control).
Before you can access the Data Environment designer, you must reference it in
Visual Basic.

To access data using your Data Environment, you must create a Connection
object. Therefore, every Data Environment should include at least one
Connection object. A Connection object represents a connection to a remote
database that is used as a data source.
Upon adding a Data Environment to your Visual Basic project, the Data
Environment designer automatically includes a new connection, called
Connection1. At design time, the Data Environment opens the connection and
obtains metadata from the connection, including database object names, table
structures, and procedure parameters.

The Data Environment designer supports:


Multiple Connection objects that allow you to access multiple data sources
within a single Data Environment.
Connection and Command objects that you can organize by either
connection or object.
OLE DB data sources, as well as ODBC data sources.

Creating a Connection Object


The Add Connection function is available at all times and is independent of the
existence of other objects.
To create a database connection
Click Add Connection on the Data Environment designer toolbar.
-or

SUBJECT: VISUAL BASIC 6.0


111/
111/119
Right-click your Data Environment designer and select Add Connection
from the shortcut menu.
To set the Connection Name and Data Source
In the Visual Basic Properties window, change the default Name to a
more meaningful name for your data source database.
Right-click the Connection object and choose Properties to access the
Data Link Properties dialog box.
From the Data Link Properties dialog box, specify the connection
information on the Provider and Connection tabs. This is typically a
database that contains data or stored procedures. You may select only one
source for each Connection object.
Click OK to apply the properties and close the dialog box.

Create the Command Object


Command objects define specific detailed information about what data is
retrieved from a database connection. Command objects can be based on either
a database object (such as a table, view, stored procedure or synonym) or a
Structured Query Language (SQL) query.
To add a Command object
Click Add Command in the Data Environment designer toolbar.
-or
Right-click a Connection object, or your Data Environment designer, and
choose Add Command from the shortcut menu.
To specify Command object properties
Right-click the Connection object and choose Properties to access the
Command Properties dialog box.
Click the General tab, and set the following:
Item

Purpose

Command
Name

Change the default Command Name to a more


meaningful name for your database object.

Connection

If the Command object was created from a Connection


object's shortcut menu, the Connection name is
automatically set. However, you can change this
connection.

Database
Object

Select the type of database object from the drop-down


list. This can be a stored procedure, synonym, table, or
view.

Object Name

Select an object name from the drop-down list. The

SUBJECT: VISUAL BASIC 6.0

112/
112/119

listed objects are from the connection and match the


selected Database Object type.
or
SQL Statement

If this is selected as your data source, type an SQL


query that is valid for your database in the SQL
Statement box.

If the Command object is based on a parameterized query or a stored


procedure, it may have a parameters collection. To set the parameter
properties, click the Parameters tab in the Command Properties dialog
box.
Use the Relation, Grouping, and Aggregates tabs to define relationships
and shape the data included in the Recordset.
Click the Advanced tab in the Command Properties dialog box to set
the properties that change how the data is retrieved or manipulated at run
time.
Click OK to apply the properties to the new Command object and close the
dialog box.

Microsoft Data Report Designer


The Microsoft Data Report designer is a versatile data report generator that
features the ability to created banded hierarchical reports. Used in conjunction
with a data source such as the Data Environment designer, you can create
reports from several different relational tables. In addition to creating printable
reports, you can also export the report to HTML or text files.
Possible Uses
Automatically create reports that are exported in HTML format for instant
distribution on the Internet.
Create reports that show the sums of transactions occurring on a daily
basis.

Data Report Designer Features


The Data Report designer has several features:
1. Drag-and-Drop Functionality for FieldsDrag fields from the Microsoft
Data Environment designer to the Data Report designer. When you do this,
Visual Basic automatically creates a text box control on the data report and
sets the DataMember and DataField properties of the dropped field. You
can also drag a Command object from the Data Environment designer to
the Data Report designer. In that case, for each of the fields contained by
the Command object, a text box control will be created on the data report;

SUBJECT: VISUAL BASIC 6.0


113/
113/119
the DataMember and DataField property for each text box will be set to the
appropriate values.
2. Toolbox ControlsThe Data Report designer features its own set of
controls. When a Data Report designer is added to a project, the controls
are automatically created on a new Toolbox tab named DataReport. Most
of the controls are functionally identical to Visual Basic intrinsic controls,
and include a Label, Shape, Image, TextBox, and Line control. The
Function Control automatically generates one of four kinds of information:
Sum, Average, Minimum, or Maximum.
3. Print PreviewPreview the report by using the Show method. The data
report is then generated and displayed in its own window.
4. Print ReportsPrint a report programmatically by calling the PrintReport
method. When the data report is in preview mode, users can also print by
clicking the printer icon on the toolbar.
5. File ExportExport the data report information using the ExportReport
method. Formats for export include HTML and text.
6. Export TemplatesYou can create a collection of file templates to be
used with the ExportReport method. This is useful for exporting reports in
a variety of formats, each tailored to the report type.
7. Asynchonous OperationThe DataReport object's PrintReport and
ExportReport methods are asynchronous operations. Using the
ProcessingTimeout event, you can monitor the state of these operations
and cancel any that are taking too long.
The DataReport designer works in bound mode only, in the sense that it's able
to automatically retrieve the data to be sent to the printer or simply displayed in
the preview window. It can export a report to a text file or an HTML file and also
supports custom format layouts. The DataReport designer comes with a set of
custom controls that you can drop on its surface in the same way as you do with
forms and other designers. These controls include lines, shapes, images, and
also function fields, which you can use to create summary fields in your reports.
Another intriguing feature of this designer is its ability to print in asynchronous
mode, which lets the user perform other tasks while the printing proceeds.

Design-Time Operations
The simplest way to create a report using the DataReport designer is in
conjunction with the DataEnvironment designer. The DataReport designer
supports drag-and-drop operations of DataEnvironment's Command objects,
including hierarchical Command objects. The only limitation is that the report
can account for just one child Recordset at each nesting level. For all the
examples in this chapter, I'll use a hierarchical Command object based on the
Orders and Order Details tables in the NWind.mdb database.

Binding to a Command object

SUBJECT: VISUAL BASIC 6.0


114/
114/119
Here are the steps you should follow to create a report based on the sample
hierarchical Command object:
Create a hierarchical Command, named Orders, that contains a child Command
named Order Details. Ensure that it retrieves the information you're interested
infor example, by binding it to a Hierarchical FlexGrid control on a form and
running the application.
Create a new instance of the DataReport designer, or use the one provided by
default with a Data Project type of Visual Basic project.
Bring up the Properties window, let the DataReport's DataSource property point
to DataEnvironment1 (or whatever the name of your DataEnvironment is), and
then set its DataMember property to Orders.
Right-click on the Report Header of the DataReport designer, and select the
Retrieve Structure menu command; this will create a Group Header and Group
Footer section labeled Orders_Header and Orders_Footer, respectively; between
them is a Detail section labeled Order_Details_Detail.
A section represents a block of data that will be repeated for each record in the
parent Command object. The first section corresponds to the parent Command
object, the second section to its child Command, and so on until you reach the
Detail section, which corresponds to the innermost Command object. All the
sections except the Detail section are divided into a header section and a footer
section, which are printed before and after the information related to the
sections pertaining to objects at an inner level. The DataReport designer also
includes a Report section (which prints information at the beginning and end of
the report) and a Page section (which prints information at the beginning and
end of each page). If you don't see these two sections, right-click anywhere on
the DataReport designer and select the appropriate menu command.
Drag the fields you need from the Orders Command object in the
DataEnvironment to the Orders_Header section of the DataReport. Whenever
you release the mouse button, a pair of controls, RptLabel and a RptTextBox,
appear in the DataReport. When the report is eventually displayed, the RptLabel
control produces a constant string with the name of the field (or whatever you
assigned to its Caption property), while the RptTextBox control is replaced by
the actual contents of the corresponding database field. You can then arrange
the fields in the Orders_Header section and delete the RptLabel controls that
you don't want to display.
Click on the Order Details Command object and drag it onto the DataReport;
Visual Basic creates one RtpLabel-RptTextBox control pair for each field in the
corresponding Recordset. You can then delete the OrderID field and arrange the
others in a row, as displayed in Figure below.

SUBJECT: VISUAL BASIC 6.0


115/
115/119
Adjust each section's height so that it doesn't take more room than strictly
necessary. This is especially important for the Detail section, because it will be
repeated for each single record in the Order Detail table. You can also reduce all
the sections that don't contain any fields to a null height.
What you've done so far is sufficient to see the DataReport in action. Bring up
the Project Property Pages dialog box, select DataReport1 as the startup object,
and then run the program.

SUBJECT: VISUAL BASIC 6.0


116/
116/119
Wizard either as an add-in in Visual Basic or as a standalone. To run it as an
add-in, use the Add-In Manager (select Add-In Manager from the Add-Ins menu
in Visual Basic) to load the PD Wizard. Load the project you want to
package/distribute into Visual Basic, then run the PD Wizard from the Add-Ins
menu. To run it as a standalone, execute the file PDCMDLN.EXE. In either case,
when the program starts, youll see the opening screen shown in Figure 26.5.

As the name suggests, the


PD
Wizard has two functions:
Packaging
your
programDetermining
which
files
are
needed
and
combining them and the
setup
program into a compressed
form.
Packaging can also include
the
process
of
copying
distribution
files
to
diskettes.
Deploying this package
Moving
it to a network or Internet
site
where people can access it.
These two functions are accessed via the corresponding buttons on the PD
Wizards opening screen. The third button, Manage Scripts, is used to work with
scripts that let you automate some of the PD Wizards functions for repetitive
tasks. I will not be dealing with script management in this book.

Figure 15-8. The DataReport designer at design time, with the pop-up
menu that appears when you right-click on a control.

Lecture 34
The Package And Deployment Wizard
The Package and Deployment Wizard (or PD Wizard) is on the same level as
sliced bread and indoor plumbing in terms of being a great thing. Assembling all
the files needed to distribute your Visual Basic application and packaging them
for distribution would be a miserable task without this tool. You can run the PD

Packaging Your Application


You have several distribution options when packaging your application:
Distributing the program on multiple diskettes, splitting files that are too
large to fit onto a single diskette.
Placing the distribution files in a hard-disk directory for distribution over a
network or mastering onto CD-ROM.
Distributing your application across the Internet using the automatic code
download capability of Microsoft Internet Explorer.
To start creating your distribution package, load the desired project.
Recompiling your project to an EXE (or whatever the target is) is a good idea,
because the PD Wizard requires up-to-date files before it can do its job. If the
wizard detects out-of-date or unsaved files, it will prompt you to correct the
situation before continuing.
Next, start the PD Wizard and click on the Package button. Youll be offered a
choice of package types. The types available will depend on the type of project:

SUBJECT: VISUAL BASIC 6.0


117/
117/119
Standard Setup PackageThe correct choice for EXE projects and any other
type of project that will be installed with a setup program and distributed on
disks or on a local network.
Internet PackageAvailable only for ActiveX projects. It creates a package
that will be installed by downloading
from an
Internet site.
On the next screen, shown in Figure
26.6,
you select a folder where the PD Wizard
will
place the setup package. Placing each
package
in its own folder is advisable to avoid
confusion. Click on the Network button
to select
a folder on the network (assuming, of course, that you are connected to one).
Click on the New Folder button to create a new folder with a name different from
the one suggested by the PD Wizard.

The next screen (Figure 26.7) lists all of the files the PD Wizard will include in
your setup package. To add files,
click on
the Add button. Files you might
need to
add include a READ.ME file, help
files,
licensing information, and the
like.
You should never need to add an
actual
program component, because the
PD
Wizard will have already included
all
required items. You can also
remove
a file from the distribution
package
by clearing the checkbox next to
its
name in the list. I strongly
suggest
that you never do this, because
the files
included in the list are required for your application to install and run correctly.
The next screen lets you select whether your package will be compressed into a
single cab file (a cab file, short for cabinet, is a type of compressed file used by
Microsoft for program distribution) or into multiple cabs. If you select multiple
cabs, you can also select the maximum size for each file to match the
distribution media. For example, select 1.44MB if your program will be
distributed on standard high-density diskettes.
The next few screens let you select options, such as the name your program will
be assigned when it is installed and the location of the program on the users
Start menu. You can make your selections, using the PD Wizard prompts to help
you if needed. When asked whether to designate shared files, accept the default

SUBJECT: VISUAL BASIC 6.0


118/
118/119
settings, unless you have a specific reason to change them. The final screen lets
you enter a name for the setup script. All the choices you made will be saved in
this script. Then, the next time you run the wizard to package this application,
you can reload the script to save time.
The last step is to click on Finish. The PD Wizard will create the distribution files
in the specified folder and display a summary report. All you need to do is copy
the resulting files (SETUP.EXE, one or more cab files, and SETUP.LST) to the
distribution disks, and you are ready to start distributing your program. If you
will be distributing the program via the Internet or a network, youll use the
deployment part of the wizard next to deploy the files.

Deploying Your Application


If your package will not be distributed on disks, the next step is to deploy it
copy it to a Web server or folder. The first option is most useful, as the PD
Wizard will actually log onto the desired Web site and upload files. Deploying to
a folder is useful only if your computer is itself the Web server or if you want to
upload the files manually at a later time.
To deploy a package, start the PD Wizard and click on the Deploy button. On the
first screen, you can either load a deployment script or select (none) if you are
starting a new deployment. Next, select the package to deploy and choose
between Web publishing and folder deployment. For folder deployment, the only
remaining task is to select the destination folder. Web publishing has a few
more steps on subsequent PD Wizard screens:
1. Select the files to deploy. You should not remove any of the automatically
selected files unless you are sure of what you are doing. Add files, such as
READ.ME documents, as needed.
2. Specify the destination URL and publishing protocol . The URL is, of course,
the destination for the package (for example, http://www.yoursite.com/).
For the protocol, select either HTTP Post or FTP, depending on what the
destination server supports. The end result is the same in either case.
Select the Unpack and Install Server-Side cab only if necessaryfor
example, if deploying a DHTML application. Note that the protocol specified
in the URL (HTTP:// or FTP://) must match the publishing protocol
selected.
3. Next you will be asked whether to save the URL and publishing protocol in
the registry as a Web Publishing Site. Select Yes, then specify a name for
this site.
4. Enter a name for the deployment script. All of the information you entered
will be saved and can be recalled again if you need to redeploy the same
package.

SUBJECT: VISUAL BASIC 6.0


119/
119/119
5. Click on Finish. The PD Wizard will begin the deployment procedure. You
may be asked for a logon and password, depending on the security
measures in effect at the destination site. When the process is complete,
the wizard will display a report detailing which files were uploaded, any
errors that were encountered, and so on.

Potrebbero piacerti anche