0% found this document useful (0 votes)
13 views126 pages

Visual Basic 6.0 Programming Guide

The document provides an overview of Visual Basic 6.0, including its programming environment, integrated development environment (IDE), and various components such as the toolbox, project explorer, and properties window. It explains how to work with forms, set properties, and develop applications through visual and code programming steps. Additionally, it covers creating executable files and the organization of code within modules.
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
13 views126 pages

Visual Basic 6.0 Programming Guide

The document provides an overview of Visual Basic 6.0, including its programming environment, integrated development environment (IDE), and various components such as the toolbox, project explorer, and properties window. It explains how to work with forms, set properties, and develop applications through visual and code programming steps. Additionally, it covers creating executable files and the organization of code within modules.
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

Visual Basic Lesson Notes - Unit I

Getting Started with VB 6.0


1.1 Visual Basic 6.0 Programming Environment
Visual Basic is an ideal programming language for developing sophisticated professional
applications for MS Windows. Visual Basic was developed from the programming language BASIC in
the 1970s, Microsoft started developing ROM-based interpreted BASIC for the early microprocessor-
based computers. In 1982, MS QuickBasic revolutionized BASIC and was legitimated as a serious
development language for MS-DOS environment. VB 6.0 for Windows requires at least Microsoft
Windows 95 or later versions of Windows.

VB is imitated by using the Start → All Programs → MS Visual Studio → MS Visual Basic
6.0. By Clicking the VB 6.0 icon in Desktop it can be opened. Below Figure shows the interface screen of
VB 6.0 with Menu bar, Toolbar and etc.

The Integrated Development Environment (IDE)


The VB IDE is made up of a number of components such as Menu Bar, Toolbar, Project Explorer,
Properties Windows, Form Layout Window, Toolbox, Form Designer and Object Browser. In earlier
versions, IDE was designed as a Single Document Interface (SDI), but in VB 6.0, the IDE is in a Multiple
Document Interface (MDI) format. In this format, the windows associated with the project will stay
within a single container known as the parent.
Menu Bar
Menu Bar displays the commands that are required to build an application. The main menu items
have sub menu items that can be chosen when needed. The toolbars in the menu bar provide quick access
to the commonly user commands and a button in the toolbar is clicked once to carry out the action
represented by it.

Department of Computer Science, HiSAC, Erode 1


Visual Basic Lesson Notes - Unit I

Toolbar Action Toolbar Action


Button Button
Adds a New Form Adds a New Module

Opens an existing Project Saves the current Project

Locks and Unlocks the command Display the Properties Window


controls
Display the Object Browser Displays the Project Explorer

Starts an application in design mode Used for debugging, stops execution of


a program while running
Stops execution of an application Toggles breakpoint on menu
and returns to the design mode
Displays the value of the current Traces through each line of code and
selection in the code window steps into procedures
Executes one code procedure or Displays the Menu Editor
statement at a time in the Code
window.
DataView window Visual Component Manager

Toolbox
Toolbox contains a set of controls that are used to place on a form at design time thereby creating
the user interface area. Additional controls can be included in the toolbox by using the Components menu
item on the Project menu. A toolbar is shown in the below.
Pointer PictureBox

Label Textbox
Frame CommandButton
CheckBox Option Button
ComboBox List Box
Hscroll Bar VScrollBar
Timer Drive ListBox
DirListBox FileListBox
Shape Line
Image Data

OLE

Department of Computer Science, HiSAC, Erode 2


Visual Basic Lesson Notes - Unit I

• The pointer helps to move and resize the controls and Forms
• Label displays a text that the user cannot modify or interact with.
• Frame control serves as a visual and functional container for controls.
• CheckBox displays a True/False or Yes/No option.
• TextBox is a control used to display message and enter text.
• The ListBox displays a list of items from which a user can select one.
• ComboBox contains a TextBox and a ListBox. This allows the user to select an item from the
dropdown ListBox or to type a selection in the TextBox.
• HScrollBar or VScrollBar controls allow the user to select a value within the specified range of values.
• Timer control executes timer events at specified intervals of time.
• DirListBox allows the user to select directories and paths, which are displayed.
• Shape control adds a shape to a Form.
• Image control is used to display icons, bitmaps, metafiles, etc.
• OLE control is used to link or embed an object, display and manipulate data from other Windows
based applications
• PictureBox displays icons/bitmaps and metafiles. It display text or acts as a visual container for other
controls.
• CommandButton carries out the specified action when the user chooses it.
• The OptionButton control which is a part of an option group allows the user to select one option even
if it displays multiple choices.
• The DriveListBox displays the valid disk drives and allows the user to select one of them.
• The FileListBox displays a set of files from which a user can select the desired one.
• Line controls draws a straight line to the Form.
• Data control enables the user to connect to an existing database and display information from it.
Form serves as a window that can be customized and controls, graphics and pictures can also be
added to it.

Project Explorer
The project explorer serves as a quick reference to the various elements of a project namely form,
classes and modules. All of the objects that make up the application are packed in a project. A typically
project contains one form, which is a window that is designed as part of the program’s interface.

Properties Window
The Properties window exposes the various characteristics of selected objects. Each and every
Form in an application is considered an object. All the characteristics of an object are called its properties.

Object Browser
The object Browser allows browsing through the various properties, events and methods that are
made available to us. It is accessed by selecting Object Browser from the View menu or by pressing F2.

Properties, Methods and Events


All the controls in the Toolbox except the Pointer are objects in VB. These objects have associated
properties, methods and events.

A property is a named attribute of a programming object. Properties define the characteristic of an


object such as size, color, etc. or sometimes the way in which it behaves. For example, a TextBox accepts

Department of Computer Science, HiSAC, Erode 3


Visual Basic Lesson Notes - Unit I

properties such as Enabled, Font, Multi Line, Text, Visible, etc. A method is an action that can be
perfomed on objects. The TextBox has associated with Refresh, SetFocus etc.

VB programs are built around Events. Events are various things that can happen in a program. In
an event driven application, the program statements are executed only when calls a specific part of the
code that is assigned to the events.

1.2 Working with Forms


Visual Basic has several different types of objects. A Form is one of the most basic objects in
which the application code and has other objects placed on it to create the user interface. A From may fill
the entire screen or have other Forms contained within it or it may be a custom dialog box. VB initially
includes a default form, Form1 file in each new project. User can change the form’s name and caption to
identify the purpose of the Form. Every Form object has its own properties, events and methods
associated with it.

Setting Form Properties


Any VB application program uses the Form to gather input from the user and to display the output
information to the user. Various Form properties are discussed below.

Border Style
Forms can have a variety of types of borders. Various borders that are available in VB are Name,
Fixed Single, Sizeable, Fixed Double, Fixed ToolWindow and Sizeable ToolWindow.

Caption
The title for the window is stored in the Caption property, the caption appears below the form’s
icon when the form is minimized.

Control Box
This property determines whether the Control box, available by clicking the upper left corner of a
window, will be shown or not.

Icon
This property specifies the icon for the window in the upper left corner of the window.

MousePointer
This property sets the value that indicates the type of mouse pointer displayed when the mouse
pointer appears over a particular area of the object at runtime.

MaxButton
This property indicates Whether the Maximize button should be shown and the Maximize choice
made available in the Control Box menu.

MDIChild
This property specifies if this window must be shown within a multiple document interface (MDI)
window.

Department of Computer Science, HiSAC, Erode 4


Visual Basic Lesson Notes - Unit I

MinButton
This property indicates whether the Minimize button should be shown and the Minimize choice
made available in the Control Box menu.

Moveable
By setting it to False, it is possible to prevent the user from moving the window manually. This is
useful for splash screens and other informational dialog boxes that are shown and dismissed quickly.

StartUpPosition
Instead of writing code to position user window, user can pick a starting position from this drop-
down menu. The available choices are Manual, CenterOwner, CenterScreen and Windows Default.

WindowState
This property indicates whether the window is shown normally, maximized or minimized. It is
possible to pick a starting state for your Form at design time so that when you show the window, it comes
up in that state.

Show Method
The Show method is used to display the Form object. For example, to display the form
frmCalculator, the following code is written.
[Link]

Using Load Statement


The Load statement is used to load a form or control into memory but does not display it. To load
the form frmCalculator, the following code should be entered.
Load frmCalculator

Using the Hide Method


The hide method hides a Form. For example, the following codes hides From object
frmCalculator
[Link]

Using the Unload Statement


The Unload statement removes the form from the display and releases its memory. The following
code should be entered to unload the frmCalculator from memory.
unload frmCalculator

Using the Unload Event


The Unload event procedure is used to verify that the form should be unloaded or specific actions
that have to take place when the form is unload. The unload events occurs when.
• The Form is unloaded using the Unload statement.
• The Form is closed by the user either clicking the Close command on the application menu or clicking
the Close button on the application title bar.

Department of Computer Science, HiSAC, Erode 5


Visual Basic Lesson Notes - Unit I

Setting Run Time and Design Time Properties


Many properties can be set at either design time or runtime, at design time, the controls are added
to a project, their properties set and the relevant code is written. During runtime, user examines the
program in action, just as the end user will eventually see it.
To set a property at design time, the following steps are followed.
• Select control or object whose characteristics are to be changed.
• Activate the Properties window.
• Scroll to the property user want to set and select its name.
• Enter a new setting.
At runtime, property settings can be changed by a program's code. This is accomplished by writing
a special kind of assignment statement that gives a new value to a specific property of a selected object.
[Link] = value
The left side of this assignment statement, [Link] is a compound name identifying the
object and the property that is to be reset. The value on the right side of the statement gives the new
setting. When a program resets a property at runtime, the new setting overrides the value assigned at
design time. Design time settings need not be permanent during a program run.
Example: The following example illustrates how the Caption, MousePointer, WindowState, Height and
Width properties for a form object are set at runtime.
Private Sub Form_Load()
[Link] = vbHourglass
[Link] = “Simple Application”
[Link] = vbNormal
[Link] = 5000
[Link] = 5000
End Sub

1.3 Developing an Applications


An application can be created with the project. A project is a [Link] of files that are used to
build an application. Writing a Visual Basic program involves the following two steps.
• Visual programming step
• Code programming step
Visual programming step involves designing an application with various tools that come along with the
Visual Basic package. Code programming step involves writing programs using a text editor. The
program window resembles as shown in the below figure comprising three CommandButton controls that
perform specific actions represented by their captions and an empty TextBox. The Display button displays
specified message and Clear button clears the message in the TextBox. The Exit button terminates the
application. Let us consider a simple display program using the TextBox control in this example.

A New Standard EXE Project item is selected from the File menu that displays a New Project
dialog box. The standard EXE is chosen for normal applications. Visual Basic responds by displaying the
Project and Form windows. Though no change have made to the Form, it is better to save the project at
the early stage of the design. When a project is saved, two files are saved, namely Project file and Form
file. The project file has .VBP extension and its contains information that VB uses for building the
project. The Form file contains information about from and has .FRM extension. The Save Project
command is selected from the File Menu. VB responds by displaying a Save File As dialog box. A file
name called [Link] is given and Save button has to be clicked on. VB than display a Save Project As
dialog box. The project file is saved as [Link].

Department of Computer Science, HiSAC, Erode 6


Visual Basic Lesson Notes - Unit I

Examining the Project Window


At this Stage, project consists of a single Form. In order to examine the Project window, Project
Explorer command is selected from the View menu. It displays the Project window with the Form.

Changing properties and Adding Controls


The next step is to add the controls and set their properties. The application is designed as per the
specifications given in the below Table.
Object Property Setting
Form Caption The Display Program
Name FrmDisplay
CommandButton Caption &Exit
Name cmdExit
CommandButton Caption &Clear
Name cmdCtear
CommandButton Caption &Display
TextBox Name Txt Display

Changing the Properties of Form


In order to change the property of the Form, click anywhere on it and press F4 or select Properties
window from the View menu. We can change the Caption and Name in the Properties window as given
in the above Table. The CommandButton control is added by double clicking it in the Toolbox, which
places it in the centre of the Form. It can then be dragged and dropped at the required location. It has a
caption Command1. Now the properties are set in the Properties window according to the specifications
given in the above Table. The same step is followed for the other controls. Property window displays the
properties alphabetically and in a categorized form with a description pane at the bottom.

Adding Code for the Program


The visual programming step is now completed and selecting Save Project command from the
File menu saves the work. The next step is the code programming step. Visual Basic code is written in the
Code window that consists of an Object box and Procedure list box. The Object box displays the name of
the selected object associated with the Form. The Procedure list box lists the procedures for an object such
as click, double-clicks, etc. An event procedure is written in the Code window that combines the control’s
name, which is listed in the ListBox, an underscore and the event name. The Code window is viewed by
selecting View Code from the Project window or by selecting Code from the View menu or
pressing F7.

Department of Computer Science, HiSAC, Erode 7


Visual Basic Lesson Notes - Unit I

Code editor window includes List Properties/Methods which presents a list of properties available
for controls.

The application is run by clicking Start command form the Run menu or Pressing F5. When the
Display button is clicked the message Visual Basic 6 is displayed in the TextBox. Clicking the Clear
button clears the message, while button terminates the application.

Creating an Executable File


We can create an executable file in Visual Basic by choosing Make EXE File command in the File
menu. A Make EXE dialog box appears. Now the file is saved as [Link] in the required directory or
hard-disk and the OK button is clicked. As the application is converted into an executable file the user can
run it on any other Windows program.

Ending an Application
The End statement is used to terminate the execution of the application. It unloads all the forms
from memory.

1.4 Variables Data Types and Modules


Modules
Code in Visual Basic is stored in the form of module. The three kinds of modules are Form
modules, Standard modules and Class modules. A simple application may contain a single Form and the
code resides in that Form module itself. As the application grows, additional Forms are added and there
may be a common code to be executed in several Forms. To avoid duplication of Code, a separate module
containing a procedure is created that implements the common code. This is a Standard module.

Class modules (.CLS filename extension) are the foundation of object oriented programming in VB.
New objects can be created by writing code in class modules. Each module can contain:
➢ Declaration
May include constant, type, variable and DLL procedure declarations.
➢ Procedure
A sub function or property procedure that contains piece of code that can be executed as a unit

Data Types
By default Visual Basic variables are of the variant data type. The variant data type can store
numeric, date/time or string data. When a variable is declared, a data type is supplied for it that
determines the kind of data of data it can store. The fundamentals data types in VB including variant are
integer, long, single, double, string, currency, byte and Boolean. VB supports a vast array of data types.
Each data type has limits to the kind of information and minimum and maximum values it can hold.

Department of Computer Science, HiSAC, Erode 8


Visual Basic Lesson Notes - Unit I

Variables
Variables are used for storing values temporarily. A defined naming strategy has to be followed
while naming a variable. A variable name must begin with an alphabet letter and should not exceed 255
characters. It must be unique within the same scope. It should not contain any special characters such as
%, &, #, etc. There are ways of declaring variable in VB. Depending on where variable are declared and
how they are declared, user can determine how they can be used in the application. The different types of
declaring variables in VB are discussed below

Explicit Declaration
Declaring a Variable tells Visual Basic to reserve space in memory. It is not a must that a variable
should be declared before using it. Automatically whenever Visual Basic encounters a new variable, it
assigns the default variable type and value. This is called implicit declaration.

Though this type of declaration is easier for the user, it is advisable to declare them explicitly. The
variables are declared with a Dim statement to name the variable and its type. The As type clause in the
Dim statement allows to define the data type or object type of the variable. This is called explicit
declaration.
Syntax
Dim variable [As type]
Example
Dim strname As String
Dim intCounter As Integer

Using Option Explicit statement


It may be convenient to declare variables implicitly, but it can lead to errors that may not be
recognized at run time. Say, e.g. a variable by name intcount is used implicitly and is assigned to a value.
In the next step, this field is incremented by 1 by the following statement.
IntCount = intcont + 1
This calculation will result in intcount yielding a value of 1 as intcont would have been initialized
to zero. This is because the intcount variable has been mistyped as intcont in the right hand side of the
second variable. But Visual Basic does not view this as a mistake and considers it to be a new variable
and hence gives a wrong result. To prevent errors of this nature, we can declare a variable by adding the
following statement to the general declaration section of the Form.
Option Explicit
This forces the user to declare the entire variable. The Option Explicit statement checks in the module for
usage of any undeclared variables and reports an error to the user. The Option Explicit statement can be
explicitly placed in the general declaration of each module using the following steps.
• Click Option item in the Tool Menus
• Click the Editor tab in the Options dialog box.
• Check Require Variable declaration option and then click the OK button.

Scope of Variables
A scope of variable to a procedure-level (local) or module-level variable depending on how it is
declared. The scope of variable, procedure or object determines which parts of the code in the application
are aware of the variable’s existence.

Department of Computer Science, HiSAC, Erode 9


Visual Basic Lesson Notes - Unit I

A variable is declared is general declaration section of a Form and hence is available to all the
procedure. Local variables are recognized only in the procedure in which they are declared. They can be
declared with Dim and Static keywords. If we want a variable to be available to all the procedures within
the same module or to all the procedures in an application, a variable is declared with border scope.

Local Variables
A local variable is one that is declared inside a procedure. This variable is only available to the
code inside the procedure and can be declared using the Dim statement
Dim intTemp As Integer
The local variables exist as long as the procedure in which they are declared, is executing. Once a
procedure is executed the value of its local variables are lost and memory used by these variables is freed
and can be reclaimed. Variables that are declared with keyword Dim exist only as long as the procedure is
being executed.

Static Variables
Static variables are not re-initialized each time Visual Basic invoke a procedure and thus retains or
preserves value even when a procedure ends. In case we need to keep track of the number of times a
CommandButton in an application is clicked, a static counter variable has to be declared. These static
variables are also ideal for making controls alternatively visible or invisible. A static variable is declared
as given below.
Static intPermanent As Integer
Variables have a lifetime in addition to scope. The values in module-level and public variables are
preserved for the lifetime of an application whereas local variables declared with Dim exist only while the
procedure in which they are declared is still being executed. The value of a local variable can be
preserved using the Static keyword. The following procedure calculates the running total by adding new
values to the previous variable value.
Function RunningTotal()
Static Accumulate
Accumulate = Accumulate + num
RunningTotal = Accumulate
End Function
If the variable Accumulated was declared with Dim instead of Static, the previously accumulated values
would not be preserved across calls to the procedure and the procedure would return the same value with
which it was called. To make all variables in a procedure static, the Static keyword is placed at the
beginning of the heading in the statement below.
Static Function RunningTotal()

Module Level Variables


A module-level variable is available to all the procedures in the module. They are delcared using
the Public or the Private keyword.
Public IntPermanent As Integer
Private IntTemp As Integer
Declaring a variable using the Public keyword makes it available throughout the application even for the
other modules. At the module-level there is no difference between Dim and Private, but Private is
preferred because it makes the code easier to read. Pubic variable should not be declared within a
procedure. Public variable in different modules can share the same name and they can be differentiated in

Department of Computer Science, HiSAC, Erode 10


Visual Basic Lesson Notes - Unit I

code. For example, if the public integer variable intY is declared in both Forml and Modulel of a project
it can be referred as [Link] and [Link].

Public vs Local Variables. A variable can have the same name and different scope. For example, we can
have a public variable named R and within a procedure we can declare a local variable R. References to
the name R within the procedure would access local variable and references to R outside the procedure
would access the public variable.

1.5 Procedure and Control Structures


Procedures
Visual Basic programs can be broken into smaller logical components called procedures.
Procedures are useful for condensing repeated operations such as the frequently used calculations, text
and control manipulation, etc. Following are the benefits of using procedures in programming.
• It is easier to debug a program with procedures, which breaks a program into discrete logical limits.
• Procedures used in one program can act as building blocks for other programs with slight
modifications.
• A Procedure can be a Sub, Function or Property Procedure.

Sub Procedures
A sub procedure can be placed in standard, class and form module. Each time the procedure is
called, the statements between Sub and End Sub are executed. The syntax for a sub procedure is as
follows.
[Private | Pub1ic] [Static] Sub procedurename[(arglist)]
[Statements]
End Sub
arglist is a list of argument names separated by commas. Each argument acts like a variable in
the procedure. There are two types of Sub Procedures-general procedures and event procedures.

Event Procedures
An event procedure is a procedure block that contains the control’s name, an under score( _ ), and
the event name. The following syntax represents the event procedure for a Form_Load event.
Private Sub Form_Load( )
… Statement block …
End Sub
Event Procedures acquire the declaration as Private by default.

General Procedures
A general procedure is declared when several event procedures perform the same actions. It is a
good programming practice to write common statement m a separate procedure (general procedure) and
then call them in the event procedure. In order to add a general procedure following steps are followed.
• The Code window is opened for the module to which the procedure is to be added.
• The Add Procedure option is chosen from the Tools menu, which opens as Add Procedure dialog box
• The name of the procedure is typed in the Name textbox.
• Under Type, Sub is selected to create a Sub procedure, Function to create a Function procedure or
Property to create a Property procedure.

Department of Computer Science, HiSAC, Erode 11


Visual Basic Lesson Notes - Unit I

• Under Scope, Public is selected to create a procedure that can be invoked the module or Private to
create a procedure that can be invoked only from within the module.

We can also create a new procedure in the current module by typing Sub ProcedureName.
Function ProcedureName or Property ProcedureName in the Code window. A Function procedure returns
a value and a Sub procedure does not return a value.

Function Procedures
Functions are like sub procedures, except that they return a value to the calling procedure. They
are especially useful for taking one or more pieces of data, called arguments and performing some tasks
with them. Then the function returns a value that indicates the results of the tasks which are complete
within the function. The following function procedure calculates the third side or hypotenuse of a right
triangle, where A and B are the other two sides. It takes two arguments A and B (of data type Double) and
finally returns the result.
Function Hypotenuse(A As Double, B As Double) As Double
Hypotenuse = sqr(A^2 + B^2)
End Function
The above function procedure is written in the general declarations section of the Code window. A
function can also be written by selecting the Add Procedure dialog box from the Tools menu and by
choosing the required scope and type.

Property Procedures
A property procedure is used to create and manipulate custom properties. It is used to create read
only properties for Forms, Standard modules and Class modules. Visual Basic provides three kinds of
property procedures - Property Let that sets the value of a property, Property Get procedure that returns
the value of a property and Property Set procedure that sets the reference to an object.

Control Structure
If...Then...Else Statement
The If…Then block is used for conditional execution of one or more statements.
If Condition Then
Statements
End If
The statement is executed only if the condition is true. The condition is usually a comparison, but it can
be any expression that evaluates a numeric value. If…Then-Else block is used to define several blocks of
statements, in order to execute one block. The following block of statement illustrates If...Else...End If
statements.
If A=l Then
Statements
Else
Statements
End if
The following example illustrates the If...Then ...Else statement.
Private Sub Commandl_Click()
If Val([Link]) < 10 Then
MsgBox “It is a Single Digit Number"
Else lf Val([Link]) < 100 Then

Department of Computer Science, HiSAC, Erode 12


Visual Basic Lesson Notes - Unit I

MsgBox "It is a Two Digit Number"


Else If Val([Link]) < 1000 Then
MsgBox "It is a Three Digit Number"
Else
MsgBox "The Value is More Than Three Digits"
End If
End Sub
The program is executed by pressing F5. When a number is entered in the TextBox it displays a message
accordingly.

Select…Case Statement
Select...Case structure is an alternative to If…Then .... Elself for selectively executing a single
block of statements from among multiple blocks of statement. Select...Case is more convenient to use
than the If..Else..End If. The following program block illustrates the working of Select ... Case.
Select case Index
Case 0
Statements
Case 1
Statements
End select
Select…Case structure evaluates an expression once at the top of the structure, where as If..Then…Else If
structure evaluates different expressions for each Else If statement.

Do While Loop Statement


The Do While .....Loop is used to execute statements until a certain condition is met. The variable
counter is initialized to 1 and then Do While loop starts.
counter = 1
Do while counter < 101
counter = counter + 1
Loop

Do… Loop While Statement


The Do...Loop While statement, first executes the statements and, then tests the condition after the
execution.
counter = 200
Do
[Link] = Str(counter)
counter = counter + 1
Loop while counter < 501
The program executes the statements between Do and Loop While structure in any case. Then it
determines whether the counter is less than 501. If so, the program again executes the statements between
Do and Loop While else exits the loop.

Do…Loop Until Statement


The Do…Loop Until structure executes the statements until the condition is satisfied is false.
Private Sub Form_Load()
Do
name$ = InputBox(“Enter Name please…”)
Department of Computer Science, HiSAC, Erode 13
Visual Basic Lesson Notes - Unit I

msgbox name$
Loop Until name$ = “NIL”
End Sub
At the runtime it asks for the Name and until it is entered as “NIL” the loop remains infinite.

The For…Next Loop Statement


The For…Next Loop Statement is another way to make loops in Visual Basic. The following loop
counts from 1 to 50.
For I = 1 to 50 step 1
[Link] = Str(I)
Next
In order to count from 1 to 50 in steps of 2, the following loop can be used:
For I = 1 to 50 step 2
[Link] = Str(I)
Next

The Exit For and Exit Do Statement


A For…Next Loop can be terminated by an Exit For statement. Consider the following statement
block.
For I = 1 to 100
[Link] = Str(I)
If I = 50 then
Exit for
End If
Next
The preceding code increments the value of I by 1 until it reaches the condition I = 50. The Exit For
statement is executed and it terminates the For…Next Loop. The following statement block containing
Do..While loop using Exit Do statement.
I = 1
Do while I < 1001
[Link] = Str(I)
I = I + 2
If I > 500 then
Exit Do
End If
Loop

With - End With Statement


When properties are set for objects or methods are called, a lot of coding is included that acts on
the same object. It is easier to read the code by implementing the With-End With statement. Multiple
properties can be set and multiple methods can be called by using the With- End With statement. The
code is executed more quickly and efficiently as the object is evaluated only once. This concept can be
clearly understood with the following example.
with textprice
.[Link] = 16
.[Link] = True
.Height = 235

Department of Computer Science, HiSAC, Erode 14


Visual Basic Lesson Notes - Unit I

.Text = "Welcome to Visual Basic 6.0"


End With
In the above coding, the object textprice, which is evaluated only once instead of every associated
property or method. This makes the coding simpler and efficient.

1.6 Arrays in Visual Basic


A sequence of variables by the same name can be referred using arrays. The individual elements
of an array are identified using an index. Arrays have upper and lower bounds and the elements have to lie
within these bounds. Each index number in an array is allocated individual memory space and hence users
must avoid declaring arrays of larger size than required. We can declare an array of any of the basic data
types including variant, user defined types and object variables. The individual elements of an array are
all of the same data type. Following are the two types of arrays in VB:
• Fixed-size array The size of array always remains the same.
• Dynamic array The size of can be changed at runtime.

Fixed Size Array


Fixed arrays can be declared by giving a name to the array with the upper limit in the parentheses.
The upper limit should always be within the range of Long data type. Declaring fixed arrays in difference
cases are given below. Array declaration in the General Declaration section of a module or a procedure is
as shown in this example.
Dim lengths(9) As Integer
In the above illustration, lengths is the name of the array and the number 9 included in the parentheses is
the upper limit of the array. The above declaration creates an array with 10 elements, with index running
from 0 to 9.

If we want to specify the lower limit, then the parenthesis should include both the lower and upper
limit along with the To keyword. An example for this is given below.
Dim lengths(1 To 10) As Integer
In the above statement, an array of 10 elements is declared but with indexes running from 1 to 10. A
public array can be created using the keyword Public instead of Dim as shown below:
Public digits(20) As Integer

Multidimensional Arrays
A multidimensional array is used when we need to represent or store information of different
dimension. For example to hold the student registration number and marks of the student, we need to
mention its x and y co-ordinates. The following statement declares a two-dimensional 50 by 50 array
within the procedure.
Dim Marks(50,50)
It is also possible to define explicit lower limits for one or both the dimensions as for fixed size arrays.
An example for this is given here.
Dim StudMarks(101 to 200, 1 to 100)
Any number of dimensions can he declared in a multidimensional array. An example for a three
dimensional array with defined lower limits is given below.
Dim StudDetails(101 To 200,1 To 100,1 To 100)

Department of Computer Science, HiSAC, Erode 15


Visual Basic Lesson Notes - Unit I

Dynamic Array
There will be a situation when the user may not know the exact size of the array at design time.
Under such circumstances, a dynamic array can be initially declared and the user can then add elements
when needed instead of declaring the size of the array at design time.
Dim NewArray()
The actual number of elements can be allocated using a ReDim statement. This example allocates the
number of elements in the array based on the value of the variable Y.
ReDim NewArray(Y + 1)
The ReDim statement can appear only in a procedure, which is an executable statement. The same way of
declaration as used for fixed arrays is used for declaring ReDim statement also. ReDim is an executable
statement. The lower and upper limits for each dimension can also be specified explicitly as in a fixed size
array. An example for this is given below
ReDim FirstArray(4 to 12)
Each time on executing the ReDim statement, the current data stored in the array is lost and the default
value is set. But if we want to change the size of the array without losing the previous data, we have use
the preserve keyword with the ReDim statement. This is shown in the example given below.
ReDim Preserve NewArray(Ubound(FirstArray)+1)
When the Preserve keyword is used, only the upper limits of the last dimension in a multi dimensional
array can be changed. No other dimensions or the lower limit of the last dimension can be changed.

User-Defined data types


Variables of different data types when combined as a single variable to hold several related
information’s is called a User-Defined data type. A Type statement is used to define a user-defined type in
the General declaration section of a form or module. User defined data types can only be private in form
while standard modules they can be public or private. An example for a user defined data type to hold the
product details is as given below.
Private Type ProductDetails
Prodld As String
ProdName As String
Price As Currency
End Type

The user defined data type can be declared with a variable using the Dim statement as in any other
variable declaration statement. An array on these user-defined data types can also be declared. An
example to consolidate these two features is given below.
Dim Electronicgoods As ProductDetails ‘ One record
Dim Electronicgoods(lO) As ProductDetails ‘ An array of 11 record
A User-defined type can be referenced in an application by using the variable name in the
procedure along with the item name in the Type block. Say, for example if the text property of a textbox
namely text1 is to be assigned the name of an electronic item is written as given below.
[Link] = [Link]
If the same is implemented as an array, then the statement changes to the following.
[Link] = Electronicgoods(i).prodname
Here i is the index of the array. User defined types can also be passed to procedures to allow many related
items as one argument.
Sub ProdData(Electronicgoods As ProductDetails)
[Link] = [Link]

Department of Computer Science, HiSAC, Erode 16


Visual Basic Lesson Notes - Unit I

[Link] = [Link]
End sub

Constants
Constants are named storage locations in memory, the value of which does not change during
program execution. They remain the same throughout the program execution. When the user wants to use
a value that never changes, a constant can be declared and created. The Const statement is used to create
a constant. Constants can be declared in local, form, module or global scope and can be public or private
as for variables. Constants can be declared as illustrated below.
Public Const gravityconstant As Single = 9.81

Predefined Visual Basic Constants


The predefined constants can be used anywhere in the code in place of the actual numeric values.
This makes the code easier to be read or write. For example consider a statement that will set the window
state of a form to be maximized.
[Link] = 2
The same task can be performed using a Visual Basic constant.
[Link]=vbMaximised

Data Type Conversion


Visual Basic functions either to convert a string into an integer or vice versa and many more
conversion functions. A complete listing of all conversion functions offered by Visual Basic is listed
below
Conversion To Function
Boolean Cbool
Byte Cbyte
Currency Ccur
Date Cdate
Decimals Cdec
Double CDbl
Integer Cint
Long CLng
Single CSng
String CStr
Variant CVar
Error CVErr
A conversion function should always be placed at the right hand side of the calculation statement.

Visual Basic Built-in Functions


Many built-in functions are offered by VB that fall under various categories. These functions are
procedures that return a value.
• Date and Time Functions
• Format Function
• String Functions
Date and Time Functions
Date and time are internally stored as numbers in VB. The Whole number portion of the number
represents the date between 1st January, 100 and December 31, 1999 inclusive. The decimal portion

Department of Computer Science, HiSAC, Erode 17


Visual Basic Lesson Notes - Unit I

represents the time between 0:00:00 and 29:59:59 hours inclusive. The system's current date and time can
be retrieved using the Now, Date and Time functions in VB, The Now function retrieves the date and
time, While Date function retrieves only date and Time function only retrieves the time. To display both
the date and time together a message box is displayed using the statement given below.
MsgBox "The current date and time of the system is" & Now
Here ‘&’ is used as a concatenation operator to concatenate the string and the Now function. Selective
portions of the date and time value can be extracted using following functions given in the below.
Function Extracted Portion
Year() Year(Now)
Month() Month(Now)
Day() Day(Now)
WeekDay() WeekDay(Now)
Hour() Hour(Now)
Minute() Minute(Now)
Second() Second(Now)
The calculation and conversion functions related to data and time are listed below
Function Description
DateAdd( ) Returns a date to which a specific interval has been added
DateDiff( ) Returns a Long data type value specifying the interval between the two values
DatePart( ) Returns an Integer containing a specified part of a given date.
DateValue( ) Converts a string to a date.
TimeValue( ) Converts a string to a time.
DateSerial( ) Returns a date for a specified year, month and day.

DateDiff Function
The DateDiff function returns the interval between two dates in terms of years, months or days.
The syntax for this given below
DateDiff(interval, date1, date2 [,firstdayofweek[,firstdayofweek]])

Format Function
The format function accepts a numeric value and converts it to a string in the format specified by the format
argument. The syntax is given below
Format(expression[, format [,firstdayofweek[,firstdayofweek]]])
The Format function syntax with various parts are listed below
Part Expression format
Expression Required any valid expression
format Optional. A valid named or user-defined format expression
firstdayofweek Optional. A constant that specifies the first day of the week
firstweekofyear Optional. A constant that specifies the first week of the year

Comparison and Relational Operators


There are six relational operators used in testing expressions. They are < (less than), <= (leass or
equal to), > (greater than), >= (greater or equal to) and = (Equal to) and <> (Not Equal to). When two
expressions are compared, it returns either True or False. True or False are Boolean values, with 0 for
Fa1se and 1 for True.

Department of Computer Science, HiSAC, Erode 18


Visual Basic Lesson Notes - Unit I

Logical Operators
There are six logical operators. The most common operators are And, Or and Not operators. And
Xor, Equ and Imp operators are advanced operators.
Operator Functions
And Combines two expressions. Both the expression must be True for the entire expression
to be True
Or Combines two expressions. If one of the expression is True for the entire expression is
True
Not The Negative of single expression
Xor Combines two expressions. The entire expression consider to be True if the two
expression are not both True or False
Equ Combines two expressions. Both expression must be True or False for the entire
expression to be True
Imp Combines two expretyg rssions. The entire expression is True except when first
expression is True and the second expression is False

Test Strings
VB string functions can manipulate strings in applications. Below table given brief description
about the string functions in VB.
Function Name Purpose
StrComp( ) Compare two strings
Format, Lcase( ) Converts the string to lowercase
Format, Ucase( ) Converts the string to uppercase
Space, String( ) Creates a string of repeating character
Len( ) Finds the length of a string
Format( ) Format a string
Lset( ), Rset( ) Justify a string
Instr( ) Returns a Variant(Long) specifying the position of the
first occurrence of one string within another
Left( ) Returns a Variant(String) containing a specified number
of characters from the left side of the string
Mid( ) Returns a Variant(String) containing a specified number
of characters from a string
Right( ) Returns a Variant(String) containing a specified number
of characters from the right side of the string
Trim( ) Returns a Variant (String) containing a copy of a
specified string without leading spaces and trailing
spaces.
Ltrim( ) Returns a Variant (String) containing a copy of a
specified string without leading spaces.
Rtrim( ) Returns a Variant (String) containing a copy of a
specified string without trailing spaces.
StrConv( ) Converts the strings

**********

Department of Computer Science, HiSAC, Erode 19


Visual Basic Lesson Notes - Unit I

2. Working with Controls


2.1 Creating and using Controls
A control is an object be drawn on a Form object to enable or enhance user interaction with an
application controls have properties that define aspects of their appearance, such as position, size and
colour and aspects of their behaviour, such as their response to the user input. They can respond to events
initiated by the user or triggered by the system. For example, a code could be written in a Command
Button control's Click event procedure that would load a file or display result.

In addition to properties and events, methods can also be used to manipulate controls from code.
For example, the Move method can be used with some controls to change their location and size. Most of
the controls provide choices to users that can be in the form OptionButton or CheckBox controls, ListBox
entries or ScrollBars to select a value.

Classification of Controls
Visual Basic controls are broadly classified as standard controls, ActiveX controls and insertable
objects. Standard controls such as CommandButton, Label and Frame controls are contained inside a
.EXE file and are always included in the 'l'oolbox which cannot removed. ActiveX controls exist as
separate files with .VBX or .OCX extension. They include specialized controls such as
• MSChart Control
• The Communicating Control
• The Animation control
• The List View control
• An ImageList control
• The Multimedia control
• The Internet Transfer control
• A WinSock control
• The Tree View control
• The Syslnfo Control
• The Picture Clip control
These built-in ActiveX controls will be discussed at length in Chapter 14. Some of these objects support
OLE automation, which allow programming another application object from within Visual Basic
application.

Tablndex Property of Controls


Visual Basic uses the Tablndex property to determine the control that would receive the focus next
when a Tab key is pressed. Every time a Tab key is pressed, VB looks at the value of Tablndex for the
control that currently has focus and then it scan through the controls searching for the next highest
Tabludex number. If this new control can accept the keyboard focus, the focus moves to the control.
Otherwise, it looks for the next control with next higher Tablndex value. When there are no more controls
with higher TabIndex value, Visual Basic starts all over again with 0 and looks for the first control with
TabIndex of 0 ot more that can accept keyboard input.

By default, Visual Basic assigns a tab order to controls as we draw them on a form, with the
exception of the Menu, Timer. Data, Image, Line and Shape controls which are not included in the tab
order. At run time, invisible or disabled controls and controls that cannot receive the focus (Frame and

Department of Computer Science, HiSAC, Erode 20


Visual Basic Lesson Notes - Unit I

Label controls) remain in the tab but are skipped during tabbing. Setting the TabIndex property of
controls is a must in development environment.

Each new control is placed last in the tab order. If we change the value of a control's
Tablndex property to adjust the default tab order, VB automatically re-numbers the TabIndex of other
controls to reflect insertion and deletions. We can make changes at the design time using the Properties
window or at run time in code.

Using Text Box Control


A TextBox control sometimes called an edit field or edits control, display information entered at
design time. This could be entered by the user or assigned to the control in code at run time.

Setting Properties to a Text Box


• Text can be entered into the text box by assigning the necessary string to the text property of the
control
• If the user is interested in displaying multiple line of text in a TextBox control, he has to set the
MultiLine property to True. If a multiple-line Textbox does not have a horizontal ScrollBar, text
wraps automatically even when the Textbox is resized.
• In order to customize the scroll bar combination on a TextBox, set the ScrollBars property.
• ScrollBars will always appear on the TextBox when its Multiline property is set to True and its
ScrollBars property is set to anything except None (0).
• If the user sets MultiLine property to True, he can use the Alignment property to set the alignment
of text within the TextBox. The text is left-justified by default. If the MultiLine property is False,
setting the Alignment property has no effect.
• A TextBox control can also act as a destination link in a DDE conversation.
• In order to work with the part of a text in a TextBox, the text can be selected using the following three
properties.
• SelLength Returns or sets the number of characters selected.
• SelStart Returns or sets the starting point of selected text. when no text is selected, SelStart indicates
the position of the insertion point.
• SelText Returns or sets the string containing the currently selected text. If no text is selected, SelText
consists of a zero-length string.
• The selected text can be copied to the Clipboard by using SelText in the following form
[Link] text, [format]
In the above syntax, text is the text that has to be placed into the Clipboard and format has three
possible values.
➢ VbCFLink - conversation information
➢ VbCPRTF - Rich Text Format
➢ VbCFText – Text
We can get the text from the clipboard using the GetText( ) function in the following way.
[Link]([format])

Using a label Control


A Label control is a graphical control you can use to display text that a user can’t change directly.

Properties of a Label control

Department of Computer Science, HiSAC, Erode 21


Visual Basic Lesson Notes - Unit I

• We can write code that changes the caption property displayed by a Label control in response to
events at run time. We can also use a Label to identify the control, such as TextBox control, that
doesn't have its own Caption property.
• The AutoSize and WordWrap properties should be set if users wants the Label to properly display
variable-length lines or varying numbers of lines.
• A Label control can also act as a destination in a DDEconversation. Set the LinkTopic property to
establish a link, set the LinkItem property to specify an item for the conversation, and set the
LinkMode property to activate the link. When these properties have been set, VB attempts to initiate
the conversation and displays a message if it’s unable to do so.
• Set the UseMnemonic property to True if you want to define a character in the Caption property of
the Label as an access key

Using a Command button


A Command Button control is used to begin interrupt or end a process. When chosen, a
CommandButton appears pushed in and so is sometimes called a push button.

Properties of a Command Button Control


• To display text on a CommandButton control, set its Caption property.
• An event can be activated by clicking a command button.
• A button's background colour can be set by setting the Backcolour property to the desired choice.
• The text colour of a command button can be set using the Forecolour property.
• The Font of a command button can be selected by setting the Font property in the Font dialog box to
the desired one.
• The buttons can be enabled or disabled by setting the Enabled property to True or False respectively.
• Also the buttons can be made visible or invisible at run time using the Visible property.
• Tooltips can be added to a button by setting a text to the Tooltip property of the command button.
• A button click event is triggered or fired the following Code is entered in the General Declarations
Private Sub Commandl_Click( )
......
End Sub

Using OptionButton Control


OptionButton provides a set of choices from which a user can select only one button by
• Clicking it at run time.
• Assigning the value property t o True in code like [Link]=True
• Using the shortcut keys specified in the Caption of a Label.
To disable an OptionButton at run time, its Enabled property is set to False. Let us develop a
number system application that illustrates the operation of the OptionButton control. The program
contains Label, TextBox, CommandButton and three OptionButton controls.

Example
• A new Standard EXE project is opened and the Form and the project is saved as Option. frm and
[Link] respectively.
• The Form is designed as per the following specifications table. The design Form appears as shown
below Figure.

Department of Computer Science, HiSAC, Erode 22


Visual Basic Lesson Notes - Unit I

Object Properties Setting


Label Caption Enter a Number
Name Label 1
TextBox Text (Empty)
Name Text 1
CommandButton Caption &Close
Name Command 1
OptionButton Caption &Octal
Name optOct
OptionButton Caption &Hexadecimal
Name optHex
OptionButton Caption &Decimal
Name optDec
The application responds to the following events
• The change events of the TextBox read the value and store it in a form-level numeric variable as
currentval.
• The click event of optOct button returns currentvalin octal.
• The click event of optHexa button returns currentvalin hexadecimal.
• The click event of optDec button returns currentvalin decimal.
The following code is entered in the general declarations section of the Form.
Dim currentval as variant
The variable is initialised to 0 by default. The change event procedure checks to ascertain the number
system (Octal, Hexadecimal) that is in effect and then reads in the number.
Private Sub Textl_Change()
If [Link] = True Then
currentval = Val("&0" & LTrim([Link]) & "&")
Elseif [Link] = True then
currentval = Val(Ltrim([Link]) & "&")
Else
Currentval = Val("&H" & LTrim([Link]) & "&")
End If
End Sub

The Val function is used to translate string to a number and can recognize Octal and
Hexadecimal strings. The LTrim function trims the leading blanks in the text. The following code is
entered in the click event of the OptionButton controls.
Private Sub optOct_Click()
[Link] = Oct(currentval)
Department of Computer Science, HiSAC, Erode 23
Visual Basic Lesson Notes - Unit I

End Sub
Private Sub optHex_Click()
[Link] = Hex(currentval)
End Sub

Private Sub optDec_Click()


[Link] = Format(currentval)
End Sub
The following code is entered in-the click event of the Close button.
Prlvate Sub cmdclose_Click()
Unload Me
End Sub

Using ListBox and ComboBox Controls


ListBox and ComhoBox controls present a set of choice that is displayed vertically in a single
column. If the number of items exceeds the value that can be displayed, scroll bar will automatically
appear on the control. These scroll bars can be scrolled up and down or left to right through the list.

Adding Items to Lists


It is possible to populate the list at design or at run time.
Deign Time - To add items to list at design time, click List in the property box and then add the items.
Press CTRL+ENTER after adding each item.
Run time - The AddItem method is us to add items to a list at run lime. The AddItem method uses the
following syntax.
[Link] item, index
The item argument is string that represents the text to be added to the list.
The index argument is an integer that indicates where in the list to add the new item.

Removing Items from a List


The RemoveItem method is used to remove an item from list. The syntax for this is given below.
[Link] index
The following code verifies an item which is selected in the list and then removes the selected item.
Private Sub cmdRemovelistltem_Click()
If [Link] > -1 Then
[Link] [Link]
End if
End Sub
An error occurs if you attempt to use RemoveItem when no items are selected.

Selecting an item from a List Box


To access items in a list box, we use the ListIndex and List properties. The ListIndex property sets
the index number of the currently selected item. The first item in the list in index number is 0. The
ListIndex retirns -1 if no item is selected. The ListCount property is always one more than the index of the
last item in the list. The NewIndex property returns the index of the last item added to the list. The
following example adds an item to the list box and sets the new item as current selection.
[Link] = “Television”
[Link] = [Link]

Department of Computer Science, HiSAC, Erode 24


Visual Basic Lesson Notes - Unit I

The List property sets or returns that text of an item in a list box. The index number is passed to the list
property to specify the item to be accessed. To return the text of the selected item, the ListIndex property
is passed as shown in the following example:
Str = [Link]([Link])
To return the string for a ListBox, the Text property of the control is used as shown in the following
example:
Str = [Link]

Sorting the List


The sorted list property is set to True to enable a list to appear in alphanumeric order and False to
display the list items in the order in which they are added to the list.

Using the ComboBox


A ComboBox combines the features of TextBox and a ListBox. This control enables the User to
select either by typing text into the ComboBox or by selecting an Item from the list. There are three types
of ComboBox styles.
• Dropdown Combo (style 0)
• Simple Combo (style 1)
• Dropdown List (style 2)
The Simple combo box displays an edit area with an attached list box always visible immediately below
the edit area. A simple ComboBox displays the contents of its list all the time. The user can select an item
from the list or type an item in the edit box portion of the combo box. A ScrollBar is displayed beside the
list if there are too many items to be displayed in the list box area.

The Dropdown combo box first appears as only an edit area with a down arrow button at the right.
The list portion stays hidden until the user clicks the down-arrow button to drop down the list portion. The
user can either select a value from the list or type a value in the edit area.

The Drop-down list combo box turns the combo box into a drop-down list box. At run time, the
control looks like the drop-down combo box. The user could click the down arrow to view the list. The
difference between Dropdown combo and Drop-down list combo is that the edit area in the dropdown list
is disabled. The user can select only one of the list items and cannot type an item in the edit area. This
area, however, does display the item currently selected in the list.

Generally the ComboBox is preferred when there is a list of choices. It saves space on a Form. The
full list is not displayed until the user clicks the down arrow (except for style 1). An illustration of
different types of combo boxes is shown in below figure.

Department of Computer Science, HiSAC, Erode 25


Visual Basic Lesson Notes - Unit I

The AddItem method is used to add values to the ComboBox and ListBox. Similarly the
RemoveItem method is used to remove items from the ListBox or ComboBox. Let us now develop a
small application that uses AddItem, RemoveItem and Clear methods. The application contains a
TextBox, ListBox and three Label and CommandButton controls as shown in below figure. It is designed
in name in the TextBox. When the Add button is clicked, the types name is added in the ListBox. A
particular entry in the ListBox can be removed by selecting the item and choosing the Remove button.
Example
For the supermarket SM & Co. develop an application to Add, Remove, Clear the list of items and
then finally close the application.

Object Properties Setting


Form Caption List Box Application
Name Form1
TextBox Name Text 1
Text (Empty)
Label Name Label1
Caption Enter a Name
ListBox Name List1
Sorted True
Label Name Label2
Caption #Clients
Label Name Label3
Caption (Empty)
Border style 1-Fixed Single
CommandButton Caption &Add
Name cmdAdd
Enabled False
CommandButton Caption &AddRemove
Name cmdRemove
CommandButton Caption &Clear
Name cmdClear
CommandButton Caption E&ixt
Name cmdExit

Following event procedure are added for the TextBox, CommandButton and ListBox controls.
Private Sub Text1_Change()
[Link] = (Len([Link]) > 0)
End Sub

Department of Computer Science, HiSAC, Erode 26


Visual Basic Lesson Notes - Unit I

Private Sub cmdAdd_Click()


[Link] [Link]
[Link] = ““
[Link]
[Link] = [Link]
End Sub
The click event of the Add buttons adds the text into the list box that was types in the TextBox. It
then clears the TextBox. The value of the Label which shows the number of ListBox items immediately
incremented. The focus is again set back to the TextBox for adding the item.
Private Sub cmdRemove_Click()
Dim Ind As Integer
Ind = [Link]
If Ind >= 0 then
[Link] Ind
[Link] = [Link]
End If
[Link] = ([Link] <> -1)
End Sub
The code written in the Remove button removes the selected items from the ListBox. If none of
items in the ListBox are selected, the Remove command is disabled. The number of items in the list box is
decremented by 1 and value is displayed in Label.
Private Sub cmdClear_Click()
[Link]
[Link] = False
[Link] = [Link]
End Sub
The code in the clear button clears all the items in the ListBox. Then it disables the remove
CommandButton and the Label that displays the list items becomes zero.
Private Sub cmdExit_Click()
Unload Me
End Sub
Private Sub List1_Click()
[Link] = ([Link] <> -1)
End Sub
We can have multiple column and multiple selection ListBox by setting both the Columns and
MultiSelect properties of the ListBox.

Using ScrollBar control


The ScrollBar is a commonly used control, which enables the user to select a value by positioning
it at the desired location. It represents a set of values. 'I'he Min and Max property represents the minimum
and maximum value. The Value property of the scroll bar represents its current value, which may be any
integer between minimum and maximum value. Let us develop a small program that illustrates the
ScrollBur control.
Example
For the supermarket SM&Co. we need to develop an application where the ScrollBar is used to
indicate the weights in grams. A standard Exe project is opened and saved. The Form is designed as

Department of Computer Science, HiSAC, Erode 27


Visual Basic Lesson Notes - Unit I

shown below where thumb of the ScrollBar is positioned at the centre. When the thumb’s position is
changed, it should in the TextBox.

The Form is designed as per the below specifications


Object Properties Setting
Form Caption Weight Program
Name Form1
TextBox Name Text 1
Text Gms
CommandButton Caption Exit
Name Command1
HScrollBar Max 100
Min 0
Name HScroll1
Value 50
The following code is entered in the HScroll_Change( ) procedure
Private Sub HScroll_Change()
[Link] = [Link] & “gms”
End Sub
The following code is entered in the Command1_Click() procedure.
Private Sub Command1_Click()
End
End Sub
The project is saved and the application is run by pressing F5. By changing the position of
HScrollBar, we can find the change in the speed in the TextBox.

2.2 Working with ControlArrays


A control array is a group of controls that share the same name and type. They also share the same
event procedures. Adding controls with control arrays uses fewer resources than adding multiple controls
of same type of same type at design time.

Creating Control Arrays at Design time


There are three ways to create a control array at design time.
• Assigning the same in the Name property for more than one control.
• Copying an existing control and then pasting it into the Form. This can be done by focusing the
control and choosing the Copy from Edit menu and then choosing the Paste option from Edit menu.
• Setting the Index property to a value that is not null.

Department of Computer Science, HiSAC, Erode 28


Visual Basic Lesson Notes - Unit I

Adding a Control Array at Run Time


Control arrays can be created at run time using the following statements.
• Load object (index %)
• Unload object (index %)
Where object is the name of the control which is to be added or deleted from the control array. Index %
is the value of the index in the array. The control array to be added must be an element of the existing array
created at design time with an index value of 0. When a new element of control array is loaded, most of the
property settings are copied from the lowest exiting element in the array.

Control Array Application


The application use a set of CommandButton controls in an array to illustrate the working of a
Calculator.
Example
A standard EXE form is created and saved. The form is designed as per the following below
specifications.
Object Properties Setting
CommandButton Name Cmd
Caption 0
Index 1
CommandButton Name Cmd
Caption 2
Index 1
CommandButton Name Cmd
Caption 3
Index 2
CommandButton Name Cmd
Caption 4
Index 3
CommandButton Name Cmd
Caption 5
Index 4
CommandButton Name Cmd
Caption 6
Index 5
CommandButton Name Cmd
Caption 7
Index 6
CommandButton Name Cmd
Caption 8
Index 7
CommandButton Name Cmd
Caption 9
Index 8
CommandButton Name Cmd
Caption 0
Index 9

Department of Computer Science, HiSAC, Erode 29


Visual Basic Lesson Notes - Unit I

CommandButton Name Cmd


Caption .
Index 10
Text box Name Text1
Alignment Right Justify
CommandButton Name CmdAC
Caption AC
In addition to these controls, six command button controls are added and they are named as CmdPlus,
CmdMinus, CmdDiv, CmdMul, CmdNegtive and Cmd Equal with their caption +, -, /, *, +/- ,=,
respectively. The following variables are declared in the general declarations of the form.
Public curval As Double
Public preval As Double
Public choice As String
Public result As Double
The following code is entered in the cmd_Click( ) (Control Array) event procedure.
Private Sub cmd_Click(Index As Ingeter)
[Link] = [Link] & cmd(Index).Caption
curval = Val([Link])
End Sub
In the cmdAC_Click( ) procedure, the following code is entered.
Private Sub cmdAC_Click()
curval = preval = 0
[Link] = “”
End Sub
The following code is written in the CmdNegtive_Click( ) procedure
Private Sub CmdNegtive_Click()
curval = - curval
[Link] = Val(curval)
End Sub
The following code is entered in the click events of the cmdPlus, cmdMinus, cmdMul, cmdDiv control
respectively.
Private Sub cmdPlus_Click()
[Link] = “”
preval = curval
curval = 0
choice = “+”
End Sub
Private Sub cmdMinus_Click()
[Link] = “”
preval = curval
curval = 0
choice = “-”
End Sub
Private Sub cmdMul_Click()
[Link] = “”
preval = curval
curval = 0

Department of Computer Science, HiSAC, Erode 30


Visual Basic Lesson Notes - Unit I

choice = “*”
End Sub
Private Sub cmdDiv_Click()
[Link] = “”
preval = curval
curval = 0
choice = “/”
End Sub
To print the result on the TextBox, the following code is entered in the cmdEqual_Click( ) event
procedure.
Private Sub Command2_Click()
Select Case choice
Case "+"
result = preval + curval
[Link] = Str(result)
Case "-"
result = preval - curval
[Link] = Str(result)
Case "*"
result = preval * curval
[Link] = Str(result)
Case "/"
result = preval / curval
[Link] = Str(result)
End Select
curval = result
End Sub

Save and Run the project. On clicking digits of user ‘s choice and an operator button, the output appears
as shown below:

***** End of Unit I ****

Department of Computer Science, HiSAC, Erode 31


Visual Basic – Unit II

3. Menus, Mouse Events andDialogBoxes


3.1 Menus
VB offers applications can be enhanced by adding menus to it. It offers a convenient and consistent way
to group commands and an easy way for users to access them. The menubar appears below the title bar and it
may contain one or more menu titles. When a menu title is clicked it displays a set of menu items under that
title (for e.g. Exit, Open). Each menu item corresponds to a menu control that is defined in a menu editor and
performs a specific action.

Using the Menu Editor


A menu editor can be used to add new commands to the exiting menus, create new menus and menu
bars, change or delete exiting menu and menu bars. A menu editor can be added only after opening a project. To
display menu editor, Menu Editor Command is chosen from the Tools menus or the menu editor is clicked this
is in the toolbar. Below figure displays a menu Editor. The menu editor includes all the menu controls of the
current form. The properties of all the menu items are available in the properties window.

Writing a Program
Develop an application for the supermarket SM & CO, when the label tags for the items have to be
obtained in different colours and size.

A program contains a menu bar with two titles: Colours and Size. The Colours menu allows selection of a
colour from a menu and files the program's Form with the selected colour. The Colours menu has menu items
Fillcolour and Exit. When the FillColour menu is clicked another menu pops up with a list of colours. This is a
submenu of the menu FillColour. A menu item can have a maximum of four levels of submenus. The Form of
the program is filled with the selected colour from the popup menu. The Size menu contains menu items Small
and Large.

Dept. of Computer Science, HiSAC, Erode 33


Visual Basic – Unit II

Example
• A new Standard EXE project is opened and the Form and the project files are saved as [Link] and
[Link].
• The Form is designed as per the properties table given below
Object Property Settings
Form Caption COLOUR / SIZE
Name frmColour
The menu items are for the Form is designed as per the following specification listed below:
Object Settings
&Colours mnucolour
...&Fill Colour mnuFillColour
. .... &Red mnuRed
. .... &Green mnuGreen
. .... &Blue mnuBlue
&Size mnuSize
... &Small mnuSmall
...&Large mnuLarge
The following steps are performed to create the full menu application.
• After selecting the Menu Editor, &Colours is typed in the Caption TextBox and mnucolour in the Name
TextBox. The '&' character underlines the letter C. This property allows to us to press Alt + C while the
program is running which has the same effect of clicking Colours.

• The Next button is clicked and &FilI Colour is typed in the Caption TextBox and mnuFillColour in the
Name TextBox. The right arrow button is now clicked.
• The Next button is clicked and &Exit is typed in the Caption TextBox and mnuSize the Name TextBox.
The left arrow button is now clicked.
• The Next button is clicked and &Size is typed in the Caption TextBox and mnuSize in the Name TextBox.
The left arrow button is now clicked.

Dept. of Computer Science, HiSAC, Erode 34


Visual Basic – Unit II

• Now the next button is clicked and S&maIl is typed in the Caption TextBox and mnuSamll in the Name
TextBox. The right arrow is clicked.
• The Next button is clicked and &Large is typed in the Caption TextBox and mnuLarge in the Name
TextBox.
• When FillColour menu item is selected, a submenu with Red, Green and Blue should pop-up. Hence, these
items should be included below the Fill Colour item.

Writing Code for Menu Controls


Each menu control has a click event, which is executed when the menu item is selected or clicked. The
following code is entered in the general declarations section of the Form [Link].
Option Explicit
The following code is entered in the Form_Load( ) procedure.
Private Sub Form_Load()
[Link] = False
[Link] = false
End Sub
Initially the window is small and the Form is green in colour. Hence the menu items Small and Green are
disabled. The following code is entered in the mnuRed_Click( ) procedure.
Private Sub mnuRed_Click()
[Link] = QBColor(4)
[Link] = False
[Link] = True
[Link] = True
End Sub
When the menu item Red is clicked, mnuRed procedure is executed this changes the colour of the Form to red
and disables the Red menu item. The procedure then enables the Green and Blue menu items because the colour
Form is now red and it should be changed to either blue or green.
Private Sub mnuBlue_Click()
[Link] = QBColor(1)
[Link] = False
[Link] = True
[Link] = True
End Sub
When menu item Blue is clicked, the mnuBlue_Click( ) procedure is executed which changes the colour of the
Form to red and disables the Blue menu item. The procedure then Green and Red menu items because the
colour of the Form is now blue and it should be changed to either green or red.
Private sub mnuGreen_Click()
[Link] = QBColor(2)
[Link] = False
[Link] = True
[Link] = True
End Sub
When the menu item Green is clicked, the mnuGreen_Click( ) procedure is executed which changes the colour
of the Form to green and disables the Green menu item. The procedure then enables the Red and Blue menu
items because the colour of the Form is now green and it should be changed to either blue or red.
Private Sub mnuLarge_Click()
[Link] = 2

Dept. of Computer Science, HiSAC, Erode 35


Visual Basic – Unit II

[Link] = False
[Link] = True
End Sub
When the menu item Large is selected, the mnuLarge_Chck.( ) procedure is executed which maximizes the size
of the Form and disables the Large menu item. The size of the Form is changed by setting the WindowState
property of the Form.
Private Sub mnuSmall_Click()
[Link] = 0
[Link] = False
[Link] = True
End Sub
End statement is added in the mnExit_Click( ) To terminate the application. When the menu it Small selected,
mnuSmall_Click() procedure is executed which minimizes the size of the Form and disables the Small menu
item.

Adding a Separator Bar and Shortcut Keys


A separator bar is line which separates the menu items. It is mainly useful for obtaining clarity. The
Colours program can be enhanced by adding a separator bar between the FillColour and Exit menu items.
• Exit menu is selected in the menu Editor and Insert button is clicked.
• In the Caption TextBox ‘-‘ typed and mnuSep is typed in the Name TextBox. The OK button is clicked.
This adds a separator line, which is drawn between the FillColour and Exit menu items.

Popup Menu
A pop-up menu is a floating menu that is displayed over a Form independent of the menu bar. Pop-up
menus are also called context menu because the items displayed on the pop-up menu depend on where the
pointer is located when the right mouse button is clicked. Any menu can be displayed as a pop-up menu at run
time provided it has one menu item. The following code displays the Colours menu when the user clicks the
right mouse button over the Form at run time.
Private Sub Form_MouseDown(Button As Integer, Shift As
Integer, X As Single, Y s Single)
If Button = 2 Then
PopupMenu mnuCo1ors
End If
End Sub

Making Menu Controls invisible


In the above program, menu items are enabled and disabled at run time by setting the Enabled property
to True or False. When a menu item is disabled, it is dimmed and cannot be selected. But it is still visible and
the menu items are seen. Sometimes it is required to hide the menu items completely. We can do this using the
following statement.
[Link] = False
The following code entered in the Form_Load( ) procedure of the Colours program makes the menu item Exit,
invisible at runtime.
[Link] = False
The whole menu is made invisible by setting the visible property of the menu's title to False. The following
code entered in the Form_Load() procedure makes the Colours menu invisible.
[Link] = False

Dept. of Computer Science, HiSAC, Erode 36


Visual Basic – Unit II

Using Check Marks


Some programs may require check marks to be placed in the menu items. To place a check mark in a
menu item, the checked property is set to True. The following example code entered in the Form_Load( )
procedure places a check mark in the menu item Red.
[Link] = True
The following code entered in the Form_Load( ) procedure unchecks the menu item Red.
[Link] = False

Menu Control Arrays


A menu control array is a set of menu items on a menu that share the same name and event procedure.
Each menu control array element is identified by a unique index value, indicated in the Index property box on
the menu editor. When a member of a menu control array recognizes an event, VB passes the index property
value to the event procedure as an additional argument. The event procedure must include the code that can
check the value of the Index property.

3.2 Mouse Events


Visual Basic Applications respond to various mouse events, which are recognized by most of the
controls, the main events are MouseDown, MouseUp and MouseMove. MouseDown occurs when the user
presses any mouse button and MouseUp Occurs when the user releases any mouse button: MouseMove occurs
whenever the mouse pointer is moved to a new point on the screen. These events use the arguments button,
Shift, X, Y and they contain information about the Mouse's condition when the button is clicked.

The first argument is an integer called Button. The value of the argument indicates whether the left, right
or middle mouse button was clicked. The second argument is an integer called shift. The value of this argument
indicates whether the mouse clicked simultaneous with the Shift key, Ctrl key or Alt key. The third and fourth
arguments X and Y are the co-ordinates of the mouse location at the time mouse was clicked. As the Form is
executed automatically whenever the mouse button is clicked inside the Form’s area x, y Co-ordinates are
referenced to the Form.

Positioning a Control
Mouse Down is a commonly used event and it is combined with a Move method to move an
ImageControl to different location in a Form. The following application illustrates the movement of object
responding to events. It makes use of two OptionButton controls, two Image controls and a CommandButton.
The application is designed in such a way that when an OptionButton is selected, the corresponding image
control is placed anywhere in the Form whenever it is clicked.
Example
A new Standard Exe project is opened and the Form and the project files are saved as [Link] and
[Link]. The form is designed as per the properties given below:
Object Property Setting
From Caption Mouse Down Application
Name Form1
OptionButton Caption Credit card is selected
Name Optionl
Value True
OptionButton Caption Cash is selected
Name Option2

Dept. of Computer Science, HiSAC, Erode 37


Visual Basic – Unit II

Image Name imgcard


Picture c: \[Link]
Image Name imgcash
Picture c:\[Link]
The following code in entered in the general declaration section of the Form
Option Explicit
The following code is entered in the Form_MouseDown( ) event.
Private Sub Form_MouseDown(Button As Integer, Shift As Integer, X
As Single, Y As Single)
If Option1 = True then
[Link] X, Y
Else
[Link] X, Y
End If
End Sub
The application is run by keying in F5. When the mouse is clicked over the Form, the selected image moves to
that location where the mouse is clicked.

Graphical Mouse application


Mouse events can be combined with graphics methods and any number of customized drawing or
painting applications can be created. The following application combines MouseMove and MousaDown events,
and illustrates a drawing program.

Example
A new Standard EXE project is opened and the Form and project files are saved as [Link] and [Link].
The Name and Caption properties of the Form are changed to frmDraw and LINE DRAWING APPLICATION.

The following code is entered in the general declarations of the frmDraw Form,
Option Explicit
The following code is entered in the Form_MouseDown( ) procedure.
Private Sub Form_MouseDown(Button As Integer, Shift As Integer,
X As Single, Y As Single)
[Link] = X
[Link] = Y
End Sub
The following code is entered in the Form_MouseMove( ) procedure.
Private Sub Form_MouseMove(Button As Integer, Shift As Integer,
X As Single, Y As Single)
If Button = 1 Then

Dept. of Computer Science, HiSAC, Erode 38


Visual Basic – Unit II

Line ([Link], [Link])-(X, Y)


End If
End Sub
Button va1ue 1 indicates that the left mouse button is clicked. The code written in the MouseDown event
changes the CurrentX and CurrentY to the co-ordinates where the mouse was clicked. The program is executed
by pressing F5. When the mouse button is clicked and moves in the Form a line is drawn corresponding to the
mouse movement. Below Figure shows the combined action of MouseDown and MouseMove.

This program uses two graphics related Visual Basic concepts: for the Line method and the currentX and
CurrentY properties. Line method is preferred for drawing a line in a Form. The following statement draws a
line from the co-ordinates x=2500, y=2000 to x=5000, y = 5500
Line(2500,2000)-(5000,5500)
The CurrentX and CurrentY properties are not visible in the Properties window of the Form because it
cannot be set at the design time. After using the Line method to draw a line in a Form, Visual Basic
automatically assigns the co-ordinates of the line's end point to the CurrentX and Current Y properties of the
Form on which the line was drawn.

Visual Basic does not generate a MouseMove event for every pixel the mouse moves over and a limited
number of mouse messages are generated per second by the operating environment. The following application
illustrates how often the Form_MouseMove( ) procedure is executed.

Example
A new Standard EXE project is opened and the Form and the Project files are saved as [Link]
and [Link].
Object Property Setting
From Caption Mouse Move Application
Name frmMouseMove
CommandButton Caption &Clear
Name cmdClear
Font System
The following code is entered in the general declaration of the Form.
Option Explicit
The following code is entered in the Form MouseMove event procedures
Private Sub Form_MouseMove()
circle(X, Y), 70
End Sub
The above simply draws small circles at the mouse’s current location using the Circle method. The parameters
x, y represent the centre of the circle and the second parameter represent the radius of the circle.
Private Sub cmdClear_Click()
[Link]
End Sub

Dept. of Computer Science, HiSAC, Erode 39


Visual Basic – Unit II

The program is executed by pressing F5. When the mouse inside the Form, circles are drawn along the path of
the mouse movement as shown in below figure. When the clear button is clicked it clears off the circles from
the screen. The circles are widely spaced when the mouse is moved quickly and viva versa. Each small circle is
an indication that the MouseMove event occurred and Form_MouseMove( ) procedure was executed.

Dragging and Dropping


Dragging is the process of clicking the mouse button in a control and moving the mouse while holding down the
mouse button. The action of releasing the mouse button after the dragging is called dropping. The following drag and drop
properties, events and method a supported in Visual Basic.
• DragMode property enables automatic or manual dragging of a control. Draglcon property specifies the icon that is
displayed when the control is dragged.
• DragDrop event is recognized when a control is dropped onto the object. DragOver event is recognized when a
control is dragged over the object.
• Drag method starts or stops manual dragging.
All controls except menus, timers, lines and shapes support the above mentioned properties and method. Forms
recognize the Drag Drop and Drag Over events but they do not support the Drag method and the Drag mode and DragIcon
properties.
Example
Develop an application that illustrates the drag and drop operation the following steps have to be undertaken
• A new Standard EXE project is opened and saved.
• An Image control is added and it DragMode is set to 1-Automatic. Picture property is set to c:\vb\...\
[Link]. Its Stretch property is set to True.
• A TextBox and a CommandButton is added to the Form.
• The following code is entered in the declaration section of the Form.
Option Explicit
• The following code is entered in Form_DragDrop( ) procedure.
Private Sub Form_DragDrop(Source As Control, X As Single,
Y As Single)
[Link] = ““
[Link] X,Y
End Sub
• The following code is entered in Form_DragOver( ) procedure.
Private Sub Form_DragOver(Source As Control, X As Single,
Y As Single, State As Integer)
Dim Info As String
Info = “Now Dragging”
Info = Info + [Link]
Info = Info + "Over the Form"

Dept. of Computer Science, HiSAC, Erode 40


Visual Basic – Unit II

Info = Info + “State=”


Info = Info + Str(State)
[Link] = Info
End Sub
• The following code is entered in Commandl_DragOver() procedure.
Private Sub Commandl_DragOver(Source As Control, X As Single,
Y As Single, State As Integer)
Dim Info As String
Info = "Now Dragging"
Info = Info + [Link]
Info = Info + "Over the Exit button”
Info = Info + "State=”
Info = Info + StrState)
[Link] = Info
End Sub
• The following code is entered in Commandl_Click( ) procedure.
Private Sub Commandl_Click()
End
End Sub
• The Form is executed by pressing F5. When the Image is dragged over the Form it sage in the TextBox.
Similarly, a message is displayed when it is moved over the Exit button.

3.3 Dialog Boxes


Dialog Boxes are used to display information and to prompt the user about the data needed to continue an
application. There are three ways of adding dialog boxes to an application, which are as follows
• Predefined Dialog Boxes – Created using InputBox( ) and MsgBox( ) function.
• Custom Dialog Boxes – Created by adding controls to the Form or by customizing an existing dialog box.
• Standard Dialog Boxes - Created using Common Dialog Control.

Modal and Modeless Dialog Boxes


Dialog Boxes are either Model or Modeless. A Modal dialog box does not allow the user to continue with other
applications unless it is closed or unloaded. The Modeless dialog box allows shifting of focus between the
dialog box and another Form without closing the dialog box. For displaying a Form as a model dialog box we
can use the show method with a style argument 1 as given below.
[Link] 1
For displaying the Form as a modeless dialog box we use the show method without a style argument.
[Link]

Dept. of Computer Science, HiSAC, Erode 41


Visual Basic – Unit II

Predefined Dialog Boxes


Predefined dialog boxes can be added easily to an application. This uses the InputBox and MsgBox
functions. These dialog boxes are always model. Let us design a small program to get familiar with MsgBox( )
function.
Example
A new Standard Exe Project is opened and the Form and the project files are saved as [Link] and
[Link]. The program is designed as per table given below:
Object Property Setting
From Caption DISPLAY FORM
Name Form1
Menu items are added to the Form as table given below. The designed application is represented is shown in the
below figure:
Caption Name
&File mnuFile
…D&isplay mnuDisplay
- mnuSep1
…E&xir mnuExit

The following code is entered in mnuDisplay_Click( ) procedure.


Private Sub mnuDisplay_Click()
Dim Message As String
Dim DialogType As Integer
Dim Title As String
Message = “Hava a gala shooping”
DialogType = vbOK + vbinformation
Title = “Welcome to Super Market”
MsgBox Message, DialogType, Title
End Sub
The mnuDisplay_Click procedure updates the three variables Message, DialogType and Title that are used as
parameters to the MsgBox statement before executing it. As a result a message box appears as shown in the
below figure. vbOK and vbExclamation are VB constants that represent the OK icon and Exclamation point
icon. The following code in entered in mnuExit_Click( ) event procedure
Private Sub mnuExit_Click()
Dim Message As String
Dim DialogType As Integer
Dim Title As String
Dim Response As Integer
Message = “Thank You, Shop again”
DialogType = vbOK + vbinformation

Dept. of Computer Science, HiSAC, Erode 42


Visual Basic – Unit II

Title = “Good Bye”


Response = MsgBox Message, DialogType, Title
If Response = vbYes Then
End
End If
End Sub
The mnuExit_Click( ) procedure updates the variables Message, DialogType and Title. Once these three
variables are updated, Msg Box( ) function is executed and its return value is assigned to the variable
Response. The returned value of the MsgBox( ) function indicates the button that was clicked.

The MsgBox( ) function takes the same parameters as the MsgBox statement. The only difference between the
MsgBox statement and MsgBox( ) function is that the function returns a value. The returned value indicates the
button that was clicked in the dialog box.

This application is run by pressing F5. A form appears as shown in below figure. By clicking the Display item,
a dialog box with exclamation point icon and OK button appears. By clicking the Exit menu, a dialog box with
a message appears as shown in above figure. If Yes is clicked, the application terminates.

Using InputBox Function


The InputBox( ) Function displays a model dialog box that asks the user to enter some data. The dialog
box contains a message, an OK button and a Cancel button. The user can type in the TextBox and close the
Dialog box by clicking OK. The first parameter of the InputBox( ) function is the message of the dialog box and
second parameter is the title of the message box.
I = InputBox(“Enter a Date: “, “Date Demo”)
Let enhance the Dialogs program in order to understand the usage of InputBox( ) function. New menu
items are inserted before Exit menu item of the Dialog program. It should have the following characteristics.
Caption Name
…Get &Date mnuDate
…Get &Value mnuValue
- mnuSep2
The following code is entered in the event procedure mnuDate_Click().
Private Sub mnuDate_Click()
Dim I, Day, Msg
I = InputBox(“Enter a Date: “, “Date Demo”

Dept. of Computer Science, HiSAC, Erode 43


Visual Basic – Unit II

If Not IsDate(1) Then


MsgBox “Invalid Date”
Exit Sub
End If
Day = Format(I, “dddd”)
Msg = “Day of this date is: “ +Day
MsgBox Msg
End Sub
Whenever Get Date menu is clicked the code in the mnuDate Procedure asks the user to enter a date and verifies
if the date is valid. An InputBox with a message Enter a Date and Ok and Cancel buttons as shown in below:

When date is typed in the TextBox, the procedure determines whether it is valid date or not. If variable I is
filled with characters such as ABC or 1234 the condition. Not IsDate() is satisfied and it displayed a message
box with the message “Invalid Date”.

If the value entered is valid one such as 12/04/18, the condition Not IsDate(1) is not satisfied and the
user is prompted with a message box indicating the day of that date as shown in the below figure:

The following code is entered in the event procedure mnuValue_Click().


Private Sub mnuValue_Click()
Dim I As Integer
I = InputBox(“Enter a Value: “, “Input Demo”)
End Sub
When the menu Get Value item is clicked, it is displays an InputBox prompting the user to enter a value. This
procedure allows the user to enter only integer values in the TextBox. If the user enters a value other than an
integer it displays an error value.

Custom Dialog Control


A custom Dialog box is a Form that is created containing controls including CommandButton,
OptionButton and TextBox controls that supply information to the application. Custom dialog boxes are
customized by the user. The appearance of the Form is customized by setting the property values. Let us the
Dialogs in order to understand the methodology for designing a custom dialog and its use in a program.
Example
• The [Link] project is opened and a new Form is added to the project by selecting the Add Form from
the Project menu. The Form of the project is saved as [Link].

Dept. of Computer Science, HiSAC, Erode 44


Visual Basic – Unit II

• The [Link] is designed as per Table given below


Object Property Setting
From Caption DISPLAY FORM
Name Form2
MaxButton False
MinButton False
ControlBox False
Border Style 1-Fixed Single
OptionButton Caption Monday
Name Option1
OptionButton Caption Tuesday
Name Option2
OptionButton Caption Wednesday
Name Option3
OptionButton Caption Thursday
Name Option4
OptionButton Caption Friday
Name Option5
OptionButton Caption Saturday
Name Option6
OptionButton Caption Sunday
Name Option7
CommandButton Caption &OK
Name Command1
CommandButton Caption E&xit
Name Command2
The BorderStyle property of the Form2 dialog box is set to 1-fixed single and hence the size of the dialog box is
not changed during run time. The dialog box is displayed without a Control Menu at runtime because the
ControlBox property is set to False. The dialog box is displayed without using Minimize and Maximum button
since the Min Button and Max Button property of the Form2 is set to true.

• Two menu items are added to the Form1 of the [Link] project with the following characteristics. These
menu items are inserted above the Exit menu item.
Caption Name
…Get a Da&y mnuDay
- mnuSep3
The following code is entered in the mnuDay_Click( ) procedure of Form1
Private Sub mnuDay_Click()
[Link] 1
If [Link] = “ “ Then
MsgBox “Dialog Box is Cancelled”
Else
MsgBox “The Selected Day is: ” + [Link]
End If
End Sub

Dept. of Computer Science, HiSAC, Erode 45


Visual Basic – Unit II

When the menu item Get a Day is clicked, it displays the [Link] as a custom dialog box and prompts the
user to select a day. It also displays the day which is selected by using the Tag property of the Form2 dialog
box. The code uses [Link] to store the name of the day which is selected.

The following code is entered in Command1_Click( ) procedure of Form2.


Private Sub Command1_Click()
If Option1 = True Then [Link] = “Monday”
If Option2 = True Then [Link] = “Tuesday”
If Option3 = True Then [Link] = “Wednesday”
If Option4 = True Then [Link] = “Thursday”
If Option5 = True Then [Link] = “Friday”
If Option6 = True Then [Link] = “Saturday”
If Option7 = True Then [Link] = “Sunday, No Transaction”
[Link]
End Sub
Whenever the OK button of the Form2 dialog box is clicked, the code written in the procedure of
Command1_Click() procedure is executed. The If statement are used here to ascertain the option button that is
currently selected and accordingly updates the Tag property of the Form2 dialog box with the name of the
selected day. After the If statement, the procedure uses the Hide method to hide the Form2 dialog box. The Tag
property of the dialog box is used as the output of the dialog box. When the user selects the option Sunday, a
message box is displayed as shown below.

The following code is entered in the Command2_Click() procedure of Form2 dialog box.
Private Sub Command2_Click()
[Link] = “ “
[Link]
End
End Sub
Whenever the Exit button is clicked, the Tag property of the Form2 dialog box is set to null and the Hide
method hides the Form. Setting [Link] to null indicates that the user has clicked the Exit menu.

Using the Common Dialog Control


The Common Dialog Control is a custom control that displays the commonly used dialog boxes such as
Save As, Colour, Font, Print and File Open. When a common dialog control is drawn on a Form1 automatically
resizes itself and it is invisible at run time. The common dialog box is used as a dialog box that lets the user
select and save files.

Dept. of Computer Science, HiSAC, Erode 46


Visual Basic – Unit II

• Components is selected from the Project menu which displays a Components box.
• After ensuring that Common Dialog 6.0 Control CheckBox has a check mark in it, the OK is clicked
Example
• A new Standard EXE is opened and the Form and the project are saved as [Link] and [Link].
• The application is designed and menu items are added to the to the From as per below Tables specifications
• The designed Form is represented in below Figure
Object Property Setting
From Caption The Common Dialog Program
Name Form1
CommonDialog Cancel Error True
Name CommonDialog1

Caption Name
&File mnuFile
…Color mnuColour
…Open mnuOpen
- mnuSep
...E&xit mnuExit

The following code is entered in the mnuColour_Click( ) procedure.


Private Sub mnuColor_Click( )
On Error GoTo errortrap
[Link] = 3
[Link] = [Link]
Exit Sub
errortrap:
MsgBox "Dialog Box is cancelled."
End Sub
Whenever Colour menu is selected it displays a Colour dialog box as shown in below Figure.

Before displaying the dialog box, the mnuColour_Click( ) procedure sets an errortrap. The purpose of an
errortrap is to detect an error during the display of the dialog box. We have set the CancelError Property of the
Dept. of Computer Science, HiSAC, Erode 47
Visual Basic – Unit II

CommonDialog1 control to true at design time. Therefore, if Cancel button is pressed when the dialog box is
displayed, the errortrap, which has been set displays the “Dialog Box is Cancelled” and dialog box disappears.
However, if specific colour is selected from the dialog box and OK button is clicked the Back Colour of the
Form is changed to that particular colour. The following code is entered in the mnuOpen_Click( ) procedure.
Private Sub mnuOpen_Click()
Dim filter As String
On Error GoTo errortrap
fi1ter = “all files(*.*) | *.*”
[Link] = fi1ter
[Link] = 1
MsgBox "Selected file is: “+[Link]
Exit Sub
errortrap:
MsgBox “Dialog box is cancelled”
Exit Sub
End Sub
The above procedure displays an Open dialog box. Before displaying the dialog box, the first statement of the
mnuOpen_Click() procedure sets an errortrap which detects an error during the display of the dialog box. If
the Cancel button is pressed when the dialog box is displayed, the errortrap, which has been set, displays the
message “Dialog Box is cancelled” and the dialog box disappears. However, If a specific file is selected from
the dialog box the name of the selected file is displayed as a message box. The filter property of the
CommonDialog1 is set to the value of the filter variable Action property to 1, displays the Open dialog box
Private Sub mnuExit_CliCK )
End
End Sub
The above procedure terminates the application. Like Colour and Open dialog boxes, the properties of the
Common Dialog Control may used to determine the user’s response to the dialog box. Action property 4
displays the Font dialog box and 5 displays the Print dialog box.

RichTextBox Control
The RichTextBox control allows the user to enter and edit text while also providing more advanced
formatting feature than the conventional 'I'extBox control. It almost works like an editor. The RichTextBox
control provides a number of properties we can use to format any portion of text within control. Using these
properties, we can make the text bold or italic, change it colour, and create superscripts and subscripts. We can
also a paragraph formatting by setting both left and right indents, as well as hanging indents.

******

Dept. of Computer Science, HiSAC, Erode 48


Visual Basic – Unit II

4. Graphics, MDI and FlexGrid


4.1 Graphics For Application
Visual Basic provides a number of ways of creating and using graphics in an application, which adds
styles, interest and visual structure to the interface of an application. Graphic objects such as lines, circles and
bitmaps can be displayed in Visual Basic in a quicker and easier way. This section concentrates on two
approaches for creating graphics for an application using
• Graphical controls
• Graphics methods

Fundamentals of Graphics
Various controls and methods are used in Visual Basic to draw points, lines, boxes, circles and other
shapes and their location and appearance on a Form can be changed. There are some basic idea that is used for
creating graphics using twips, coordinate system and simple colour.

A twip is a unit that specific the dimensions and location of the object. The number of times a twip is
used by all Visual Basic movement. There are 1440 twips in one inch. These measurements designate the
object’s size then printed. The co-ordinate system is a two-dimensional grid that define location either on the
Form or any other container which or an any other container which is represented as (X, Y). A colour is
represented by a long integer and there are four ways of specifying it at run time; RGB function, using
QBColour function using one of the intrinsic constants in the Object Browser or by entering a colour value
directly.

The RGB( ) function enables the user to specify colours. The RGB( ) function has three arguments. The
value of the first argument represent amount of Red in the final colour the second argument represents Green
and the third represents Blue. The maximum value of each argument is 255 and minimum is 0. The following
statement uses the RGB function to give the colour red.
RGB (255, 0, 0)
The following statement returns yellow colour.
RGB (255, 255, 0)
QBColour function takes a single number that specifies a Quick Base colour number from 0 to 15 and returns a
long integer that can be used in the Visual Basic Colour property.
[Link] = QBColor (8)
This changes the background colour of the Form to grey.

Using Graphical Controls


Visual Basic provides three controls for creating graphical applications such as Line, Image and Shape.
These controls are very useful while design. The main advantage of graphics control is that user can create an
application with less code. Fewer system resources are sufficient than other VB controls.

Line Control
A Line control is a straight line segment that is drawn at design time. The position, length, color and
style of the Line control can be positioned to customize the look of the application.

Shape Control
A Shape control is a visual element that contains several predefined specified shape. In order to view a
specific shape, control is added to the Form by double clicking it. The default shape is rectangle. The Shape

Dept. of Computer Science, HiSAC, Erode 49


Visual Basic – Unit II

property is selected from the Properties window, which drops a list of shapes, from which a user can select the
desired one.

The FillColor and FillStyle properties of the Shape control can be changed so that the desired color and
style can be obtained.

Image Control
An Image control is a rectangular portion into which picture files can be loaded. Picture files include
bitmap files, icon files and metafiles. A bitmap also called "paint type" graphics defines an image as a pattern of
dots. It has a filename with extension .bmp. An icon is a special kind of bitmap with extension .ico.

Adding Pictures
Line control and Shape control are used for drawing geometric shapes such as lines, circle, squares,
and so on. For drawing more complex figures user can use a picture file. A picture file can be loaded on a
Form, Image control or Picture control. A picture can be added using the following two ways at design time.
• In the Properties window of the Form, the Picture property is selected. Visual Basic displays a dialog box
from which a picture file can be selected. The selected picture is displayed in the Form as its background.
Similarly a picture can be loaded in PictureBox and Image control.
• A picture can be copied from another application such as Paintbrush to the Clipboard and by selecting Paste
command from the Edit menu, the picture can be pasted onto a Form, Picture Box or Image Control.

A picture can be added using the following ways at run time.


• LoadPicture function is used to specify the filename and assign the picture to the Picture property.
• Any picture loaded to a Form, PictureBox or Image control can be copied to another Form, PictureBox or
Image control. The following statement copies a picture from Image control to a PictureBox.
Set [Link] = [Link]
• A picture can be copied from a Clipboard object.

Removing Pictures
A picture can be removed at run time using the LoadPicture function without arguments. The following
statement removes a picture from an image control at run time.
Set [Link] = LoadPicture(““)

Moving and Sizing Pictures


In a Form, PictureBox or an Image control is moved, the picture associated with it also moves
automatically. The AutoSize property of a picture box can be set to True in order to automatically expand and
accommodate a new picture at run time. The AutoSize property can also be used to shrink a control in order to
reflect the size of a picture. This property is not available in the Form and Image control but they automatically
size themselves to fit the picture loaded onto them.
Dept. of Computer Science, HiSAC, Erode 50
Visual Basic – Unit II

Stretch Property of an Image control is used to automatically resize a picture and place it inside the
control. When this property is set to True, the image control resizes the picture the desired size to fit into the
control. When this property is set to False, the control automatically adjusts its size to the size of the picture
loaded on to it.

Using Graphics Methods


The graphics method operates on controls such as Form, Picture Box or Printer forms run time drawing
operations such as animation or simulation. Visual Basic offers several methods such as Cls, PSet, Point to
create graphics applications. The graphics method offers some visual effects that are not available in the
graphics controls. For example individual pixels can be painted only by using graphics method. PSet’s method
sets the colour of an individual pixel. Every graphics method draws output on a Form, PictureBox or to the
Printer following statement draws a point on a Form named Form1.
[Link](500, 500)
The PSet method draws a point at x, y co-ordinates that are specified by its arguments. Cls method clears all the
graphics. The following statement clears the Form Form1.
[Link]
The Point method returns the colour of a particular pixel. For example the following Statement is used to find
the colour of the pixel at location 30, 40.
PixelColor = Point(30, 40)
The Line method draws a line, rectangle or filled-in text box. The Line method has the following syntax.
Line(xl, yl)-(x2, y2), Color
where (xl, yl) is the co-ordinate of the starting point and (x2, y2) is the co-ordinate of the ending point of the
line. If the co-ordinates xl, yl are omitted, the line is drawn starting at the co-ordinate CurrentX, CurrentY. The
following statement draws a slanted line on the Form.
Line(600,600) - (2000,2000)
An optional step argument can be used with the Line method as follows.
Line(xl, yl) – Step(dX, dY), Color
where (xl, yl) are the co-ordinates of the starting point and Step(dX, dY) is an indication that the end point of
the line is at xl+dX, yl+dY. The following statement draws a line with the starting point co-ordinates 30, 40 and
ending point co-ordinate 80, 140.
Line(30,40)- Step(50,100)
The Line method is used to draw and fill boxes. The following example draws a box with its upper left corner at
(600, 600) and measuring 1000 twips on each side.
Line(600, 600) - Step(1000, 0)
Line - Step(0, 1000)
Line - Step(-1000, 0)
Line - Step(0, -1000)
Visual Basic provides a much simpler way to draw a box, which replaces the above four statements into a single
statement as given below.
Line(600, 600) - Step(1000, 1000), , B
B option is used with the Line method. This causes a box to be drawn using the coor0dantes to specify opposite
corners of the box. It is to be noted that two commas are required before B to indicate that the colour argument
has been skipped.

Dept. of Computer Science, HiSAC, Erode 51


Visual Basic – Unit II

A circle method is used to draw a variety of circular and elliptical shapes. To draw a circle, Visual Basic
requires the location of the circle's centre and the length of its radius. The following statement draws a circle
with a center(1400, 1200) and radius 650.
Circle(l400,1200), 650

4.2 Multiple Document Interface (MDI)


MDI stands for Multiple Document Interface. A Multiple Document Interface is used for opening many
windows at the same time. All the document windows are contained in a parent window, which provides a
workspace in the application. Visual Basic applications can have only one MDI Form, which contains all the
Child Forms. A Child Form is an ordinary Form that has its Child property set to True. Child Forms are
displayed within the internal area of an MDI Form at run time.

Creating an MDI Application


The Multiple Document Interface can be designed for document-centred applications. This application
allows the user to open many similar documents at the same time. To create a document-centred application in
Visual Basic, we require atleast two Forms, an MDI Form and a Child Form. This application is designed
similar to the Notepad application in Microsoft Windows. Each time the user clicks New from the File menu, a
new Child window is created and displayed.
Example
• A new Standard EXE project is opened. An MDI Form is inserted by selecting Add MDI Form from the
Project menu. The Project now contains a standard Form and an MDI Form. The project is saved as
[Link]. The Form is saved as [Link] and the MDI Form as [Link],
• A TextBox is added in the standard Form. The two Forms are designed as per below specifications.
Object Property Setting
MDIFrom1 Caption Parent Form
Form1 Caption Child Form
MDIChild True
Text1 MultiLine True
Text (Empty)
Left 0
Top 0
Height 2295
Width 3015
ScrollBars 3-Both
Menu items are added to the MDI Form as per the specifications shown in above Table. The designed Forms
1ooks like resemble the one shown in the below Figure
Caption Name
&File mnuFile
…&New mnuNew
…E&xit mnuExit
&Window mnuWindow
...&Cascade mnuCascade
...&Tile mnuTile

Dept. of Computer Science, HiSAC, Erode 52


Visual Basic – Unit II

The following code is entered in the mnuNew_Click() procedure of the MDIForm1.


Private Sub mnuNew_Click()
Dim NewForm As New Forml
[Link]
End Sub

The first statement in the above procedure declares a variable called NewForm as a copy of the Child Form
Form1. This implies that, for all purposes, the NewForm can be referred to as an instance of the Form1 with the
same properties that Form1 had at the time of design. The second statement in the procedure causes the newly
created Form to pop up. Every time when the menu item New is clicked in the MDI form, a new Form pops up.
The following code is entered in the mnuTile_Click( ) procedure of the MDI form.
Private Sub mnuTile_Click()
[Link] vbTi1eHorizonta1
End Sub
The code in the mnuTile_Click() procedure uses the Arrange method with vbTileHorizontal as the argument
to Tile the Child Forms. Below Figure represents the Forms in Tile arrangement. This procedure is executed
when the menu item Tile is clicked. The following code is entered in the mnuCascade_Click( ) procedure of the
MDI form.

Private Sub mnuTile_Click()


[Link] vbCascade
End Sub

Dept. of Computer Science, HiSAC, Erode 53


Visual Basic – Unit II

The code in the mnuCascade_Click( ) procedure uses the Arrange method with vbCascade as the argument to
cascade the Child Forms. Below Figure represents the cascaded forms. The following code is entered in the
mnuExit_Click( ) procedure.
Private Sub mnuTile_Click()
End
End Sub
When the menu Exit is clicked, the application terminates.

Adjusting the TextBox


The Text Box in the Child Form can be adjusted to the same size of the Child Form Form1. This can be
incorporated in to the Resize event. The Resize event is fired whenever the size of the Form is changed.
Therefore, the Form_Resize( ) procedure is a focal point that is executed whenever the Form size of the Form
changes. The following code is entered in the Form_Resize( ) procedure of the Form1 Child Form.
Private Sub Form_Resize()
[Link] = [Link]
[Link] = [Link]
End Sub
The first statement of the above procedure assigns the ScaleHeight property of the current Form to the Height
property of the TextBox and the second statement assigns the ScaleWidth of the Form to the width of the
TextBox. Hence the TextBox has the size of the current Form as represented in below Figure.

The Me reserved word used in the Form_Rcsizc( ) procedure is a variable containing the name of the
Form where the code is currently executed. The Me keyword in Visual Basic behaves like an implicitly declared
variable. For example, in the above program, there may be several instance of the child form in the parent form.
When the size of one of these forms is changed, the Form_Resize( ) procedure is executed and automatically
updates the Me variable with the instance that was resized.

Creating a Toolbar
Most of the Windows programs include a Toolbar, which is an area containing control to provide quick
access to the most commonly used operations. Toolbar is also called a ribbon bar or control bar. In order to add
a Toolbar item, the MDI form is selected and the Picture control in the Toolbox is double clicked. Visual Basic
responds by displaying a PictureBox control in the Form as shown in below Figure.

Dept. of Computer Science, HiSAC, Erode 54


Visual Basic – Unit II

Displaying a Status Bar


Status bars are similar to the toolbars except that the status bar appears at the bottom of an MDI
form. The Picturelsox can be displayed at the bottom of the Form by setting the 1 1s property to 2-Align
Bottom. A status bar may display information about the currently selected object or the state of an application.

4.3 Using the FlexGrid Control


An MSFlexGrid control in Visual Basic is used to create applications that present information in row
and column. It displays information in cells. A cell is a location in the MSFlexGrid at which a row and a
column intersect. The user can select a cell at run time by clicking it or by using the arrow keys, but cannot edit
or alter the cell’s contents. The 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 read-only data.

User can place text, or a picture, or both in any cell of an MSFlexGrid. The Row and Col properties
specify the current cell in an MSFlexGrid. We can specify the current cell in code, or the user can change it at
run time using the mouse or the arrow keys. The Text property references the contents of the current cell. If a
cell's text is too long to be displayed 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, we need to increase the cell's column width
(ColWidth property) or row height (RowHeight property). The Cols and Rows properties are used to determine
the number of columns and row in an MSFlexGrid control.

Two kinds of rows or columns are created in the MSFlexGrid control. They are fixed and non-fixed. A
non-fixed row or column scrolls when the scroll bars are active in the MSFlexGrid control. A fixed row or
column does not scroll at any time. FixedRows or FixedCols is generally used for displaying headings. Rows
and columns are created by setting the four properties of the MSFlexGrid control such as Rows, Cols,
FixedRows and FixedCols. Since the MSFlexGrid control is an OCX control, user must make sure whether the
control is included in the project. If the control does not appear in the ToolBox, it is added by selecting
Components from Project menu and placing a check mark in the Microsoft MSFlcxGrid Control. This places
the control in the ToolBox.

Example
This example uses a MSFlexGrid to view the sales of a particular item in a particular month.
• Start a new Standard Exe project from the New project dialog box.
• The Form is designed as shown below.

• To add the FlexGrid, choose Components from the Project menu and check on the Microsoft Flexgrid
Control 6.0.
• The two combo boxes are named itemname and mnthname respectively.
• The MSFlexgrid is named as itmdet.
• The command button with caption Add shown in the above Figure is named as Add.
Dept. of Computer Science, HiSAC, Erode 55
Visual Basic – Unit II

• In the general declarations section of the Form, the following code is entered to initialize two arrays.
Dim arrl(12) As String
Dim itm(6) As String
Dim i As Integer
• The following code is entered in the Form Load event:
itm(0) = “Stationeries”
itm(1) = “Groceries”
itm(2) = “Milk Products”
itm(3) = “Confectionaries”
itm(4) = “House hold item”
itm(5) = “Toys”
arrl (0) = "Jan"
arrl (1) = "Feb"
arrl (2) = "Mar"
arrl (3) = "Apr"
arrl (4) = "May"
arrl (5) = "Jun"
arrl (6) = "Jul"
arrl (7) = "Aug"
arrl (8) = "Sep"
arrl(9) = "Oct"
arrl(10) = "Nov"
arrl(l1) = "Dec"
[Link] = 0
For i = 0 To 11
[Link] = i + 1
[Link] = arrl(i)
[Link] arrl(i)
Next
itmdet.Co1 = 0
For i = 0 To 5
[Link] = i + 1
[Link] = itm(i)
[Link] itm(i)
Next
The two arrays are initialized itm, arrl are initialized in the Form Load. The first "For loop" shown above adds
the names of the month in the 0th row. The second "For loop" adds the names of the items in the 0th column.
• The following code is entered in the Add Button’s click event:
[Link] = [Link] + 1
[Link] = [Link] + 1
[Link] = Str(Val([Link]) + Val([Link]))

This event procedure stores the value of the sale of the item for the month specified.
Example
• A new Standard EXE project is opened and the Form of the project is saved as [Link]
and the project file is saved as [Link].

Dept. of Computer Science, HiSAC, Erode 56


Visual Basic – Unit II

• MSFlexGrid control is placed in the Form by double clicking it. After placing it, the Rows property of the
MSFlexGrid is set to 7 and Cols property to 4.16.
• The Caption property of the Form is changed to MSFLEXGRIDAPPLICATION.
• After setting the properties, the MSFlexGrid control is enlarged vertically and horizontally by dragging its
handles.
• Now, the Form is designed as per the specification given above looks like the one shown in below Figure. A
menu title File is placed with a menu item Clear in the Form.

The following code is entered in the general declarations section of the Form.
Option Explicit
The following code is entered in the Form_Load( ) procedure of the Form1
Private Sub Form_Load()
[Link] = 0
[Link] = 1
[Link] = "OF"
[Link] = 2
[Link] = "IMPACT"
[Link] = 3
[Link] = "IMP_NET"
[Link] = 0
[Link] = 1
[Link] = "Jan-Feb"
[Link] = 2
[Link] = "Mar-Apr"
[Link] = 3
[Link] = "May-Jun"
[Link] = 4
[Link] = "Jul-Aug"
[Link] = 5
[Link] = "Sep-Oct"
[Link] = 6
[Link] = "Nov-Dec"
End Sub
The application is run by pressing F5. The program displays a FlexGrid control with seven rows and four
columns displaying the text in the top heading row and the left heading column. The FlexGrid control displays
information in a tabular format. Each cell can be viewed by using the arrow keys but values cannot be entered
directly into cells. The FlexGrid control has both the properties Row and Rows. Similarly it has properties Col
and Cols. Rows and Col properties can be set both during the design time and run tune whereas, the Row and
Col properties are set into action only during run time.

Changing the Cell Width and Cell Height


The height and width of the cells in the FlexGrid control can be widened in order to get a clear picture at
run time. A procedure is added to the Form by selecting the Add Procedure command from the Project menu
in the Code Window. The new procedure is named as SetColWidth. The following code is entered in the
SetColWidth( ) procedure.
Public Sub SetColWidth()
Dim counter

Dept. of Computer Science, HiSAC, Erode 57


Visual Basic – Unit II

For counter = 0 to 3 Step 1


[Link](counter) = 1000
Next
End Sub
The code in this procedure uses a "For loop" to change the ColWidth property of each of the column to 1000
twips. The ColWidth property determines the width of the column. [Link](0) determine the width
of column 0, and [Link](1) determine the width of column 1 and so on. This statement
SetCoJWidth is added to the end of the Form_Load ( ) procedure along with the code written previously.

Another procedure called SetRowHeight( ) is added by selecting from the Project menu and it is added
to the code. The following code is entered in the SetRowHeight( ) procedure.
Public Sub SetRowHeight()
Dim counter
For counter = 0 To 6 Step 1
[Link](counter) = 350
Next
End Sub
The code in this procedure uses a "For loop" to change the height of each of the rows to 350 twips. The
RowHeight property determines the height of the cell. The SetRowHeight statement is added to the end of the
Form_Load( ) procedure as shown below.
Private Sub Form_Load()
..................................
.....Same Code written as before.....
SetRowHeight
SetColWidth
End Sub

Entering Values in the Column


The rest of the cells are filled with values by calling a procedure FillValues in the Form_Load( )
procedure. A new procedure called FillValues is inserted in the general declaration section of the Form. The
following code is entered in the procedure FillValues( )
Public sub FillValue()
Dim colcounter, rowcounter
For colcounter = 1 To 3 Step 1
[Link] = colcounter
For rowcounter = 1 To 6 Step 1
[Link] = rowcounter
[Link] = "NIL"
Next
Next
End Sub
To fill a specific cell with data, the following statements are added to the end of FillValues( ) procedure.
Public Sub FillValues( )
...........
...........
[Link] = 1
[Link] = 1

Dept. of Computer Science, HiSAC, Erode 58


Visual Basic – Unit II

[Link] = "120"
[Link] = 2
[Link] = 1
FlexGrid1. Text = "150"
[Link] = 3
[Link] = 2
[Link] = “180"
[Link] = 4
FlexGrid1.Co1 = 2
[Link] = "210"
[Link] = 5
FlexGrid1.Co1 = 3
[Link] = "240"
[Link] = 6
[Link] = 3
[Link] = "270"
End Sub
The code which is added in the FillValues( ) procedure fills six cells in the FlexGrid by selecting the
Row and Col properties with the required row number and column number, and then sets the Text property of
the cell with the desired text. Below Figure represent a FlexGrid control with values filled in the specified cells.

Scroll Bars of the FlexGrid Control


Visual Basic automatically adds horizontal and vertical scroll bars in the FlexGrid control when the cells
do not fit into it. This is because the default values of the ScrollBar property of the FlexGrid control is set to 3-
Both. If we do not want the scroll bars to appear, the ScrollBars property is set to 0-None at design time or the
following code is added in the Form_Load( ) procedure.
[Link] = 0
Similarly, a FlexGrid control can be displayed with a single vertical scroll bar or horizontal scroll bar at run
time by setting the ScrollBars property at design time.

A FlexGrid control includes a property called FlexGridLines, which can be set to either True or False. The
default setting is True, which causes the control to appear with visible grid lines. If this property is set to False,
the control is shown without grid lines.
*******

Dept. of Computer Science, HiSAC, Erode 59


Visual Basic – Unit III

5. ODBC and Access Objects


Data Access Options
VB provides a variety of options to access remote Client / Server database. They are:
• Date Access Objects (DAO). It communicates with data source through the JET database
engine.
• Data Control. It binds data-ware controls to Microsoft Access and other ODBC data sources.
• ODBC Direct. It allows of ODBC data source through the RDO with DAO objects, bypassing the JET
database engine.
• Remote Data Objects (RDO). It provides a framework for using code to create manipulate components of
a remote ODBC database system.
• Open Database Connectivity (ODBC). This is an API call interface to the Open Database Connectivity
libraries and drivers to provide data access to Oracle and other databases that provide an ODBC driver.
• Visual Basic Library for SQL Server (VBSQL). It is an implementation of the DB library API
specifically designed to provide access to an SQL server through a Visual Basic application.
• Active Data Objects (ADO). This is a programming model that eliminates the need to choose from among
DAO and RDO and all other data access methods. It is designed to provide a common bridge between
different databases, file systems and e-mail servers.

Data Access Objects


A Data Access Object is a collection of object classes that model the structure of a relational database
system. They provide properties and methods that allow the user to accomplish all the operations needed to
manage such a system, including features for creating databases, defining tables, navigating and querying a
database. Visual Basic supports Data Access Object such as the DBEngine, Workspace, Database, TableDef,
Field, Index and Recordset Objects. Below Figure shows the Data Access Objects hierarchy.

Dept. of Computer Science, HiSAC, Erode 61


Visual Basic – Unit III

The DBEngine is the top-level database object and corresponds to the Jet database engine. This object is
used to set database engine system parameters and default workspace. The Workspace object is used to support
simultaneous transaction and it acts and it acts as a container for open databases. A default Workspace objects
Workspace (0) is created when the Data Access Objects are referenced in the language at run time. The default
workspace is always available and can never or removed from the collection.
• The Database object corresponds to a Jet native or external database or a direct ODBC connection. This us
used to define the database’s table, relations and stored queries and to open Recordset objects.
• The TableDef object corresponds to a stored table definition. Each TableDef in a collection represents the
definition of a table in the current database or an attached table in the external database.
• The QueryDef object is a stored query definition, which is precompiled SQL statement.
• The Recordset object corresponds to a cursored view into a database table or the results of a query. A
cursored view is one that stores rows of data in buffer and points to one row of data at a time called
current record. The cursor may be positioned to any row of data using Move, Seek or Find methods.
• The Field object corresponds to a column of data type and set of properties. TableDef, QueryDef and
Recordset objects have a collection of Field objects. The collection of Field objects associated with a
Recordset cursor describes a single row of data.
• The Index object is a stored index associated with TableDef objects or table type Recordset object. Setting
the index allows the user to quickly re-order the record in a table.
• The Parameter object represents a parameter associated with a QueryDef object created from a parameter
query. A Parameter's collection contains all the Parameter object of a QueryDef object.
• The User object used to define and enforce database security. The DBEngineobject supports a set of user’s
collection. The Users collection contains all stored User object of a Workspace or group account.
• A Group is a collection of users with similar access rights. The DBEngine Object supports a collection of
system groups. Each user in the group inherits the permission to access the objects that the group can
access.
• A Relation object represents a relationship between field in a table or queries. A Relation collection contains
stored Relation objects of a database object. The DBEngine enforces certain update and delete conditions on
the data associated with the fields of the Relation object, to maintain referential integrity.
• A Property object represents a built-in characteristics or used defined characteristics of a data access object.
Properties collection contains all the Property objects for a specific instance of an object.
• A Document object includes information about one instance of a type of object. The object can be a
database, saved table, query or relationship. A Documents collection contains all of the Document objects
for a specific type of object.
• A Container objects holds information describing the objects that are grouped container. A containers
collection contains all Container objects that are defined in a database.

Accessing and Navigating Databases


In order to work with data access objects, a reference has to be set to the appropriate DAO library. There are
two DAO libraries supported by VB 6.0. They are
• Microsoft DAO 3.51 Object Library
• Microsoft DAO 2.5 / 3.51 Compatibility Layer.
To set a reference to the DAO type library the following sequence has to followed
• Select References from the Project Menu.
• Select DAO 3.51 Object Library
• Click on OK

Dept. of Computer Science, HiSAC, Erode 62


Visual Basic – Unit III

Opening a Database
To open an existing database, the OpenDatabase method of the Workspace object is used.
Syntax
OpenDatabase(dbname,[options],[readonly],[connect])

The following code opens the employee_details database.


Dim db as Database
Set db = OpenDatabase("emp1oyee_detai1s")
In the above code, db is a variable that represents the Database object. By default, a database that is opened can
be shared and modified by any user. To specify that the database is to be opened for exclusive use, the
following statement can be used.
Set db = OpenDatabase("employee_details",True)
In the above statement the true value indicates that no other users will be able to open the database. The
default value is False.

To open the employee_details database in the read only mode, the following statement is used.
Set db = OpenDatabase("emp1oyee_detail",Fa1se,True)
In the above statement, the True value specified as the third argument will provide only read access on the
database.

Recordset
A Reeordset is an object that contains a set of records from the database. There are five major types of
Recordset objects.

Table Type Recordset


The table type Recordset object is a set of records that represents a single table which can be used to
add, change or delete records. They are the fastest type of Recordsets.

Dynaset-Type Recordset
The dynaset type Recordset object is a set of records that represents a table, or attached tables, or the
results of queries containing fields from one or more tables. A dynaset enables us to update data from more than
one table.

Snapshot Type Recordset


The snapshot type Recordset can refer to any table, attached table or query. A snapshot cannot be
updated and does not reflect any changes made by the users.

Dynamic Type Recordset


This type of Recordset represents a query result set from one or more base tables in which we can add,
change, or delete records from a row-returning query. Further, records that other users add, delete, or edit in the
base tables also appear in the Recordset. This type is only available in ODBCDirect workspaces, and
corresponds to an ODBCdynamic cursor.

Forward Only Type Recordset


This type of Recordset is identical to the snapshot Recordset except that we can only scroll forward
through its records. This improves performance in situations where we only need to make a single pass through
a result set. In an ODBCDirect workspace, this type corresponds to an ODBC forward-only cursor.

Dept. of Computer Science, HiSAC, Erode 63


Visual Basic – Unit III

Creating a Recordset
The OpenRecordset method is used to open a Recordset and create a Recordset variable.

Example
To create a read only Recordset for the table employee, the following code is used.
Dim rs as Recordset
Set rs = [Link]("employee",dbOpentable, dbReadOnly)
In the above statement, db is the variable that represents the Database object. Here db Open Table specifies the
type of Recordset to be created.

Navigating a Recordset
After creating a Recordset object, various Move methods can be used to navigate through the records in a
Recordset.
• The MoveFirst method moves to the first row in the Recordset
• The MoveNext method moves to the next row in the Recordset.
• The MovePrevious method moves to the previous row in the Recordset.
• The MoveLast method moves to the last row in the Recordset.

Using BOF and EOF to Navigate through Recordsets


The Recordset object provides two properties to the user to know when he has moved in the beginning
or the end of the recordset.
• The EOF (End of File) property is True when the user moves beyond the last record in the recordset.
• The BOF (Beginning of File) property is True when the user has moved to a position before the first
record in the recorded.

Modifying and Deleting Records


To manipulate a record in a recordset, the following methods are used.
Edit Method. The user can edit the current record using the Edit method. The Update method is used to save
the necessary changes made to the record.
AddNew Method. Add New method is used to create a new record in the Recordset.
Delete Method. This method can be used to delete an existing record in the dynaset or table type Recordset.
The Jet engine deletes the current record without any warning when the Delete method is used.

Finding RecordSet
The Find methods can be used to locate a record in a dynaset or snapshot type Recordset. Visual Basic
supports four Find methods.
• FindFirst method finds the first record satisfying the specified criteria.
• FindLast method finds the last record satisfying the specified criteria.
• FindNext method finds the next record satisfying the specified criteria, searching forward from the current
record.
• FindPrevious method finds the previous record satisfying the specified criteria, searching backward from
the current record.
When the database engine finds a match for the criteria that is specified, it moves to that record. If no match is
found, the current record is unchanged and the Recordset object's No Match property is set to true.

Dept. of Computer Science, HiSAC, Erode 64


Visual Basic – Unit III

Performing Indexed Searches using the Seek Method


The Seek method can be used to locate a record in a table type Recordset. This method performs an
indexed search for the first occurrence of the record that matches the indexed criteria. Dynasets and Snapshots
cannot use the Seek method.

Manipulating Stored Queries using the QueryDef Object


The QueryDef object contains information about a stored SQL query. QueryDef objects run faster than
SQL queries because Visual Basic must go through a processing step before executing a SQL query. Stored
queries are stored in their processed format. There are two basic methods for working with QueryDefs. They are
• Execute method
• OpenRecordset method
The Execute method is used to perform action queries. Action queries are SQL statements that perform some
action on the database. The OpenRecordset method is used to retrieve data from the tables.

Creating Parameterized Queries using the Parameter Object


Parameter query can be created by using the Parameters Collection of a QueryDef object. A value must
be supplied for the parameter in order to run the query.

TableDef Data Object


TableDef is a collection Table objects that contain detailed definition about each data table in the
database. There are five methods available that can be used with Tabledef object.
• OpenRecordset method is used to open a table – Dynaset or Snapshot Recordset from the TableDef object.
• RefreshLink method updates and refreshes any attached table links for the TableDef object.
• CreateProperty method is used to create and store a user-defined propery.
• CreateIndex method is used to add an index to the TableDef object.
• CreateField method is used to add a new field to an existing TableDef object.

Modifying and Deleting Existing Tables


New field can be added or existing fields can be deleted using the Append or Delete methods
respectively on the Tabledef object.

Creating a Table in Oracle using SQL*Plus


A table is created in SQL * Plus using the following syntax.
CREATE TABLE <table name>
(column_namel datatype, column_name2 datatype, ...)

Inserting Values in a Table


The INSERT command is used to add rows to a table.
Syntax
INSERT into <table name> VALUES <data list>
The data entered in the-table should match the order of the columns as they appear in the table.

********

Dept. of Computer Science, HiSAC, Erode 65


Visual Basic – Unit III

ODBC using Data Access Objects and Remote Data Objects

Open Database Connectivity (ODBC)


Open database connectivity (ODBC) is a Windows technology that lets a database client application
connect to an external database. To use ODBC, the database vendor must provide an ODBC driver for data
access. Once this driver is available, the client machine should be configured with this driver. The destination of
the database, login id and password should also to be configured on every client machine. This is called a Data
Source. The user can configure multiple data sources with same or different drivers on the same machine. Thus
using ODBC, it is possible to access heterogeneous data from any client. The Open Database Connectivity
architecture is shown below. ODBC has three parts. They are
• A driver manager
• One or more drivers
• One or more data Sources
Client ODBC Data ODBC Driver ODBC Driver
Application Source Manager

Creating an ODBC Data Source


Before any application can access an ODBC database, the ODBC drivers must be installed and a Data
Source Name (DNS) created using the control panel. The DSN is used whenever a reference is made is an
ODBC database. The following sequence of steps has to be undertaken to set up an Oracle data source.
• Double click on the ODBC configuration option under the control panel
• A list of ODBC data sources will be displayed.
• Note that various data sources associated with various drivers exist. User objective is to create a new data
source using the ODBC driver for Oracle.
• Select the Add button to add a new ODBC data source. Lists of ODBC drivers that are currently installed in
the system are displayed. Select the ODBC driver for Oracle.
Steps for Creating an ODSC Data Source Name on the Client
1. Double click on the Oracle ODBC driver. The Oracle DSN configuration dialog box is displayed as shown
in below Figure. This screen gathers login and connection information.

Dept. of Computer Science, HiSAC, Erode 66


Visual Basic – Unit III

2. Enter the Data Source Name as XYZ Company in the Data Source Name box. Enter the description as XYZ
company database in the Description box. Provide the user name as user1 and the server name as server1.
3. Click the Next button to continue and display the screen that allows us to choose more options.
4. Click the select button that allows us to choose appropriate translators.
5. To see the list of ODBC drivers installed in the system, the drivers tab must be clicked. This is illustrated in
the below figure

Using ODBC with DAO


The properties and methods of DAO can be used in conjunction with the ODBC type database.
OpenDatabase
The OpenDatabase method creates a connection between the application and the ODBC database and assigns it
to a database type object.
Syntax
Dim db as Database
Set db = OpenDatabase("<Data Source name>", <dbdriverpromptinformation>,
<Readon1y>,"ODBC;UID=<User ID>; PWD=<Password>”)

db is a variable that represents the Database object.

Example The senior manager of an XYZ company wants to view the details of all the employees in the
company. In order to Navigate through a Recordset the following steps have to be used.
• Add a new Form to the project and set its caption as Emp Details.
• Add controls - six label controls, six textboxes and nine command buttons to the Form as shown below.

Dept. of Computer Science, HiSAC, Erode 67


Visual Basic – Unit III

In the General declaration section of the form, a Database object db and RecordSet object rs are declared.
Dim db As Database
Dim rs As Recordset
The emp_details database in Oracle using the data source name XYZ Company can be accessed using the
OpenDatabase method on loading the form. The code for this is included in the Form_Load event. Further, in
order to retrieve the data from table emp, the OpenRecordset method in association with the database object db
is called and the resulting data is set into the Recordset rs. The textboxes are then assigned with the field values
of a particular record using the Recordset variable. The txt_empno.text = [Link] ("Emp_no") assigns the value
of the Emp_no in the bracket to the text property of a textbox txt_empno. The other field values are assigned in
a similar way. The following code has to be attached in the Form_Load event procedure.
Private Sub Form_Load()
Set db = OpenDatabase("XYZCompany",Fa1se,Fa1se,_
"ODBC;UID=USERl;PWD=SSI;DSN:"XYZCompany)
Set rs = [Link]("select * from emp")
Txt_empno.Text= [Link](“Emp_no")
Txt_name.Text= [Link]("Emp_name")
Txt_sal.Text= [Link](“Sal")
Txt_date.Text= [Link]("Joindate")
Txt_dept.Text= rs.Fie1ds("Dept_no")
Txt_desig.Text= [Link]("Desig")
End Sub
To move to the First, Last, Previous and Next records, the following code has to be attached to the Click event of
the Command buttons cmdFirst, cmdLast, cmdPrev and cmdNext. The MoveFirst method is used to point a recordset to
the first record of the recordset. Similarly MoveLast points in the last record of the recordset. MoveNext method is used
in the recordset to the next record from the currently accessing one and MovePrevious in point to the previous record
from the current one. The MoveFirst, MoveNext, MovePrevious and MoveLast methods are activated in the click events
of the respective command buttons cmdFirst, cmdNext, cmdPrevious and cmdLast.
Private Sub cmdFirst_Click()
[Link]
MoveFields
End sub

Private Sub cmdLast_Click()


[Link]
MoveFields
End Sub

Private Sub cmdPrev_Click()


[Link]
If [Link] Then
[Link]
End If
MoveFields
End Sub

Private Sub cmdNext_Click()


[Link]
If [Link] Then
[Link]
End If
MoveFields
End Sub

Dept. of Computer Science, HiSAC, Erode 68


Visual Basic – Unit III

When a new employee is appointed in the company, his details have to be added to the database table.
The AddNew method of the Recordset object is applied to add a new record. The coding to add a new record is
added in the click event of the cmdAdd command button.
Private Sub cmdAdd_Click()
Txt_empno.Text = ""
Txt_name.Text = ""
Txt_sal.Text = ""
Txt_date.Text = ""
Txt_dept.Text = ""
Txt_desig.Text = ""
[Link]
End Sub

The AddNew method of the Recordset object is used to add a new row (an empty record) to the
recordset. Once the AddNew method is applied to the recordset, the edit buffer is created with the empty record
in it. The user is then entitled to enter the required data into the field objects associated with that Recordset.
Finally calling the Update method saves the changes. The user has to save the changes after entering the details.
When the user clicks the command button cmdSave, all the changes that are made to the database are saved.
Private Sub cmdSave_Click()
If [Link] = dbEditAdd then
rs("Emp_no") = Txt_empno.Text
rs("Emp name") = Txt [Link]
rs("sal") = Txt_sal.Text
rs("Joinmdate") = Txt [Link]
rs("Dept_no") = Txt_dept.Text
rs(“Desig") = Txt_desig.Text
End If
[Link]
End Sub
The Update method of the Recordset object saves the contents of the edit buffer to the Recordset object.

Whenever an employee is promoted, or any changes have to be made to his salary field or designation field, his
relevant record has to be modified accordingly. In order to implement this, the record must be in the Edit mode.
On clicking the modify button, [Link] method sets the record to the edit mode and the changes are made. The
changes are assigned to respective fields and are saved by clicking the Save button. The [Link] method saves
the changes made to the record.
Private Sub cmdModify_Click()
If [Link] = dbEditNone Then
[Link]
End If
End Sub
When a particular employee retires from the company, his relevant record has to be deleted from the database.
The Delete method of the Recordset object is used to implement this and the Recordset pointer is moved to the
next record. If the record to be deleted is the last record, then the Recordset is set to the last record using the
statement [Link].
Private Sub cmdDelete_Click()
[Link]
[Link]

Dept. of Computer Science, HiSAC, Erode 69


Visual Basic – Unit III

If [Link] Then
[Link]
End If
MoveFields
End Sub
Create a Sub procedure called Movefields and attach the following code. In this procedure, the values of the
fields of the Recordset are assigned to the text property of the textboxes.
Public Sub MoveFields()
Txt_empno=rs("Emp_no")
Txt_name=rs(" Emp_name")
Txt_sal=rs("sal")
Txt_date=rs("Hiredate")
Txt_dept=rs("Dept_no")
Txt_Desig = rs("Des;g")
End Sub

Finding a Specific Record


A particular record from a table can also be viewed using Find methods. For examp1e, a particular
employee based on the emp_no can be viewed. VB supports four Find methods.
• FindFirst method finds the first record satisfying the specified criteria, searching forward from the
beginning of the Recordset.
• FindLast method finds the last record satisfying the specified criteria, searching backward from the end of
the Recordset.
• FindPrevious method finds the previous record satisfying the specified criteria, searching backward from
the current record.
• FindNext method finds the first record satisfying the specified criteria, searching forward from the current
record.
When Find methods are used, search criteria are specified, typically equating a field name with a specified
value.

Example The following example fetches a record from the Employee table, using the Find method, where
empname = "Allen".
The manager finds that in many cases it will be much more efficient to search for a particular record
by specifying a criterion instead of scrolling through the records. In order to implement this, the Find
methods of the Recordset object are used.
Steps
Place a command button namely cmdFindFirst to activate the Find method and to detect the first record
to match the given criteria. The following code is used to declare a database object mydb, a Recordset
object MySet and a Workspace object namely MyWs and a variable Total of long datatype in the General
declaration section of the form.
Dim mydb As Database, MySet As Recordset, MyWs As Workspace
Dim Total As Long
The following code in the Form load event procedure is included to open the emp_details database and the
emp table in it and assigning the records of empl table to the Recordset variable MySet.
Private Sub Form_Load)
Set mydb = OpenDatabase("XYZCompany”,False,False, _
"ODBC;UID=USERl;PWD=SSI”;DSN=XYZCompany)
Set MySet = [Link](“Emp",dbOpenDynaset)
End Sub

Dept. of Computer Science, HiSAC, Erode 70


Visual Basic – Unit III

In the click event of the cmdFindFirst command button the emp_no entered in the text1 textbox is searched
using the MySet recordset using the FindFirst function and if no match is found, then a message is displayed
saying "record not found". If a match is found, then other details of that employee identified by the particular
emp_no like emp_name, salary, designation and other related details are assigned and displayed in the
textboxes.
Private Sub CmdFindFirst_Click()
Dim a As String
a = [Link]
[Link] “[emp_no]=" & CInt([Link])
If [Link] Then
MsgBox "The Given Record is not found"
Else
[Link]
[Link] = MySet(0)
[Link] = MySet(1)
[Link] = MySet(2)
[Link] = MySet(3)
[Link] = MySet(4)
End If
End Sub

Add the following code in the Form load event procedure


Private Sub Form_Load()
Set mydb = OpenDatabase(“XYZCompany",False,False,_
"ODBC;UID=USERl;PWD=SSI”;DSN=XYZCompany)
Set MySet = [Link]("Emp",dbOpenDynaset)
End Sub

Adding a field to a Table


A field can be added to an existing table of a database at run time by appending a field to an existing
collection of fields. The following code example adds a new field called Address to the emp table of the
emp_details database. Once the field is added it displays a message box "Field Added".
Example A Standard EXE project is opened and the following code is entered in Form_Load event.
Dim newTd As TableDef
Dim newFld As Field
Set myDb = OpenDatabase(“XYZCompany",False,False,”ODBC;UID=sa;PWD=")
Set newTd = [Link]("emp”)
Set newFld = [Link](“Address",dbText,30)
[Link] newFld
MsgBox "Field Added”
[Link]
In the above coding, the emp_details database is opened using a database object mydb, a newTd tabledef
object is set to the emp table of emp_details database and newFld object is assigned to a new field namely
Address of string type and having a character limit of 30 characters. This Address Field is added to the Fields is
added to the field in the emp table using the Append method. In general, the Append method in association
with an object is used to add element a new element of that object to already existing ones.

Dept. of Computer Science, HiSAC, Erode 71


Visual Basic – Unit III

Adding an Index to a Table


The Append method can be used to add a new Index object. The following code adds index to the emp
table for the column emp_name of the emp_details database. After an index to the table a message box with a
message "Index Created" is displayed.
Example
A new Standard EXE project is opened and the following code is entered declarations section of the Form.
Dim db As Database
Dim td As TableDef
Dim ind As Index

Private Sub Form_Load()


Set db = OpenDatabase(“XYZCompany",False,False,_
“ODBC;UID=USERl;PWD=SSI”;DSN=XYZCompany)
Set td = [Link](“emp")
Set ind = [Link](“Namelndex")
[Link] [Link]("emp_name")
[Link] ind
MsgBox "Index created"
End Sub

Deleting Index from a Table


Deleting an Index is similar to the way a table is deleted. The following code deletes the index
NameIndex, which was created from the indexes collection of the Emp table.
Dim db As Database
Dim td As TableDef

Private Sub Form_Load()


Set db = OpenDatabase("XYZcompany”, False, False, _
“0DBC;UID=USERl;PWD=SSI”;DNS=XYZCompany)
Set td = [Link](“emp”)
[Link] "NameIndex”
MsgBox “Index deleted" n
End Sub

Using Transactions to Control Changes


To enforce data integrity, a set of operations must be considered as a single unit. Visual Basic supports three
transaction methods such as BeginTrans, CommitTrans and Rollback. These methods are associated with the
Workspace object.
• The BeginTrans method begins a new transaction.
• The CommitTrans method commits all changes made to the data subsequent to the most recent invoking of
the BeginTrans method.
• The Rollback method cancels all changes made to the data subsequent to the most recent BeginTrans
method used.

The following example changes the deptno field of the Emp table in the emp_details database from 9 to 10.
After the BeginTrans method starts a transaction that isolates all changes made to the Emp table, the
CommitTrans method, saves the changes. The Rollback method is used to undo the changes that are saved using
the Update method.

Dept. of Computer Science, HiSAC, Erode 72


Visual Basic – Unit III

Example
A new Standard EXE project is opened and saved. A function called changeDeptno is entered and is called in
the Form_Load( ) procedure.
Function changeDeptno ()
Dim db As Database, myWs As Workspace, rs As Recordset
Set myWs = [Link](O)
Set db = [Link](“XYZCompany", False, False, _
"ODBC;UID=USERl;PWD=SSI”;DSN=XYZCompany)
Set rs = [Link](“Emp",dbOpenDynaset)
[Link]
Do Unti1 [Link]
If rs("dept_no")=9 Then
[Link]
rs("dept_no") = 10
[Link]
End If
[Link]
Loop
If MsgBox("Save all chances?",vbQuestion+vbYesNo,"Save changes")=vbYes Then
[Link] Else [Link]
End If
[Link]
End Function

When the function changeDeptno is called at run time, it display a message box. By choosing Yes,
changes are made in the database and the transaction is committed, Otherwise, changes made to the database
table before the Commit'I'rans method are not saved.

Accessing ODBC database using Data Control


A Data control is used to create applications that display, edit, and update information from numerous
types of existing databases, including Microsoft Access, Btrievc, Dbase, Microsoft FoxPro and Paradox. It is
also used to access Microsoft Excel, Lotus 1-2-3, and standard ASCII text files as if they were true databases. In
addition, data control allows the user to access and manipulate external Open Database Connectivity (ODBC)
databases such as Microsoft SQL Server and Oracle. The Data control implements data access by using the
Microsoft Jet database engine. .
A data control is used to create simple and robust database applications. It can be added to a Form in the
same way as other controls are added in Visual Basic, Data control can perform the following tasks without
writing any code.
• Connect to a local or external database.
• Open a specified database.
• Attach data fields to bound controls, where values can be displayed and changed.
• Add new records or update a database with the data displayed on the bound controls.
• Close the database.
A Data control has many properties and methods that enable manipulation of the database.

Using DBGrid Control


The DBGrid control is a spreadsheet-like bound control that displays a series of rows and columns
representing rows and fields from a Recordset object. The DBGrid control's DataSource property can be set to

Dept. of Computer Science, HiSAC, Erode 73


Visual Basic – Unit III

a Data control so that the control is automatically filled and its column headers are set automatically from a
Data control's Recordset object.

Each cell of a DBGrid control can hold either text or picture values, but is not linked or embedded
objects. The user can specify the current cell in the code, or change it at run time using the mouse or the arrow
keys. Cells can be edited interactively, either by typing into the cell, by programming. If a cell's text is too long
to be displayed, the text wraps to the next line within the same cell. To display the wrapped text, the DBGrid
control's RowHelght property has to be increased.

A DBGrid control can have as many rows as the system resources can support and 1700 columns. When
a cell is selected, the ColIndex property is set, thus selecting one of the Column objects in the DBGrid object's
Columns collection. The Text and Value properties the Column object reference the contents of the current
cell. The data in the current row can be accessed using the Bookmark property, which provides access to the
underlying Recordset object's record. Each column of the DBGrid control has its own font border, word wrap,
colour and other attributes that can be set without regard to other columns.

Accessing Client-Server Data Source


ODBCDirect can be used to access client server data. ODBCDirect enables the DAO to access the
server directly through DAO without loading the Jet database engine. To set up a VB application that tests the
Oracle data source name, the following steps have to be followed.
• Create a Standard EXE project.
• From the Project Components menu, add a reference to the Microsoft Data Bound Grid Control.
• The DBGrid control in the project’s toolbox. Add an instance of the DBGrid control and a standard Data
Control to the Project’s Form.
• Change the data control’s DefaultType to 1-USE ODBC.
• In the Data control’s connect property, enter the following text
“ODBC;UID=USER1;PWD=SSI”;DSN=XYZCompany
• In the Data control’s RecordSource Property, the following SQL string
Select * from emp
• Select the DBGrid control’s DataSource property to Data1.
• Run the application, the gird will now display the entire data in the emp table as shown below

Dept. of Computer Science, HiSAC, Erode 74


Visual Basic – Unit III

Adding, Updating and Deleting Records


We can add new records to a table, modify an existing record and delete a particular record in the table.
Example An XYZ company has to maintain details about the new employees. On the other and the details of'
the employees on retirement or voluntary resignation from the company have to be deleted. All these operations
can be implemented using the Data control and ODBCDirect.
In order to add, delete and Update the records the following steps have to be followed
• Add a new form to the project and name it as emp_details.
• Add controls to the form as shown in below Figure.
There are new employees joining the company. To add the details of the new employees, attach the following
code in the click event of the Add command button.
Private Sub Add_Click()
[Link]
End Sub

The AddNew method clears the bound control and sets the EditMode property of the data control to
dbEditAdd. The record is only added when an UpdateRecord is executed. In order to delete the records of these
employees who are no longer employed with the company, the following coding has to be included
Private Sub Delete_Click()
[Link]
[Link]
If [Link] Then
[Link]
End If
End Sub
The Delete method deletes the current record from the database. The EOF property becomes True if the current
record position is after the last record. In order to save the new record added and the changes made to a record,
the Update method is used.
Private Sub Update_Click()
[Link]
End Sub
The manager while inserting a new record, finds that he had entered the department number as 3 instead of 1.
Hence he decides not to add the record into the table by cancelling the insertion To accomplish this, the
following code is added in the click event of the Cancel command.
Private Sub Cancel_Click()
[Link]
End Sub
The UpdateControls method cancels any changes made to the data and retains the original values. If the
user selects the Add button and then decides not to add the record, then the Updatecontrols method cancels
the Add.

Dept. of Computer Science, HiSAC, Erode 75


Visual Basic – Unit III

Remote Data Objects


Using Remote Data Objects (RDO) is an object-oriented way of accessing client server data
sources. The basic idea behind Remote Data Objects is to give the user an object-oriented, implementation
independent way of acquiring access to client server data. In order to get started with Remote data Objects,
a reference has to be made to them in a Visual Basic project. The steps to be followed are
• Select References from Visual Basic’s Project menu. The References dialog appears.
• Select Microsoft Remote Data Object 2.0 from the list.
• Click OK. Remote Data Objects will be available now in the application.
The RDO consists of objects and collections that form a framework for manipulating the components of a
remote ODBC database system. The relationships among objects and collections represent the logical
structure of the database system.

Remote Data Objects Hierarchy


The complete hierarchy of Remote Data Objects is shown in below Figure

The top level object is the rdoEngine object, which is used to access all remote data. All requests using RDO
objects are handled by the rdoEngine.

The rdoEngine creates one or more rdoEnvironment objects. This object contains information about
current environment for data connections. All rdoEnvironment objects are contained in the rdoEnvironments
collection object.

The rdoEnvironment objects can create rdoConnection objects. This object contains the details needed to
establish a connection between an application and the remote data source. All rdoConnection objects are
stored in the rdoConnections collection.

Each rdoConnection can create one or more rdoResultset objects. This object contains a direct reference to
all the rows and columns in the dataset. It can be used to create a collection of records after a connection is
made to the remote data source. All rdoResultset objects are stored in the Resultsets collection of the
rdoConnection object.

The rdoTable object contains information about each column in the base table that exists on the remote
data source. The rdoTable object can be opened from the rdoConnection object.

The rdo Column object contains detailed information about the contents and properties of each data column in
the rdoTable or rdoResultset object. All rdoColumn objects are stored in the rdoColumns collection.

Dept. of Computer Science, HiSAC, Erode 76


Visual Basic – Unit III

The rdoQuery object provides a method for creating and executing defined queries or views on the remote
data source. rdoQuery objects are accessed through the rdoQueries collection object.

The rdoParameter object manages the parameters that are passed during the processing of queries. More than
one rdoParameter object can be defined for each rdoQuery object. All the parameter objects are accessed via the
rdoParameter collection.

The following steps have to be followed for accessing a database through RDO
• First, the user must create an rdoConnection object to the database.
• After the connection is established and the database is opened, the user can execute SQL statements and
store procedures against the database.
• The results are returned in a rdoResultset object. With the rdoResultset object's methods and properties, the
user can access the records, edit them and save them.

Establishing a Connection
To establish a connection to a database in Oracle, the following syntax is used
Syntax
Set connection = [Link](dsName[,prompt[,readonly[,connect[,
options]]]])
In the above syntax, OpenConnection method opens a connection to an ODBC data source and returns a
reference to the rdoConnection object that represents a specific database. Only the first argument is mandatory.

The syntax in the Open Connection method has the following parts.
connection An object expression that evaluates to a rdoConnection object that the user is opening.
environment This is an object expression that evaluates to an existing rdoEnvironment object. The user provide
an rdoEnvironment object.
dsName This is string expression, which is the name of a registered ODBC data source or name.
prompt This is variant that determine the way in which the operation in carried out, as specified in the settings.
readonly This is a Boolean value. It is True if the connection is to be opened for read only access, and False if
the connection is to be opened for read/write access. If the user omits this argument, the connection is opened
for read/write access.
connect This is a string expression used to pass arguments to the ODBC driver manager for opening the
database.
Options This is a variant or constant that determines how the operation is carried out, as specified in Settings.

The connect arguments constitutes the ODBC connect arguments, and is dependent on the ODBC driver.
If the connect argument is an empty string(“”), the user name and password are procured from the
rdoEnvironment object’s UserName and Password properties and a dsName argument must be provided. If the
Data Source Name (DSN) parameter does not appear in the connect argument, the user has to select from a list
of registered data source names.

Executing SQL Statements


After a connection has been established, the user can execute queries on the database. The
OpenResultSet method of the Connection object is used to run queries against the database. The
OpenResultSet method creates a rdoresultset object which contains the results of the query.
Syntax
Set rs = [Link](name,type,locktype,option)

Dept. of Computer Science, HiSAC, Erode 77


Visual Basic – Unit III

The name argument is a string, which specifies the source for the new rdoResultSet [Link] argument
can specify the name of a rdoTable object the name of a rdoquery object, or an SQL statement that will
be executed on the server.

The Type argument is a constant that specifies the type of cursor that will be created by the data source to
manage the qualified records. This argument can have one of the following values.

rdOpenForwardOnly (default) opens a forward-only type resultset. Only the MoveNext method can be used to
scan the resultset forwaed but it cannot be updated.

rdoopenKeyset opens a static type resultset. It can be scanned forward and backward with the Move methods
and can be updated. But it does not reflect any changes made to the rcords by the other users.

rdoOpenDynamic opens a dynamic type resultset.

rdoOpenStatic opens a static type resultset. It can be scanned forward and backward but cannot be updated and
does not reflect any changes made by other users.

The locktype argument determines the way in which other users can access the data in the resultset. It can take
the following values.
• rdConncurReadOnly This is used when the user is opening the resultsets that will not be updated.
• rdConcurLock This locks the page that contains the current record and frees it only after the application
moves to a record in another page.
• rdConcurRowVer This locks the entire page containing the record being edited, but only while the record
is being updated.
• rdConcurValues Optimistic concurrency based on row values.
• rdConcurBatch Optimistic concurrency using batch mode updates.

Using ROO to Insert, Update and Delete Records


Records can be inserted, existing records can be modified and unwanted records can be deleted using
RDO objects.
Example Create a new project called employee details. Add the following controls - five labels, five textboxes
and nine command buttons to the Form as shown in below Figure.

Dept. of Computer Science, HiSAC, Erode 78


Visual Basic – Unit III

Add the following code in the declarations section of the form


Dim env As rdoEnvironment
Dim cn As rdoConnection
Dim rs As rdoResultset
The next step is to select the Data Source name. The OpcnConnection method is used in the Form_Load
event to prompt the user to select a DSN name
Set env = rdoEnvironments(O)
[Link] = rdUseOdbc
Set cn = [Link](dsname:=””, Prompt:=rdDriverPrompt,
ReadOnly:=Fa1se,Connect:="")
Call loademp
Observe that empty connection strings have been provided in the above coding. Hence, at runtime, the ODBC
Driver Selection Window will appear prompting the user to select the DSN. After the connection is complete,
the employee detail is retrieved by calling the sub- routineloademp().
Private Sub loademp()
Dim s As String
s = "select * from empl"
Set rs = [Link](Name:=s, Type:=rdOpenDynamic,_
LockType:=rdConcurRowVer)
If [Link] <> True Then
Call Displayrecord
Else
MsgBox “No records found"
End If
End Sub
Once the connection to a data source is established the OpenResultset method is used on the connection to
create a dynamic resultset. A cursor in a resultset marks the current record within a resultset. A dynamic cursor
refers to cursors where the values in the resultset can constantly change. Rows could be updated, deleted or
inserted and these changes are detected by the cursor when data is accessed. Now the user must be able to scroll
through the records. Add the following code in the click event of the cmdFirst, cmdNext, cmdLast and
cmdPrev command buttons.
Private Sub cmdFirst_Click()
[Link]
Call Displayrecord
End Sub

Private Sub cmdNext_Click()


If [Link] <> True Then
[Link]
If [Link] = True Then
[Link]
Else
Call Displayrecord
End If
End If
End Sub

Private Sub cmdPrev_Click()


If [Link] <> True Then
[Link]
If [Link] = True Then

Dept. of Computer Science, HiSAC, Erode 79


Visual Basic – Unit III

[Link]
Else
Call Displayrecord
End If
End If
End Sub

Private Sub cmdLast_Click()


[Link]
Ca11 Disp1ayreccrd
End Sub

When the user clicks the Add command button, it clears the Form and allows the entry of new information by
the user. Then on clicking the Save command button the new information is stored in the database.
Private Sub Add_Click()
Ca11 ClearRecord
[Link]
End Sub

Private Sub Save_Click()


rs(“emp_no") = [Link]
rs("emp_name") = [Link]
rs("sal") = [Link]
rs("Joindate") = [Link]
rs("dept_no") = [Link]
[Link]
End Sub

The Update routine is used to save the changes that are made to the current record.
Private Sub Update_Click()
[Link]
rs("emp_no") = [Link]
rs(“emp_name") = [Link]
rs(“sal") = [Link]
rs("Joindate") = [Link]
rs(“dept_no") = [Link]
[Link]
End Sub

When the user clicks the Delete command button, the current record must be deleted from the table. Add the
following code in the click event of the Delete command button.
Private Sub Del_Click()
[Link]
Ca11 Disp1ayrecord
End Sub

Add the following routines to the form. These routines methods for displaying and retrieving from the
textboxes on the form.
Private Sub Displayrecord()
[Link] = rs("emp_no")
[Link] = rs(“emp_name")

Dept. of Computer Science, HiSAC, Erode 80


Visual Basic – Unit III

[Link] = rs(“sal")
[Link] = rs("Joindate")
[Link] = rs(“dept_no")
End Sub
The above routine will display the current view row of the resultset on the form
Private Sub Clearrecord()
[Link] = “”
[Link] = “”
[Link] = “”
[Link] = “”
[Link] = “”
End Sub
The Clearrecord() clears the form and allows the user to enter the new values.

Creating Parameterized Queries Using rdoParameter Object


We can write parameterized queries using the rdoParameter object. Each rdoParameter object belongs
to an rdoParameters collection.

Accessing Tables with the rdoTable Object


The rdoTable object contains information about every column in the database table that exists in the
remote data can access tables and views in RDO using rdoTable object. The rdoTables collection can be used
to obtain the list of all tables available in particular database.

******

Dept. of Computer Science, HiSAC, Erode 81


Visual Basic – Unit III

ActiveX EXE and ActiveX DLL

Introduction to ActiveX EXE and ActiveX DLL


Visual Basic can be used to compile class-based projects such as ActiveX components. These
components can either take the form of DLLs or 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. This makes it
easier for the users to reuse the code across multiple projects as well as multiple developers. Creating ActiveX
components from the classes we build also allows us to take advantages of other technologies such as remote
distribution of objects.

A class module, which we have already studied, is a server that is an application that provides its
services to the client application. 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.

ActiveX EXE and ActiveX DLL


Servers can be implemented as ActiveX DLL or ActiveX EXE components. The difference lies in how
the server is executed. An ActiveX DLL is an in-process server. The DLL is loaded to the same address space
as the client executable that calls the server and it runs on the same thread as the client. At any given moment
however, the client applications or the DLL is running. The merits of DLL is the they are faster, as in effect,
they become part of the application that use them.

An ActiveX EXE otherwise called as an out-of-process server, as the name indicates runs as a separate
process. When a client application creates an object provided by an EXE server for the first time, the server
starts running as a separate process. If another client application creates the same object, the running EXE
server provides this object. In other words, a single EXE server can service multiple clients. Out-of-process
servers seem to be more efficient to terms of resource allocation, but exchanging information between servers is
a slow process.

We will be working with a client server model. Here the application is the client, which sends request
and the ActiveX Component is the server, which services the request. Though ActiveX DLLs run within the
same application as the client, they are considered as to be servers.

Differences between ActiveX EXE and ActiveX DLL


The distinction between server types results in differences in testing the components. An ActiveX DLL
can be tested by adding a test project to the ActiveX DLL project, Since both the server component and the test
application run in the same process, we don't need two different executables.

Creating and Compiling an ActiveX Component


ActiveX component can be created in Visual Basic by starting a new project. The ActiveX EXE or
ActiveX DLL is chosen depending on the type of project to be created. A new project is created with a single
class module. If needed, additional classes can be included to the project. Suitable coding is to be written for the
classes. The final step is to compile the project into an ActiveX DLL or EXE.

An ActiveX project is compiled in the same way as a Standard EXE project. But ActiveX EXEs and
DLLs are used differently. Thus ActiveX components are Object Servers that can be used with other
applications.

Dept. of Computer Science, HiSAC, Erode 82


Visual Basic – Unit III

While both ActiveX DLLs and EXEs can provide objects to other applications, ActiveX EXEs have the
capability to execute independently, which is not so in ActiveX DLLs. Compilation of an ActiveX component
can be done by selecting the File → Make menu command as with a Standard EXE project. The project is then
compiled into an ActiveX DLL or an ActiveX EXE, as appropriate. After it is compiled, the component is
registered on the computer, so that the user has the ability to use objects created from its classes in other
applications.

Creating an ActiveX EXE Component


An ActiveX EXE component is an out-of-process server which can be developed and run independently.
These can be included in the client application after they are compiled and registered. The procedure of creating
an ActiveX EXE application, compiling and registering the same and then testing it using a client application is
explains here. The entire process of creating an ActiveX EXE project is can be understood from the following
example.

Example Let us develop a Calculator to perform the simple arithmetic calculations such as to be used in any
suitable client applications where required. This component developed can be used in dealing with simple day
to day operations of the DBF Ltd Bank, which forms our client here.
• Addition
• Subtraction
• Multiplication
• Division
• Modulus
The following three steps are involved
• To create the Calculator which is the ActiveX EXE component
• To compile this component and register.
• To test the component with our client test application.

Step1
To Create the Calculator (ActiveX EXE Component)
• To start with, go to Program→Visual Basic 6.0 → and the New Project dialog box opens. Select ActiveX
EXE.
• This opens into a class module namely Class1 by default similar to a Form in a Standard EXE project.
• Press F4 to edit the properties and set the properties of the class module as given below.
Properties Settings
Name Calculator
Instancing 5-MultiUse
• The following set of coding is included in the general declaration section of the class module Calculator to
perform addition between any two digits of data type-Single. The function is named as Addn and two
parameters A and B are of data type Single to represent that operation is performed on only two input
variables and the return datatype is declared as double here. The resulting addition is stored in Addn
variable.
Public Function Addn(A As Single, B As Single) As Double
Addn = A + B
End sub

Dept. of Computer Science, HiSAC, Erode 83


Visual Basic – Unit III

• Similar to the addition operation, the difference between any two numbers is determined using the Diff
function defined below in the general declaration section. The resultant of the operation is obtained in the
Diff variable.
Public Function Diff (A As Single, B As Single) As Double
Diff = A - B
End Function
• The same logic holds good for the code given below to perform the multiplication process for any two
numbers passed as input. The product of two numbers A and B can be retrieved from the Prod variable of
the Prod function that is defined as follows. This coding sequence is also included in the general declaration
section of the class module Calculator.
Public Function Prod (A As Single, B As Single) As Double
Prod = A * B
End Function
• The division between two numbers is performed using the function Div as defined in the following code,
included in the general declaration section of the class module. The quotient obtained after performing the
division is retrieved in the Div variable.
Public Function Div (A As Single, B As Single) As Double
Div = A / B
End Function
• The modulus obtained by performing division on one number by the other can be determined using the Mod
operator in VB. When this basic knowledge, a function called modulus has been included in the general
declaration section to determine the modulus of a division operation.
Public Function Modulus (A As Single, B As Single) As Double
Modulus = A Mod B
End Function
• This completes the development of the ActiveX EXE component Calculator. This has to be run and
compiled.
• Before running select File→Save Project As and save it as [Link] and class module as
[Link].

Step 2
Compilation and Registering the Calculator Component
• The Calculator control can be run by pressing F5.
• Then select File→ Make EXE to make component an executable.
• The Make Project dialog appears as shown below. Choose a folder to save the EXE and click OK.
• The ActiveX EXE control namely ActiveX Calculator is now compiled and registered on our computer.
This server can be used from any of our projects.

Step 3
Testing the Calculator Project with a Standard EXE Application
• Goto VB and start another instance of Visual Basic and open a New standard EXE project and save it as
[Link].
• Place the following controls on the Calculator Form as given below
Object Properties Settings
Form Name CalculatorForm
Caption ActiveXCalculator

Dept. of Computer Science, HiSAC, Erode 84


Visual Basic – Unit III

Commandbutton1 Name Addition


Caption Add
Commandbutton2 Name Subtraction
Caption Subtract
Commandbutton3 Name Product
Caption Multiplication
Commandbutton4 Name Division
Caption Divide
Commandbutton5 Name Mod
Caption Modulus
TextBox Name DisplayText
Text “”
• Our next requirement is to invoke the arithmetic operations from the ActiveX EXE component
ActiveXCalculator. We therefore need to include the ActiveXCalculator project to this application.
• To include the ActiveXCalculator project to the client application, select References from the Project menu
and select Active X Calculator from the list. This will be included in the list of references as it has been run
and registered.
• Now we can create instances of the class Calculator in the client application and invoke the functions as
given in the coding below.
• In the general declaration section of the ActiveXCalculator form, instances of the Calculator class are
created to invoke different functions of the ActiveX EXE component ActiveXCalculator.
Dim CalcObj As New Calculator
• In the click event of the cmdAdd command button, the following lines of coding are included. Here two
variables are declared to get the two numbers as the input on which the addition operation is performed. On
clicking the cmdAdd button an inputbox appears asking for the first number. The user on providing the first
digit, another Inputbox appears asking for the second number. In the statement [Link] = "The
Sum.....” & [Link](I, V), the Addn function is called through the CalcObj instance of
the class Calculator. The resultant added value is displayed in the TextBox.

Private Sub cmdAdd_Click()


Dim I As Single, V as Single
I = InputBox(“Enter a Value:”, “Calculation with two numbers”)
V = InputBox(“Enter a Value:”, “Calculation with two numbers”)
[Link] = “The Sum of the given two numbers is “ & [Link](I,V)
End Sub
• The same procedure as described for addition is followed for subtraction, multiplication, division and
modulus process on clicking the respective command buttons and the result is displayed in the textbox
responding to the function invoked. The re1evant of coding is given here for the Click events of all
command buttons.
Private Sub cmdSubtract_Click()
Dim I As Single, V as Single
I = InputBox(“Enter a Value:”, “Calculation with two numbers”)
V = InputBox(“Enter a Value:”, “Calculation with two numbers”)
[Link] = “The difference of the given two numbers is “ & _
[Link](I,V)
End Sub

Dept. of Computer Science, HiSAC, Erode 85


Visual Basic – Unit III

Private Sub cmdMultiply_Click()


Dim I As Single, V as Single
I = InputBox(“Enter a Value:”, “Calculation with two numbers”)
V = InputBox(“Enter a Value:”, “Calculation with two numbers”)
[Link] = “The product of the given two numbers is “ & _
[Link](I,V)
End Sub

Private Sub cmdDivide_Click()


Dim I As Single, V as Single
I = InputBox(“Enter a Value:”, “Calculation with two numbers”)
V = InputBox(“Enter a Value:”, “Calculation with two numbers”)
[Link] = “The Divided value of the given two numbers is “ & _
[Link](I,V)
End Sub

Private Sub cmdModulus_Click()


Dim I As Single, V as Single
I = InputBox(“Enter a Value:”, “Calculation with two numbers”)
V = InputBox(“Enter a Value:”, “Calculation with two numbers”)
[Link] = “The MOdulus value of the given two numbers is “ & _
[Link](I,V)
End Sub
• Now the test application can be run.
• If we need to perform addition of any two numbers, click the Add button. An input box appears. On entering
a number, another input box appears asking for the second number. Then the addition operation is perfumed
and the result is displayed on the text box.

Creating ActiveX DLL Component


ActiveX DLL, as mentioned earlier is an in-process server, which runs as a part of the client application.
When a new ActiveX DLL component is created, the steps we will generally follow are
• Determine the features the component will provide
• Determine what objects are required to divide the functionality of the component m a logical fashion
• Design any Forms the component will display
• Design the interface that is, the properties, methods and events for each class provided by the component.
• Create a project group consisting of the user’s component project and a test project
• Implement the Forms required by the component
• Implement the interface of each class
• As each interface element or feature is added, features are added to the test project to exercise the new
functionality.
• Compile the DLL and test it with all potential target applications.

Components provide reusable code in the form of objects. An application that uses a component's code, by
creating objects and calling their properties and methods, is referred to as a client. Components can run either
in-process or out-of-process with respect to the clients who use their object. An in-process component, or
ActiveX DLL, runs in another application’s process. The client may be the application itself, or another in-
process component that the application is using.

Dept. of Computer Science, HiSAC, Erode 86


Visual Basic – Unit III

The series of step by step procedures in this chapter build an in-process component called Interest
Calculator with class modules that demonstrate object lifetime. We will also see how to debug an ActiveX
DLL in process, by running the DLL and a test project together in the Visual Basic development environment.

Example DBF Limited finance company is in need of finding out the interest of the depositors for the time
period of investment and the type of deposit scheme chosen. This is generally done by writing a simple function
in the client's program. But the rate of interest offered may change from time to time during which time the
changes reflecting this can be done in the server program alone thereby making the work simpler and easier.
Keeping this in mind, let us more on to developing an ActiveX DLL component namely Interest Calculator as
elucidated below.
• Start an instance of Visual Basic and select an ActiveX DLL project and it opens into a class module by
default as in an ActiveX EXE.
• The properties of the class module can be set as given in below
Properties Setting
Name Interest Calculator
Instancing 5-MultiUse
• In the project menu, click Add Module and double click the module icon and name it as [Link].
• The following code is to be executed when the component starts, in response to the first object request.
Option Explicit
Public gdatServerStarted As Date

Sub Main()
gdatServerStarted = Now
[Link] “Executing Sub Main”
End sub
• Properties for a class can be created by adding public variables and property procedures to the class module.
We can also create methods for a class by adding Public Sub and Public Function procedures to the class
module. The following step by step procedure creates two properties and one method for the Interest class.
• The Name property is a string that can be retrieved and set by client applications. The methods included are
RecInterest, CumInterest and FixInterest to evaluate the interests based on the type of recurring,
cumulative and fixed deposit scheme chosen.
• Add the following code the declaration section of the Interest class module.
Option Explicit
Public Name As String
• The variable name becomes a property of the Interest class between it is declared Public.
• In the general declaration section of the class module, the function FixInterest is declared and defined which
will evaluate the interest for a fixed deposit scheme, with the rate of interest predefined to be 10 per cent
and time and principal amount as the two input parameters.
Option Explicit
Public Function FixInterest(P As Single, T As Single) As Single
Dim R As Integer
R = 10
FixInterest = (P * R * T) / 100
End Function
• If the type of deposit scheme is Recurring Deposit Scheme, then the function RecInterest is declared as
given in the following code in the general declaration section. The rate of interest is defined to be 8 percent.
Public Function RecInterest(P As Single, T As Single) As Single
Dim R As Single

Dept. of Computer Science, HiSAC, Erode 87


Visual Basic – Unit III

R = 8.0
RecInterest = (P * R * T) / 100
End Function
• If the type of deposit scheme is Cumulative Deposit Scheme, then the function CumInterest is declared as
given in the following code in the general declaration section. The rate of interest is defined to be 7.5
percent.
Public Function CumInterest(P As Single, T As Single) As Single
Dim R As Single
R = 7.5
CumInterest = (P * R * T) / 100
End Function
• Select File→Save As and save the files.
• In order to test InterestCalculator component, a test project is required. The test project creates instances of
the classes a component provides, and exercises their properties, methods, and events. To enable debugging
of in-process components, Visual Basic allows us to load two or more projects into a project group. In
addition to enabling in-process debugging, the project group makes it easier to load our component project
and test project.
• In order to test the ActiveX DLL project, select Add Project from File menu and select a Standard EXE
project, which by default opens into a Form. The controls are placed on the form with properties set as given
below
Object Properties Settings
Label1 Caption Principal Amount
Label2 Caption Time Period
Label3 Caption Choice of Deposit
Label4 Caption Interest Amount
Label5 Caption Total Amount
TextBox1 Name txtPamt
TextBox2 Name txttime
TextBox3 Name txtIamt
TextBox4 Name txtTamt
ComboBox1 Name Combochoice
CommandButton1 Name cmdResult
Caption Caption
• Goto References from the project menu and then select the InterestCalculator component and click OK.
• Next we have to declare instances of the class Interest Calculator that is to be accessed. In the general
declaration section, the following code is included thereby declaring Intobject as object of class Interest.
Dim Intobject As New Interest
• The tab properties are to be set in the desired level in the design mode itself. On running the Form, the tab
control should be positioned first to the txtPamt field to get the principal amount. Then the time period is
given as the input, the user then makes a choice of deposit scheme from the combo box and the result
command button is clicked.
• The Click event of the cmdResult button is handled as given by the code below. On clicking the result
button, it accepts the principal amount and time period and checks for the deposit scheme that is selected.
Private Sub emdResult_Cliek()
Dim I As Single, v As Single, b As Single
Dim a As String
I = [Link]
v = txtTime. Text

Dept. of Computer Science, HiSAC, Erode 88


Visual Basic – Unit III

a = Comboehoiee(l).Text
• Based on the deposit scheme selected, the functions are called. If the Combo box text field is selected to be
'Fixed Deposit', then the Interest is calculated by calling the FixInterest function referenced by the instance
of the class Intobject,
If Combochoice(l).Text = "Fixed deposit" Then
[Link] = "The Simple Interest amount for the given princip1e is ” &
[Link](I,V)
c = Intobjeet. FixInterest (I,V) + I
• If the Combo box text field is selected to be 'Recurring Deposit’, then the interest is calculated by calling the
RecInterest function referenced by the instance of the class Intobject.
Elself Combochoice(l).Text = "Recurring Deposit" Then
[Link] = "The Recurring Interest amount for the given princip1e is“&
[Link](I,V)
c = [Link](I,V) + I
• If the Combo box text field is selected to be 'Cumulative Deposit', then the interest is calculated by calling
the CumInterest function referenced by the instance of the class Intobject.
ElseIf Combochoice(1).Text = "Cumulative Deposit" Then
[Link] = “The Cumulative Interest amount for the given principle is” &
[Link](I,V)
c = [Link](I,V) + I
End If -
• Lastly the total amount, ie., the sum of the principal amount and the interest is calculated and obtained in the
variable c, which is displayed in the textbox.
[Link] = “The total Amount is” & C
End Sub
• All the coding functionality is complete. Press F5 to run the Form. The Interest Calculator Form appears
as shown below
• Say if we enter the principal amount to be Rs.5500 for a time period of 2½ years and the deposit scheme
chosen to be Commutative deposit, then on clicking the result button, the Interest amount and total amount
is displayed.

*******

Dept. of Computer Science, HiSAC, Erode 89


Visual Basic – Unit IV

Object Linking and Embedding


An important feature of the Microsoft Windows Operating system is its ability for sharing
information among applications. OLE is a means of communication, which gives any application the
power to directly use and manipulate other Windowsapplications. Any object that supports OLE can be
linked. OLE specification permits the user to link and embed objects and also edit the object within the
container application.

OLE Fundamentals
DDE is an acronym for Dynamic Data Exchange. It is the basic foundation for inter process
communication between applications. In DDE, the application creating a link is known as the destination
application, and the application that responds is the source application. Although there are functional
similarities between OLE and DDE, there are a few differences. While using DDE unformatted data is
exchanged. The Visual Basic application has to format it appropriately. For e.g., in case of an Excel
Spreadsheet, the formula used for calculating the result is not fetched, only the resultant number is fetched.

OLE actually transfers control to the original application. OLE is a technology that enables the
programmer of a Windows-based application to create an application that can display data from many different
applications. This enables the user to edit that data from within the application in which it was created. When a
spreadsheet is edited in a Visual Basic program, the original application is called OLE contains the correct
underlying objects so the information is fully editable. The following terms and concepts are the fundamentals
for understanding the methodology to use OLE in Visual Basic.

Objects and Classes


An object is a combination of code and data that can be created as a unit. It can be a piece of application
like a control or Form. An application can also be an object. A class defines each object in Visual Basic. An
object refers to a discrete unit of data supplied by an application. An application can expose several types of
objects. For example, a spreadsheet application can expose a worksheet, macro sheet, chart, cell, or range of
cells, all as different types of objects. There are three ways of creating an object in Visual Basic.
• The object is added to the Toolbox using the Custom Controls command on the Tools menu and it is drawn
directly on a Form. This technique embeds the object within the interface of a Form in our application.
• The CreateObject or GetObject functions can be used for creating the object in code. This technique
creates the object in a running instance of the application that provides the object.
• The object can be embedded or linked within an OLE container control. This technique permits the change
of objects on the Form. At runtime, linked objects have to be created, and the OLE container control
has to be bound to a Data control.

The application that provides the object's data and the type of data the object contains determines the object's
class. A class defines each object in Visual Basic. The following statements differentiate between an object and
its class.
• The controls in the toolbox in Visual Basic represent a class. This object known as a control does not exist
until it is placed on a Form. When a control is created a copy or Instance of the control class is created. This
instance of the class is the object that is referenced to an application.
• The Form we work with during design time is a class. During run time Visual Basic creates an Instance of a
class.

Dept. of Computer Science, HiSAC, Erode 92


Visual Basic – Unit IV

OLE Automation
Some applications provide objects that support OLE automation. User can use Visual Basic to
manipulate the data in these objects by programming. Some of that support OLE automation also support
linking and embedding. If an object in an OLE container control supports OLE automation, we can access its
properties and methods using the Object property.

Container Application
An application that receives and displays an object’s data is a container application. For example, a
Visual Basic application that uses an OLE container control to embed or link data from another application is a
container application.

Linked Objects
Data associated with a linked object is stored by the application that supplied the object. This
application stores only link reference that displays a snapshot of the source data. When we link an object an
application containing a link to that object can access the object's data and change it. For example, if we
link a text file to a Visual Basic application the text file can be modified by any application linked to it.
The modified version appears in all documents linked to this text file. We can use the OLE container
control to create a linked object in our Visual Basic application.

Embedded Objects
When an embedded object is created, all the data associated with that object is contained in the
object, For example, if a spreadsheet is an embedded object, all the data associated with the cells would be
contained in the OLE container control or insertable object, including any necessary formulae. The name of
the application that created the object is saved along with the data. If we select an embedded object while
working with the Visual Basic application, the spreadsheet application can be started automatically so that
we can edit those cells. When an object is embedded in an application, no other application has access to
the data in the embedded object. We can use embedded objects when we want the application to only
maintain data that is produced and edited in another application.

Using OLE container Control


The OLE container control allows adding objects from other applications. An OLE control can have
only one object at a time. Using OLE control we can do the following
• Create a placeholder in our application for an object.
• Create a linked object in our application.
• Bind the OLE container control to a database.
• Create objects from the data that was copied onto the c1ipboard.
• Display object as icons.
• Perform an action if user moves, sizes or updates the objects in the OLE control.
• Provide backward compatibility with an application that includes many OLE container controls

Creating Objects at Design Time


Each time an OLE control is drawn on a Form, an Insert Object dialog box appears as shown in the
below Figure which presents a list of the available objects that can be linked to or embedded in the application.
When an object is inserted into the OLE control at design time, the Class, SourceDoc and SourceItem properties
that identify the application that supplies the object, the source filename and any specific file that is linked from
within that file are automatically set. The following example creates a linked object using Insert Object dialog
box.

Dept. of Computer Science, HiSAC, Erode 93


Visual Basic – Unit IV

Example
This example creates a link from an existing application.
• An OLE control is drawn on the Form. This displays an Insert Object dialog box.
• The Create from File option is clicked and the Browse button is chosen. A Browse dialog box appears.
• The desired file is selected from the directory and the OK button is clicked. The Insert Object dialog box is
displayed again. The Link CheckBox is selected and the OK button is clicked.

When a linked object is created, the data displayed in the OLE control exists in one place which is the
source file. The file can be edited in its original application and saved. The object's data can be accessed from
any of the other applications that contain links to that data and the data in the source file can be changed from
within any application.

To Create an Embedded Object at Design Time


Example
• This example creates a new file using OLE container.
• OLE control is drawn on the Form. Insert dialog box is displayed at this point of time.
• Create New option is chosen and Microsoft Excel Worksheet is selected from the list of options displayed as
shown in below Figure.

• Now right-click on the OLE container and choose open.


• This takes us to the Excel application.
• The details required are entered in the excel worksheet and the file is saved as "[Link]”

Creating Objects using Paste Dialog Box


Paste special Dialog box can be used to create an object during design time. This dialog box is useful if
only a portion of a file is to be used. For example, a paragraph from a word document, or a range of cells from
an Excel Spreadsheet.

Dept. of Computer Science, HiSAC, Erode 94


Visual Basic – Unit IV

Example
• An Excel worksheet containing data that is to be linked or embedded is opened. The desired data is selected
from the sheet.
• From the Edit menu, the Copy command is chosen.
• An OLE control is drawn in a VB Form is clicked with right mouse button and the Paste Special command
is chosen from the pop-up menu. It displays a Paste Special dialog box.
• The Paste option is chosen for creating an embedded object and Paste Link option for creating a linked
object.
The above example creates an object from an Excel Worksheet and pastes data from row 45 and row 54 and
from column 1 to 7

Creating Objects at Run Time


To create a linked or embedded object at run time, various methods and properties are used in the code.
We can create a linked object at run time using the SourceDoc property and CreateLink method. The following
code fragment creates a linked object at run time.
[Link] "C:\[Link]"

Creating an Empty Embedded Object at Run Time


The CreateEmbed method can be used to specify an empty embedded object at run time. The following
code fragment inserts a file template for a Microsoft Excel Worksheet in the OLE container control.
[Link] “ ”,"[Link]"
The following code creates an empty embedded object and the application is created using the DoVerb action.
[Link] “ ”, "[Link]"
[Link] -5
The Insert Object dialog box can be displayed at run time, with which we can create a variety of objects. This
can be used in document-centered application, where the user combines data from different applications to
create a single document. The InsertObjDlg method is used to display the Insert Object dialog box.

Consider an OLE control and a CommandButton are added to the Form. The following code is entered
in the Command1_Click() procedure
Private Sub Commandl_Click()
[Link]
If [Link] = vbOLENoneThen
MsgBox "Object not created”
End If
End Sub
Once the dialog box is displayed, the user can make a choice from the options that are displayed. If the user
cancels the dialog, an object is not created. If the user selects a choice, the selected object is displayed. Any
changes made to the object can be updated in the OLE control by choosing Update from the File menu in that
object. Once the application is chosen to be linked, it is necessary to check if the application is running, To
check if the application is running, the following code ([Link]) is used.

Moving or Sizing the OLE Container


The OLE container control has an ObjectMove event, which is triggered when the object associated with
the control is moved or resized. An ObjectMove event occurs when the user moves or resizes the object
contained in the OLE container control. The arguments of the ObjectMove represent the coordinates of the
object within the object's container. The following example illustrates this.

Dept. of Computer Science, HiSAC, Erode 95


Visual Basic – Unit IV

Example
All OLE control is added to a Form. The following code is entered in the OLE1_ObjectMove() procedure.
Private Sub OLEl_ObjectMove(Left As Single, Top As Single, Width As Single,
Height As Single)
[Link] [Link], [Link], Width, Height
[Link] Top,Left, [Link], [Link]
End Sub

Using OLE Automation Objects


OLE Automation is an industry standard technology that applications use to expose their OLE objects to
development tools, macro languages, and other applications that support OLE Automation. For example, a
spreadsheet application may expose a worksheet, chart, cell, or range of cells all as different types of objects. A
word processor might expose objects such as application, document, paragraph, sentence, bookmark or
selection.

When an application supports OLE Automation, the objects it exposes can be accessed by Visual Basic.
Visual Basic could be used to manipulate these objects by invoking methods on the object or by getting and
setting the object's properties. For example, if we create an OLE Automation object named MyObj, the
following code could be written for manipulating the object
[Link] “Hello World”
[Link] = True
[Link] “C:\WORDPROC\[Link]”
The following functions are used to access an OLE Automation object.
• CreateObject creates a new object of a specified type.
• GetObject retrieves an object from a file.

Referencing an Object using an Object Library


The objects, functions, properties and methods supported by an application are usually defined in the
application’s object library. Every application that supports OLE automation provides at least one type of
object. For example, a word processing application may provide an application object, a document object, and a
toolbar object. To create an OLE Automation object, assign the object returned by CreateObject to an object
variable which is shown a follows
Dim WordBasicObject As Object
Set WordBasicObject = CreateObject(“[Link]")
When this code is executed, the application creating the object is started. If it is already running, a new instance
of the application is started, and an object of the specified type is created. Once an object is created, we
reference it in code using the object variable we have defined. In the above example, we access properties and
methods of the new object using the object variable, WordBasicObject. For Example
[Link]
[Link] “Hello World”
[Link]
[Link] “C:\DOCS\[Link]”
Filenew in the above code opens a new file in the word object. Similarly, we can pass the object returned by the
CreateObjoct function to a function expecting an object as an argument. For example
Call MySub(CreateObject(“[Link]"))
The CreateObject method is used when there is no current instance of the object. The following example uses
the CreateObject function to set a reference (myApp) to Microsoft Excel. It uses the reference to access the
visible property of Microsoft Excel.

Dept. of Computer Science, HiSAC, Erode 96


Visual Basic – Unit IV

Example
A new project is opened and the following code is entered in the Form_Load() procedure.
Dim myApp As Object
Set myApp = CreateObject(“[Link]")
[Link]
[Link] = True
The following example uses the GetObject function to get a reference to a specific Microsoft Excel Worksheet.
The file, [Link] in the example, must exist in the specified location; otherwise a Visual Basic error known as
the OLE Automation error is generated.

Example
The following code is entered in the Form_Load() procedure of a new Standard EXE project.
Dim MyApp As Object
Dim ExcelNotRunning As Boolean
On Error Resume Next
Set MyXL = GetObject(,"[Link]")
If [Link] <> 0 Then ExcelNotRunning = True
[Link]
Set MyXL = GetObject("I:\[Link]")
[Link] = True
[Link](1).Visible = True
If ExcelNotRunning = True Then [Link]
Set MyXL = Nothing
The above example uses the worksheet's Application property to make Microsoft Excel visible, to close it and
so on. The first call to GetObject causes an error if Microsoft Excel is not already running. In this example, the
error causes the ExcelWasNotRunning flag to be set to True. The second call to GetObject specifies the file to
be opened. If Microsoft Excel is not already running, this second call starts it and returns a reference to the
worksheet represented by the specified file. Next, the code in the example makes both Microsoft Excel and the
window containing the specified worksheet visible. Finally, if there was no previous version of Microsoft Excel
running, the code uses the Application object's Quit method to close Microsoft Excel If the application was
already running, no attempt is made to close it. The reference itself is released by setting it to Nothing.

Using an Object's Methods and Properties


After declaring a variable that refers to the OLE Automation object, the object can be manipulated in
Visual Basic using the object property syntax. The following example sets the Name property of the application
object.
Dim myAppAs Object
Set myApp = CreateObject(“[Link]”)
[Link] = "MyObject”
Some applications might name objects, properties or methods using characters that have special meaning in
Visual Basic. These are called nonstandard names. For example, a Microsoft Word provides methods that
return strings. The name of each of these methods ends in a dollar sign($) which has a special meaning in
Visual Basic. To use one of the Microsoft Word string functions in Visual Basic, the name is enclosed in
square brackets.
NameofStyle = MyWord.[StyleName]()

Dept. of Computer Science, HiSAC, Erode 97


Visual Basic – Unit IV

OLE Drag and Drop


OLE drag and drop is a more versatile kind of drag and drop. OLE drag and drop method is only used
when we move a file in explorer from one directory (or drive) to another. OLE Drag and drop involves several
methods and events.

OLEDrag Method
This method is used to initiate an OLE drag operation. The OLEDrag Method is called when data is
copied between two OLE containers. The following syntax is used [Link] where object is the OLE
container object that acts as the source for the drag operation.

OLEDragMode Property
This property is used to determine if the object can act as an OLE drag source, and if the OLEDrag
operation is done manually or automatically. The allowable property values are
• vbOLEDragManual-0 This is the default value. It is used when the user's own OLE drag handlers are used
in the application.
• vbOLEDragAutomatic-1 This is used when the application has to handle the drag and drop operations.

OLEDropMode Property
This property determines the methodology of processing OLE drop events in the application. It can take
any one of the following values
vbOLEDropNone-0 This is the default value. It prevents the OLE container from allowing OLE drop events.
vbOLEDropAutomatic-1 This is set when the user entrusts Visual Basic with handling of the OLE drag routines.

OLEDropAllowed Property
This property determines whether the OLE drop operations are allowed or not. If this is True it allows
OLE drop operations on the container, otherwise drop operations are prohibited.

OLEDragDrop( ) event
This event is fired whenever an OLE drop operation is performed on an OLE container which allows
OLE drop operations. The syntax of this event is as follows
Private Sub object_OLEDragDrop(data as DataObject, effect As Long, button a
Integer, shift as Integer, x As Single, y As Single)
OLE DataObject can be referenced using the GetData method to retrieve the data be dropped in this event.
Effect parameter is used to communicate to the target component the action that is to be performed on the data.
The effect parameter can be anyone of the following as shown in below Table.

Description
Parameter
vbDropEffeetNone - 0 Target cannot accept OLE data
vbDropEffectCopy - 1 Specifies that data should be copied from source to destination
vbDropEffectMove -2 Specifies that data must be moved from source to destination
vbDropEfIectScroll Indicates if the target has scrolled, or would scroll if the data were
- 2147483648 dropped onto it. Used rarely

Dept. of Computer Science, HiSAC, Erode 98


Visual Basic – Unit IV

The button parameter is used to identify the button on the mouse that was clicked during OLE drag operations.
Value Description
1 Left Button
2 Right Button
3 Middle Button
The x and y parameter indicates the current position of the mouse pointer. These values are used if
dropping is required within the target control.

Events Related to OLE Drag and Drop


OLECompleteDrag() event is fired when data has been dropped from the source control and it has either
successfully performed a Move or Copy operation or the operation was cance1led . This is the final event to be
called in an OLE Drag Drop operation.
OLEStartDrag() Event is fired when the source control's OLEDragMode property is set manual. It is also fired
when the source component initiates an OLE drag operation and the OLEDragMode property is set to
automatic.
OLEDragOver() event is fired when the mouse is moved over an OLE container during an OLE drag
operation.
OLESetData() event is fired when the target component issues a GetData method on the source’s DataObject.
The syntax for this event is as follows
Private Sub Object_OLESetData(data As DataObject, dataformat As Integer)
This event has two parameters. The data parameter contains a DataObject, which will store the requested data.
The dataformat parameter describes the format of the data stored in the data parameter.
Example The following example creates an OLE Drag and Drop Application.
• Start a new project by selecting Standard EXE from the New Project dialog box.
• Save the form as [Link] and set the Name property to olefrm and caption property to OLE Drag and
Drop Demonstration Project.
• Add two text boxes of equal size as shown in below Figure by dragging them from the toolbox. Name the
text boxes as OLEtextl, and OLEtext2. Clear their text property and set their Multiline property to true.
• Set the OLEDragMode to 1-Automatic for OLEtext1 and OLEtext2 and Set the OLEDropMode to 2-
Automatic for OLEtext1 and OLEtext2.

The following code is added in the OLEDragDrop() event of OLEtext1


Private Sub OLETextl_OLEDragDrop(Data As DataObject, Effect As Long, Button
As Integer, Shift As Integer, X As Single, Y As Single)
[Link] = [Link](vbCFText)
End Sub

Dept. of Computer Science, HiSAC, Erode 99


Visual Basic – Unit IV

The following code is added in the OLEStartDrag() event of OLEtext1


Private Sub OLETextl OLEStartDrag(Data As DataObject, AllowedEffects As Long)
Effect = vbDropEffectCopy
[Link] [Link], vbCFText
End Sub
Add the code in the OLEDragDrop() event of OLEtext2
Private Sub OLEText2_OLEDragDrop(Data As DataObject, Effect As Long,
Button As Integer, Shift As Integer, X As Single, Y As Single)
Effect = vbDropEffectCopy
[Link] = [Link](vbCFText)
End Sub
Add the code in the OLEStartDrag() event of OLEtext2
Private Sub OLEText2_OLEStartDrag(Data As DataObject, AllowedEffects As Long)
Effect = vbDropEffectCopy
[Link] [Link], vbCFText
End Sub
• Now press F5 to the run the project. Let us type in any text of our choice in the OLEtextl and drag and drop
it Into OLEText2 and also vice versa.
• Save the project as OLEDrag Drop.

We can also drag and drop between applications, which support OLE drag and drop operations.

********

Dept. of Computer Science, HiSAC, Erode 100


Visual Basic – Unit IV

Files and File System Controls


File System Controls
There are three file system controls in Visual Basic. They are DriveListBox, DirectoryList Box and
FileListBox. In an application that allows to selecting files from drives, these controls are used in combinations.
When we need to select a file, a dialog box including all these three controls is displayed on the screen. We can
select the desired file by selecting a drive from the DriveListBox, a directory from the DirectoryListBox and a
file from the FileListBox. The following program illustrates the selection of a file from the FileListBox. After
selecting the desired file, a message box is displayed which displays the name of the selected file.
Example
• A new standard EXE project is opened and Form of the object is saved as [Link] and project is saved
as [Link].
• The application is designed as per the fol1owing specification and design Form as appears in the below
Figure.
Object Properties Settings
Form Caption Select Program
Label Caption &File Name
Name Label1
TextBox Text (empty)
FileListBox Name File1
Label Caption File &Type
Name Label2
ComboBox Name Combo1
Style 2-Dropdown List
Label Caption Directories
Name (empty)
Label Caption Drive
Name (empty)
DirListBox Name Dir1
Label Caption D&rive
Name (empty)
DriveListBox Name Drive1
CommandButton Caption &OK
Name cmdOK
CommandButton Caption &Cancel
Name cmdCancel

Dept. of Computer Science, HiSAC, Erode 101


Visual Basic – Unit IV

The following code is entered in the general declaration section of the Form.
Option Explicit
The following code is entered in the Form_Load( ) procedure.
Private Sub Form_Load()
[Link] “All files(*.*)”
[Link] “Doc fi1es(*.DOC)”
[Link] "text files(*.TXT)”
[Link] = 0
[Link] = [Link]
End Sub

The above procedure initializes the ComboBox and the AddItem method fills it with three items which
includes All files (*.*), Doc files(*.DOC) and Text files(*.TXT). Then the Listlndex property of the ComboBox
is set to 0. This sets the currently selected item of the ComboBox to item 0, or All files (*.*). Finally, the
Caption of Label4 is set to the Path property of the DirListBox. The initial value of the Path property is the
current directory, and hence when we start the program, Label4 displays the name of the current directory. The
following code entered in the Drivel_Change() procedure is executed whenever the DriveListBox is changed.
Private Sub Drivel_Change0
On Error GoTo ErrorTrap
[Link] = [Link]
Exit Sub
ErrorTrap:
MsgBox "Drive Error!",vbExclamation,”Error"
[Link] = [Link]
Exit Sub
End Sub
An error trap is set before the procedure. This executes the command that changes the Path property of
the DirListBox. This error trap is required, because changing the path of the DirListBox may cause an error at
run time. For example, if the DriveListBox is to drive B, and the drive B is not ready, changing the path of the
DriveListBox may cause an error. Visual Basic gives control to the code below the ErrorTrap label. This code
displays an error message and restores the original value of the drive.

The following code is entered in the Dirl_Change() procedure and is executed whenever the DirListBox is
changed.
Private Sub Dirl_Change()
[Link] = [Link]
[Link] = [Link]
End Sub
The code in the above procedure updates the Path property of the FileListBox and the Caption property
of Labe14 with a new directory. As a result of updating the FileListBox with the selected directory, it displays
the files of that directory.

The following code is entered in the Combol_Click( ) procedure which updates the Pattern property of
the FileListBox according to the selected file type. The Pattern property returns or sets a value indicating the
filenames displayed in a FileListBox control at run time. A Select Case is used to determine which item in the
ComboBox is selected. Depending on which item is selected from the ComboBox, a different Case statement is
executed.
Private Sub Combol C1ick()
Select Case [Link]

Dept. of Computer Science, HiSAC, Erode 102


Visual Basic – Unit IV
Case 0
[Link] = .
"* *"
Case 1
[Link] = "*.DOC"
Case 2
[Link] = "*.TXT"
End Select
End Sub
The following code entered in the File1_Click( ) procedure. The event updates the Text1 with the name of the
selected file.
Private Sub Filel_Click()
[Link] = [Link]
End Sub
The following code is entered in the cmdOK_Click() procedure. The If statement checks for the selected file
and displays a message box. .
Private Sub cmdOK_Click()
If [Link] = "” Then
MsgBox “No file was selected"
Else
MsgBox “Selected File is “ + [Link]
End If
End Sub
The following code entered in the cmdCancel_Click( ) procedure terminates the application.
Private Sub cmdCancel_Click()
End
End Sub

Accessing Files
A file consists of a series of related bytes located on a disk. When an application accesses a file, it must
assume what the bytes are supposed to represent. Depending on the kind the data the file contains, we can use
the appropriate file access type. There are three ways of accessing files in VB. They are
• Random Access
• Sequential Access
• Binary

Random Access Files


A random access file is like a database. It is made up of records of identical size. Each record is made up
of data of identical size. Below Figure shows a random access file with two fields per record. The first field is a
5-byte string that corresponds to a person's name and the second field is a 2-byte string that corresponds to the
person’s age. Each record in this file is 7-bytes. Each record stores data about a specific person.
D E E P A 2 2 V I D Y A 2 3 …….

Let us design and develop an application that illustrates the creation and manipulation of a random
access file. The program allows us to maintain a database file called [Link] that holds the record of
product information. The program opens the file in a random access mode with the following fields:
Product_Name, Product_Code, Price, Date_Of_Manufacture. If the file does not exist it creates one.
Example
• A new Standard EXE project is opened and the Form and the project are saved as [Link] and
[Link]. The Form is designed as per the following specification table.

Dept. of Computer Science, HiSAC, Erode 103


Visual Basic – Unit IV

Object Properties Settings


Form Caption Select Program
TextBox Text (empty)
TextBox Text (empty)
TextBox Text (empty)
TextBox Text (empty)
CommandButton Caption &New
Name cmdNew
CommandButton Caption &Previous
Name cmdPrevious
CommandButton Caption E&xit
Name cmdExit
Label Caption Name of the Product
Label Caption Product Code
Label Caption Price
Label Caption Date of manufacture
• The designed Form appears as shown in below Figure.

• Besides the Form file the application also requires a program module. Hence, a module is added to the
project, by selecting Add module from the Project menu.

The following code is entered in the general declaration section of Modulel. This declares a user-defined type
that corresponds to the fields of a record in the Product Dat file. The declared type is a ProductInfo, and is made
up of variables that include Name of the product, product code, price, date of manufacture. Each of these strings
corresponds to a field in the [Link] file. Later, the program uses a variable of the type ProductInfo to read
and write data into the [Link] file.
Option Exp1icit

Type Productlnfo
Name of the product As String * 20
Product code as string* 5
Price as string* 8
date of manufacture As String * 20
End Type

The following code is entered in the general declaration section of the Form.
Option Explicit
Dim LastRecord As long
Dim CurrentRecord As Long
Dim RecordLen As Long
Dim Product As Productlnfo

Dept. of Computer Science, HiSAC, Erode 104


Visual Basic – Unit IV
Dim Fi1enum
The variable Product is declared as Productlnfo. Since the user-defined type ProductInfo consists of six four
variables (Name of the product, product code, price, date of manufacture) the variable Product also contains
four variables: [Link], [Link], [Link] and product.manufacture_date. The variable Product
is used to hold a record's data.

Opening the Random Access File


The file must be opened before the data can be written to or read from the file. The following code in the
Form_Load( ) procedure opens the file.
Private Sub Form_Load()
Recordlen = Len(product)
Filenum = FreeFile
Open "c:\[Link]” For Random As Filenum Len = RecordLen
CurrentRecord = 1
LastRecord = FileLen(“c:\[Link]”)
If LastRecord = 0 Then
LastRecord = 1
End If
ShowCurrentRecord
End Sub
When a file is opened for random access we need to specify the record size of the file and file number. The first
statement uses the Len( ) function to extract the length of the variable, Person. The second statement uses the
FreeFile( ) function to get a file number that is not already in use. Subsequent statements that perform
operations on this file need this file number to tell communicate to Visual Basic on the file on which it has to
perform the operation.

The RecordLen and Filenum variables are now updated and the procedure opens the file [Link] for
random access in the C:\ directory. If the file does not exist, the Open statement creates it. After the file is
opened, the procedure updates the variables, LastRecord and CurrentRecord. The variable CurrentRecord is
used to store the record number of the currently displayed record. Since the record number 1 should be
displayed initially, CurrentRecord is initialized to 1.

The variable LastRecord is used to store the record number of the last record in the file, which is
calculated by dividing the total file length by the length of a record. However, if the file was just created, the
FileLen( ) returns 0 and the above calculation yields a value of 0 for LastRecord. An If statement is used to
check whether LastRecord is 0 and if it is so, the statement changes it to 1. The last statement of the procedure
displays the data of the record specified by the variable CurrentRecord.

A new procedure called SaveCurrentRecord is created which is responsible for saving the contents of the
TextBox controls in the record specified by the CurrentRecord.
Private Sub SaveCurrentRecord()
[Link] = [Link]
[Link] = [Link]
[Link] = [Link]
Person.manufature_date = [Link]
Put #Filenm, CurrentRecord, product
End Sub
The first six statements of the procedure fill the variable product with the contents of the Textbox controls.
After the variable is filled, the procedure is executes the Put statement store the contents of the variable in

Dept. of Computer Science, HiSAC, Erode 105


Visual Basic – Unit IV

record number CurrentRecord of the file. The Put statement takes three parameters. The first parameter
specifies the file number of the file, the second parameter specifies the record number that is being saved and
the third parameter specifies the name of the variable whose content is saved in the record. A new procedure
called ShowCurrentRecord is created in the declarations section of the Form that displays the record specified
by the variable CurrentRecord.
Public Sub ShowCurrentRecord()
Get #Fi1enum, CurrentRecord, product
[Link] = Trim(Product. Name)
[Link] = Trim([Link])
[Link] = Trim([Link])
[Link] = Trim(Person.manufacture_date)
[Link] = "Record" + Str(CurrentRecord) + "/" + Str(LastRecord)
End Sub
The first statement of the procedure uses the Get statement to fill the variable Person with the data of the current
record. The Get statement takes three parameters. The first parameter specifies the file number of the file (the
number specified when the file was opened), the second parameter specifies the record number of the record
to be read, and the third parameter specifies the name of the variable that is filled with the data read from the
record.

After the variable Product is filled with the data of the current record, its contents are displayed by
updating the Textbox controls. The TextBoxes are assigned with the trimmed values of the Product variable
because it should not contain any trailing blanks. For example, if the current record in the database contains the
product name as Visual Basic Book in the Name field, after the Get statement is executed, the variable
[Link] contains the following characters.
"VANISHREEVisualBasicBook .....”
Since the Product_Name field was defined as 3020 characters and VisualBasicBook contains only 159
characters, Visual Basic adds 11 15 trailing blanks to the field when the record was stored. The trailing blanks
should not appear on the text boxes and hence the Trim() function is used. The last statement of the procedure
displays the current record number in the Form’s caption. The following code entered in the cmdNew_Click( )
procedure, adds a new record to the file.
Private Sub cmdNew_Click()
SaveCurrentRecord
LastRecord = LastRecord + 1
Product.Product_Name = “ “
Product.Product_Code = “ “
Product.date_of_manufacture_date = “ “
Put #Fi1enum, LastRecord, Product
CurrentRecord = LastRecord
ShowCurrentRecord
[Link]
End Sub
The first statement of the procedure executes the SaveCurrentRecord() procedure so that the current record is
saved in the [Link] file. After saving the current record, the procedure specifies a new blank record to the
file as per the statements from 2 to 9. The second statement increments LastRecord, so that it points to the new
record number, then the Person variable is set to null, and finally the Put statement is used to create the new
record.

After creating the new blank record, the CurrentRecord variable is updated and it points to the new
record. Then the ShowCurrentRecord( ) procedure is executed so that the record that was just created is

Dept. of Computer Science, HiSAC, Erode 106


Visual Basic – Unit IV

displayed. The last statement of the procedure uses the SetFocus method to set the keyboard focus to the
TextBox namely Textl. The following code is entered in the cmdPrevious_Click( ) procedure which displays the
contents of the previous record.
Private Sub cmdPrevious_Click()
If CurrentRecord = 1 Then
MsgBox "Beginning of File!", vbExclamation
Else
SaveCurrentRecord
CurrentRecord = CurrentRecord - 1
ShowCurrentRecord
End If
[Link]
End Sub
The first statement of the procedure is an If statement that checks if the CurrentRecord is equal to 1 and if so, a
message box is displayed. If the CurrentRecord is not equal to 1 the procedure SaveCurrentRecord( ) saves the
contents of the TextBox controls to the [Link] file and the CurrentRecord variable is decremented by 1
and points to the previous record. The procedure ShowCurrentRecord( ) is then executed and the TextBoxes
display the new value of the CurrentRecord. The following code is entered in the cmdExit_Click( ) procedure,
which is executed when the Exit button is clicked.
Private Sub cmdExit Click()
SaveCurrentRecord
Close #Filenum
End
End Sub
The code in the above procedure saves the current record and closes the [Link] and [Link] file.
The Close statement takes one parameter that specifies the file number of the file to be closed. The End
statement terminates the application.

Sequential Access Files


Sequential access files are accessed line by line and are ideal for applications that manipulate the text
files. When data is written into a sequential file, we write lines of text into a file and when data sequential
access file is read, we read lines of text from a file. Sequential access file is opened in one of the three ways-
output, append or Input.

In order to create a sequential file, we need to open a file for output. After the file is created, we can use
the output command to write lines to the file. The following code example creates the [Link] and
writes the contents of the TextBox Text1 into the file.
Example
• A new Standard EXE project is opened and a TextBox and CommandButton is added to the Form. The
Form and the project files are saved as [Link] and [Link].
• The following code is entered in the Commandl_Chck( ) procedure.
Private Sub Commandl_Click()
filenum = FreeFile
Open "C:\[Link]" For Output As filenum
Print #filenum, [Link]
Close filenum
End Sub
• The application is run by clicking F5. Text that is necessary is entered in the TextBox and the
CommandButton is clicked.

Dept. of Computer Science, HiSAC, Erode 107


Visual Basic – Unit IV

• The entered text appears in the file [Link] file. This can be viewed by opening the file in the
Notepad after terminating the application.

If the file [Link] does not exist, the code creates it. If the file exists already, the code erases it. Since
opening a file for output creates the file, it will be empty. The Print statement is used to write text into the file.
Two parameters are passed to this statement. The first parameter is the file number and the second is the string
to be written into the file. Opening a sequential access file for append is similar to opening it for output. When a
file is opened for append, it is not erased if the file already exists. Rather, subsequent output commands append
new lines to the opened file. Let us assume that the file [Link] already exists and it contains the
following two lines.
God is Great
God is Grace
The following code appends the existing file.
• Two more CommandButton controls namely Command2 and Command3, and a TextBox control Text2 are
added to the [Link]
• The following code is entered in the Command2_Click( ) event.
• The application is run and the Command2 button is clicked.
Private Sub Command2_Click()
filenum = FreeFile
Open "c:\[Link]" For Append As filenum
Print #fi1enum, "Work is Worship"
Close fi1enum
End Sub
After executing this code, the file [Link] contains three lines. If the same code is executed again, the
file contains four lines.
God is Great
God is Grace
Work is Worship
Work is Worship
In order to open the sequential file for input, we can use the Input statement. Once the file is opened for input,
the Input( ) function can be used to read the entire contents of the file into the TextBox or a string variable. The
following code is entered in the Command3_Click( ) procedure.
Private Sub Command3_Click( )
fi1enum = FreeFi1e
Open "C:\[Link]" For Input As filenum
File1ength = LOF(1)
[Link] = File1ength
[Link] = Input(LOF(filenum),filenum)
C1ose fi1enum
End Sub
Once the code is executed and the CommandButton is clicked, Text1 control displays the file length and
Text2 displays the contents of the file. The Input() function takes two parameters. The first parameter
specifies the number of bytes to be read from the file and the second parameter specifies the file number. The
LOF( ) function returns the length of the file in bytes.

Dept. of Computer Science, HiSAC, Erode 108


Visual Basic– Unit IV

Binary Access File


Binary access files are accessed byte by byte. Once a file is opened for binary access we can read from
and write to any byte location in the file. The ability to access any desired byte ill the file makes it the most
flexible one. Before accessing a file in binary mode, the file should be opened first for binary access.
Example
• A new project is opened and the Form of the project is saved as [Link] and the project file as [Link].
• A CommandButton is added and the following code is entered in the Click event.
Private Sub Command1_Click()
mystring = “This is a Binary Access File” I I

filenum = FreeFile
Open "c:\[Link]" For Binary As fi1enum
Put #fi1enum, 100, mystring
Close fi1enum
End Sub
The application is executed and the click event of the CommandButton creates the file [Link]. The Put
statement takes three parameters. The first parameter is the file number, the second is the byte location where
the writing starts and the third is the name of the variable whose contents will be written into the file.

***** End of Unit IV *****

Dept. of Computer Science, HiSAC, Erode 109


Visual Basic– Unit V

Additional Controls in Visual Basic 6.0


SSTab Control
The SSTab Control provides an easy way of presenting several dialogs or screens of information on a
single form, using the same interface seen in many commercial Microsoft Windows applications. Only one tab
is active in the control at a time, displaying the controls it contains to the user, while hiding the controls in the
other tabs. You see the SSTab in action when you open the property pages for a control, or when you open the
Printer Dialog Box Properties to set (Paper, Graphics, Device Options). Each of these 'tabs' displays a separate
set of controls.

The Tabbed Dialog control provides a group of tabs, each of which acts as a container for other controls. The
controls are exclusive to the particular tab. Other tabs cannot use the controls of one tab. We cannot see one
tab's control in another tab control.

For each of the ‘tabs’ you can set properties, add other controls and write the code necessary. The properties are
set using the property pages. Some of the properties can set during the runtime as well. However, it is better to
set the properties during the design time.

Working with SSTab Control


• Start a new project.
• The SSTab control is not part of the standard controls on the ToolBox. 'Io add the SSTab controls, carry out
the following instructions.
• Right click on the Toolbox.
• Select Components from the pop-up menu.
• From the components Select Microsoft Tabbed Dialog Control 6.0,
• You will see this control on your ToolBox.

• Draw the control on your Form. It will appear like this.

Dept. of Computer Science, HiSAC, Erode 109


Visual Basic – Unit V

Now we need to set the Properties for each of the Tab. We need to,
➢ Add controls to each of the tabs.
➢ Change the caption for each of the tabs.
➢ Write code for the control is where necessary.

Let us set the Properties of the SSTab control.

Give the captions for the tabs as follows


Tab 0: General
Tab 1: Financial
Tab 2: Personal
At run time, the user can navigate through the tabs by either clicking on them, by, pressing CTRL+TAB, or by
using mnemonics defined in the caption of each tab. For example, if you wanted to create a tab called 'General'
and allows the user to access the tab with the keyboard combination ALT+G, you set the Tab Caption property
to ‘&General'. You can change the font, the color of the text or the background, by selecting the options from
the Property Pages.

Setting Properties at Runtime


Add the following code to the Form_Load event
[Link] = 12
[Link] = 4
By default the number of tabs is 3. Run the program. When the number of tabs and rows has been set, each tab
is indexed and can then be selected individually. Tabs are indexed beginning at zero (0).

Adding Controls to Tabs


Add controls to a particular tab's 'client area', just as you add controls to a form. Make sure that you
group related controls in one tab. Once you have added the controls, you can write code for each of them.

Enabling and Disabling Tabs at Run Time


Depending upon the functionality of your application or a particular tabbed dialog box you create, you
may use the TabEnabled property to enable and disable individual tabs or group of tabs. If the user who has
logged on to the application should not be given access to the Personal details of the Customer then you can
disable that tab at runtime. The TabEnabled property specifies the tab number, and then disables it by setting the
value to False. For Example:

Dept. of Computer Science, HiSAC, Erode 110


Visual Basic – Unit V

If UserName = "JimReeves" then


[Link](2) = False
End If
To disable a group of tabs you may use a code segment like the one below.
For i = 1 to 5
[Link](i) = False
Next i

The TabOrlentatlon Property


The TabOrientation property allows you to locate the tabs of your tabbed dialog box on either of the four
sides as follows:
[Link] = ssTabOrientationLeft (OR)
[Link] = ssTabOrientationRight.
[Link] = ssTabOrientationTop (OR)
[Link] = ssTabOrientationBottom
However it would be better to set the orientation to either top or left. If choose to set the orientation to Left or
Right, you will need to change the fonts. Only True type Fonts will be displayed in vertical tabs. We can add a
picture to a tab to increase the visual impact. The picture can be added to a tab at design time or runtime. The
picture can be added at design time by setting the properties. At run time you can set the picture property, using
the LoadPicture function as follows.
[Link](0) = LoadPicture(C:\[Link]”)
The above line when added to the Form_Load event will add the ‘[Link]’ to the first tab of the SSTab. SSTab
is a useful control. There is another control similar to this called the TabStrip control.

The ImageLlst control


The ImageList control acts like a repository of images for the other controls. An ImageList control
contains a collection of images that can be used by other Windows common controls specifically the ListView,
TreeView, TabStrip, and Toolbar controls. It can also be used with controls where a picture can be assigned
using the Picture Property of that control. Having a single repository of images saves you programming time
and effort. If you want to change a particular picture that has to be displayed, then the change can be made in
one place. You need not use the LoadPicture method at every place in the application as we did in the case of
the SSTab control.

The control uses bitmap(.bmp), cursor(.cur), icon(.ico), JPEG(.jpg), or GIF(.gil) files in a collection of
Listlmage objects. You can add and remove images at design time or run time. The ListImage object has the
standard collection object properties: Key and Index. It also has standard methods, such as Add, Remove, and
Clear. However, once the ImageList has been associated with another control you cannot delete or insert images
in the ListImages collection. You can only append images.

Working with the ImageLlst Control


Start a new project. Alternatively in the same project that you used earlier, you can add the ImageList
control. In order to add the ImageList control, From the list of components, select Microsoft Windows Common
Controls 6.0. The ImageList control and the other controls will get added to the ToolBox. The ImageList control
looks like this

Dept. of Computer Science, HiSAC, Erode 111


Visual Basic – Unit V

Adding Images to the ImageLlst


The ImageList control contains the ListImages collection of ListImage objects, each of which can be
referred to by its Index or Key property value. You can add or remove images to the control at design time or
run time. To add an image to a control at design time, use the ImageList control's Property pages dialog box. To
add Listlmage objects at design time. Right-click the ImageList control and click Properties to bring up the
Property pages.

Click the Images tab to display the ImageList control’s Property pages, as shown below

Click Insert Picture to display the Select Picture dialog box. Use the dialog box to find either bitmap or icon file
files, and click Open. Click on the key box and enter a string that will uniquely identify that image. This string
can be used to refer to the image that has been added to the ImageList collection. Optional. Assign a Tab
property setting by clicking in the Tag box and typing a string. The Tag property doesn’t have to be unique.

TabStrip Control
The function of a TabStrip control is very similar to that of the SSTab. It is used to create a tabbed
dialog box to allow users to set various attributes. It can also be used to create a tabbed dialog that preference
for an application.

Dept. of Computer Science, HiSAC, Erode 112


Visual Basic – Unit V

The TabStrip control looks like control consists of one or more Tab objects in a Tab collection. You can affect
the Tab object’s appearance by setting properties both at design time and run time, an at run time, by invoking
methods to added and remove Tab objects.

Creating Tabs at Design time or Run Time


You can create Tab objects both design and run time. To create Tab objects at design time, use the
Property pages dialog box.
1. Right click the TabStrip control and click Properties to display the Property Pages dialog box.
2. Click Tabs to display the Tabs page and make the changes.

You can add a tab at run time with code like this.
[Link] ‘find’,‘Find’,‘Fbooks’
This line of code will add a tab with Caption ‘Find’, and load the picture ‘Fbooks’. However, before using the
above code line we must associate the TabStrip control with the ImageList control.

Associating the Image List Control with the TabStrip Control


To identify a tab’s function, you can assign as image form the ImageList control to the Tab object. You
must first associate an ImageList control with TabStrip control, and this can be accomplished either design time
or run time.
To associate an ImageList control with a TabStrip control at design time:
1. Populate the ImageList control with images for the tabs.
2. Right click on the TabStrip control and click Properties to open the TabStrip Property Page dialog page.
3. On the General tab, click the ImageList box and select the ImageList control you have populated.
To associate an ImageList control with the control at run time, simply set the ImageList property to the name of
the ImageList control, as shown in the example below:
Private Sub Form_Load()
[Link] = ImageListl
End Sub

The difference between TabStrlp and SSTab


Although both the controls look alike and perform similar functions, there is one major difference. In the
case of the TahStrip, each of the Tabs is not a container by itself, while in the case of the SSTab, each of the
Tabs is a container. When one Tab is active, the controls in the other Tabsare hidden and automatically
become inactive. No programming is required. In the TabStrip the programmer has to programmatically bring
forward the controls associated with the selected tab. The other controls must be made inactive.
Private Sub TabStripl_Click()
picTabStripl([Link] - 1).ZOrder 0
End Sub

Dept. of Computer Science, HiSAC, Erode 113


Visual Basic – Unit V

One should take precautions to ensure that the hidden controls do not respond to the ALT + Key combinations.
The ZOrder will not inactivate the other controls, and they may respond to the ALT + Key combinations.

MSFlexGrid Control
The MSFlex control displays and operates on data in a table form. The Flex Grid is designed to only
display the data and not allow the user to enter data in it. However, the user can sort, merge, format tables
containing string and pictures. When bound to a Data control, MSFlexGrid displays read-only data. However,
with a little programming we can do what the guys at Microsoft did not build into the FlexGnd control. We
allow the user to enter data in the FlexGrid using a textbox.

You can add text, a picture, or both, in any cell of a MSFlexGrid. The Rowand Col properties specify
the current cell in an MSFlexGrid. You can specify the current cell in code, or the user can change it at run
time using the mouse or the arrow keys. The Text property references the contents of the current cell.

The user can resize the cell's width or height in design time or run time. If a cell's text is too long to be
displayed 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 cell's column width (CoIWidth property) or row
height (RowHeight property). Let us take up the simple task of connecting the FlexGrid to a database. We will
display the data from one of the tables in the [Link].

Draw a FlexGrid control to your form. If it is not there on your ToolBox then first add it to your TholBox as
you added other controls. Choose the Microsoft Flex Grid control from the components list. Add a Data control.
Set the properties of the Data control as follows
✓ DatabaseName: [Link]
✓ RecordSource: Customer
✓ Bring up the properties window of the FlexGrid control and set its properties as DataSource: Datal,
Number of rows: 5, Number of columns: 4
Now run the program. The customer details will be displayed in the Grid.

*******

Dept. of Computer Science, HiSAC, Erode 114


Visual Basic – Unit V

ActiveX Data Objects


Why ADO?
Why do we need another data access engine when we already have DAO and RDO? To answer this question, let
us take a look at the DAO's object model via-a-vis the current data access requirements. The DAO with the help
of ODBC can let you connect to Jet, ISAM databases and other Relational databases.

However, today's data access requirements are not limited to handling only relational data. We need to
access data from other sources as well, such as mail, Internet content, directory data from other machines and
others. The technology required to access information from these different data source is different. Therefore,
the data access modal will have to change to accommodate the new requirements.

We can access any type of data and store it locally in a new type of database and tackle the various types
of data using its native method, or we can implement the various technologies in our data access table. Both
these alternatives have their own problems.

Moreover, our requirements do not end with merely getting the data from the source and downloading it
on our machine. We would also like to make changes to the data and update the data source with these changes.
What we need is a simple, consistent application programming interface (API) that enables applications to gain
access to and modify a wide variety of data sources. A data source may be a database, a text file, a spreadsheet,
a graphics application, a cluster of heterogeneous databases, or something yet to be invented.

OLEDB
The general solution Microsoft offers to this problem is OLE DB, a set of Component-Object Model
(COM) interfaces that provide uniform access to data stored in diverse information sources. OLE DB is defined
as a new low-level interface that is part of the Universal Data Access platform. It is defined as a general-
purpose set of interfaces designed to let developers build data access tool as component using the Component
Object Model (COM). OLE DB enables applications to have uniform access to data stored in DBMS and non-
DBMS information containers, while continuing to take advantage of the benefit of database technology
without having to transfer data from its place of original to a DBMS.

This means that OLE DB is not restricted to ISAM, Jet, or even relational data sources, but capable of dealing,
with any type of data, regardless of its format or storage method, In practices, this versatility means you can
can access the data that resides in an Excel spreadsheet, text files, or even on a mail server such as Microsoft
Exchange. OLE DB has what it calls ‘provider' which let you access the different data source.

For different data sources you have different data providers. OLE DB provides four services that you will be
using in application
1. A Cursor Service. A cursor is defined as temporary, read-only table that saves the result of a query with
assigned name. The cursor is available for browsing, reporting, or other uses until it is closed.
2. A service to perform batch updates.
3. A shape service to build the data in the form of a hierarchy.
4. A remote data service provider for managing data in multi-tier environment over connected or disconnected
networks.
Unfortunately Visual Basic cannot access the OLE DB directly because of its sophistication. This is where
ADO comes into the picture. The ADO acts like the intermediary between the application and the OLE DB.
Now that you understand why we need ADO, let us see what ADO is all about.

Dept. of Computer Science, HiSAC, Erode 115


Visual Basic – Unit V

ADO
ADO enables your client applications to access and manipulate data in a database server through any of
the OLE DB providers. According to Microsoft, ADO’s primary benefits are ease of use, high speed, low
memory overhead, and a small disk footprint. ADO supports key feature for building client/server and Web-
based application.

In the case of the DAO you have seventeen objects. In the case of the ADO you have only seven objects.
Besides, you do not have to follow a strict hierarchy when working with the objects. The goal of ADO is to gain
access, to edit, and update data sources. It provides classes and objects to perform each of the following
activities:
• Connection You can access a data source using the Connection object. A connection represents an open
session or connection to a data source. Unless a connection is made, data cannot be exchanged between the
data source and the application. The connection object specifies the name of the data source, the provider
that will be used to access the data, and other parameters.
• Command Once a connection has been established with the data source, the data has to be extracted. This is
done using the Command Object. The Command adds, deletes and updates data in the data source, or
retrieves data in the form of rows in a table.
• Parameter The command to retrieve data can be qualified using parameters. Parameters are arguments to a
command that alter the result of the execution of the command.
• Recordset The command object when executed will return a set of rows from one or more tables. This set of
rows is called a Recordset. The Recordset is the primary means of examining and modifying data in the
rows. The Recordset object allows you to:
✓ Specify which rows are available for examination
✓ Traverse the rows
✓ Specify the order in which the rows may be traversed
✓ Add, change, or delete rows
✓ Update the data source with changed rows
✓ Manage the overall state of the Recordset.
• Field A row of a Recordset consists of one or more fields. If you visualize the Recordset as a two
dimensional grid, the fields line up to form columns. Each field (column) has among its attributes a name, a
data type and a value. It is this value that contains the actual data from the source.
• Errors Error can occur at any time in your application, due to the data source being corrupted or renamed by
somebody, or the password being changed or many other reasons that programmer can understand.
• Property Each ADO object has a set of unique properties that either describe or control the behavior of that
object. There are two types of properties: built-in and dynamic. Built-in properties are part of the ADO
object, and are always available. Dynamic properties are added to the ADO object’s Properties collection by
underlying data provider, and exist only when that provider is being used.
• Collection Just as in DAO, ADO provides collections, a type of object that contains other objects of a
particular type. The objects in the collection can be retrieved with a collection method, either by name, as a
text string, or by ordinal as an integer number. ADO provides four types of collections:
✓ The Connection object has the errors collection, which contains all Error objects created in response
to a single failure involving the data source.
✓ The Command object has the Parameters collection, which contains all Parameter objects that apply
to that Command object.
✓ The Recordset object has the Fields collection, which contains all Field objects that define the
columns of that Recordset object.

Dept. of Computer Science, HiSAC, Erode 116


Visual Basic – Unit V

✓ In addition, the Connection, Command, Recordset, and Field objects all have a Properties
collection, which contains all the Property objects that apply to their respective containing
objects.
• Events This is new in ADO. ADO 2.0 introduces the concept of events to the programming model. Events
are notifications that certain operations are about to occur, or have already occurred.

Establishing a Reference
Open a new project. To use ADO in your project, you have to make a reference to it. Click on Projects,
and from the menu Select References. From the list displayed in the references dialog box, select Microsoft
ActiveX Data Objects 2.0 Library and the Microsoft ActiveX Data Objects Recordset 2.0 Library.

In order to achieve our objective of accessing a data source, extracting a set of records from it and
manipulating or editing the Recordset and finally updating the DataSource we have to follow the below steps.
✓ Make a connection to a data source.
✓ Create a command to specify the records to be extracted.
✓ Execute the command.
✓ Navigate and edit the data in the Recordset.
✓ Update the data source with changes made to the data in the Recordset.
ADO does not follow strict hierarchy. You can create a Recordset without explicitly making a connection.

The Data Source


What we need now is a data source. Let us use the [Link] as our data source. Having decided that
[Link] is our data source, we need to define the data store using the ODBC Data Source Administrator.

The ODBC Data Source Administrator


From the Control Panel, double click on the ODBC icon. This will bring up the ODBC Data Source
Administrator dialog box. Click on the Add button to add a data source. Another dialog box will be displayed,
asking you to select the driver. Select MS Access driver (*.mdb) since we are going to work on [Link]
click on Finish. The next dialog box displayed will ask you to specify the name of the database.

Click on Select to choose the name of the .mdb file. After selecting the .mdb file, enter the name of the
data source. You will be using this name as the DSN (Data Source Name). Click Ok and exit from the ODBC
administrator.

Using the Data Source Name in a Project


In the General declaration, add the following lines of code
Dim adocon As New [Link]
Dim rs As Recordset
Dim strconnect As String
The first line declares and sets 'adocon' as an ADODB connection object. You can declare the above as follows
Dim adocon as [Link]
In the Form_Load event you can say
Set adocon As New [Link]
We have declared the connection object. Now to set the connection to a data source. In the Form_Load event
add the following
[Link] = "DSN=[Link]"
[Link]

Dept. of Computer Science, HiSAC, Erode 117


Visual Basic – Unit V

Add the line "MsgBox [Link]" to see if the database has been opened. Run the program
and checkout if you have managed to set up a connection with the data source using ADO.

Creating the command We have established a connection with the data source. Now we need to construct our
command using SQL such that it will return the records as recordsets. Our Command can be a literal string or a
variable that represents the string. We can select all the records from the Customer table of the [Link].
The command object must be linked to the connection object using the following line.
[Link] = adocon

Executing the command Now that we have built the command, the command must be executed. The command
can be executed by either using the command object, or by using the Recordset object. Add the following lines
to your code
Set rs = [Link]
MsgBox [Link](l)
In this case you are using the command object to execute. The Connection object is not visible here. The
Connection object is set in the ActiveConnection property of the Command object. Block the above lines and
add the following lines
Set rs = [Link]("seleet * from Customer")
MsgBox [Link](l)
In this case the Connection object is used without bringing in the Command object. These methods have their
own advantages and disadvantages. The two methods that return a Recordset are [Link],
Command Execute. The syntax is as follows
[Link](CommandText, RecordAffected, Options)
[Link](RecordAffected, Parameters, Options)
Both methods return fast, static-cursor, forward-only Recordset objects. The CommandExecute method allows
you to use parameterized commands that can be reused efficiently.

Manipulating the records in the Recrodset The properties and methods for a Recordset in DAO are valid here
as well. Most of the properties of the Recordset deal with navigating and manipulating the Recordset. The row
that has your focus is the ‘current row’. If you move to the next row then that row becomes your ‘current row’.
There are methods to locate a particular record, to delete records, to update records and so forth. There are also
properties that will view selective records, sort them in an order of your choice, etc. Add a command button to
your form. Add the following lines of code to its cIick_event.
Private Sub Command1_Click()
[Link]
Do While Not [Link]
[Link] [Link](O) & " "; [Link](l)
[Link]
Loop
End Sub
This segment of code will display the first two fields of the Recordset. Remember that this Recordset returns all
the fields from the Customer Table of the [Link]. We are viewing only the first two fields of the
Recordset. The MoveFirst method moves the record pointer to the first record. The MoveNext method moves
the record pointer to the next record.

If you want to view only a certain set of records you can set the filter property of the Recordset, In order
to view only those customers who are from Bangalore you can add the following line to your code.
[Link] = "Customer_City LIKE 'Ban*'"
Your code will look like this
Dept. of Computer Science, HiSAC, Erode 118
Visual Basic – Unit V

[Link] = "Customer_City 'Ban*'"


[Link]
Do While Not [Link]
[Link] [Link](O) & " "; [Link](l)
[Link]
Loop
There are still two more steps.
1. Update the data source with the changes made.
2. Confirm the update.

Using the ADO Data Control


We can display the data from a Recordset (data source) using ADO code, or with the help of the ADO
Data Control. In order to use the ADO Data, we need to add the control to the form. Data Control cannot work
with ADO, so we need to add the ADO Data control. Right click on the ToolBox, and from the pop-up menu
select Components. In the dialog box click on Microsoft ADO Data Control 6.0. The ADO Data control gets
added your ToolBox. Draw the ADO data control on your form and set the properties. Right Click on the ADO
Data control and select ADODC Properties from the menu.

The Property Pages of the ADODC allow you to specify a lot more information than the Data control. In
the case of the Data control, you only need to give the following four details.
The type of database (Access, dBase, FoxPro ...)
The Name of the database
The type of Recordset (Table, Dynaset, Snapshot)
The RecordSource (A Table name, an SQL Query…..)
However, you may need to do a little more in case of the ADODC, the Property pages of ADODC contain four
tabs. They allow you to set the various properties of the ADODC. They are

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

Use data links file You will need this option if you are going to link a textbox or a grid or some such control to
an application like Excel or Word via DDE.

Use ODBC date source name You can mention the name of the DSN that we created using the ODSC Data
Source Administrator, The DSNs already created will be displayed in a drop-down ListBox. You can select the
one you need to work with, or you can build a new DSN.

Use connection string You can build the connection string here by clicking on the 'Build' button. This will
bring up a Wizard and guide you along.

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

RecordSource Here you can specify the method of creating the Recordset. That is, you can indicate the
Command Type (adCmdUnknown or adCmdText or adCmdTable, or adCmdStoredProc)

Table or Stored Procedure


SOL text if you choose adCmdTable in the Command Type, then in the Table or Stored Procedure, you
can select the table name from the Database. If you choose the other options, then you have to enter the Stored
Procedure or the SQL Command Text.

Dept. of Computer Science, HiSAC, Erode 119


Visual Basic – Unit V

Font and color The other two tabs Font and Color allow you to customize the appearance of the ADO Data
Control.

Using Bound Controls


Data aware controls can be bound to the ADODC just as with the Data control. There are two new
options that are made available with ADO in Visual Basic 6.0. You can specify the Data Member and the Data
Format along with the Data Source and the Data Field.

Updating the data in the Data Source


The code required to navigate the Recordset or to find a particular file is very similar to the code that we
used with DAD. ADO provides the facility to rollback a transaction if any error occurs while updating anyone
of the related tables for a given transaction. For example, a transaction like a payment receipt may mean
updating the Customer Table, the Payments Received Table, the Payments Due Table, etc. While updating the
last table, say the Payments Due table, if there is an error for some reason, then the entire transaction must be
rolled back. If this is not done then the data in the database will not be consistent. ADO monitors the transaction
and rolls it back in the event of an error.

There are two approaches that ADO uses to add or modify the data in the database
1. Changes made to the data or the row are made in the 'copy buffer' and not directly to the Recordset. If
the changes are acceptable then they are applied to the Recordset.
2. Changes are made directly to the data source either immediately or in a batch mode. These modes are
governed by the CursorLocation and LockType properties. Changes will make to the data source in the
immediate mode as soon as you confirm an update.

In the Batch node, every time you confirm an update, the Recordset gets update and not the data source. In
order to update the data source you have to invoke the UpdateBatch method. In order to use this method you
must open the Recordset in the batch mode. You can also make a change to the data in a field or fields and
invoke the update in one step.

If your application has transactions that update more than one table it is a good idea to use the
‘transaction’ method. This is to ensure that related operations that depend on each other either all occurred
successfully, or else were all canceled. There are three transaction methods involved. They are

BeginTrans To be invoked when you start working on the Recordset. This method begins a new transaction.
Once the BeginTrans method has been invoked, the OLEDB provider will not continuously commit the
changes made to the data source unless you call CommitTrans to commit the changes or RollbackTrans to
reverse the changes and end the transaction.

CommitTrans To be invoked when you want to commit the changes to the data source. CommitTrans saves
any changes made to the Recordset and ends the current transaction.

RollbackTrans This method is to be invoked to cancel any changes made within the current transaction. This
method also ends the current transaction.

The CommitTrans and the RollbackTrans may also start a new transaction. The following code will show you
how to use the Transaction methods. Add a Module to your project.

Dept. of Computer Science, HiSAC, Erode 120


Visual Basic – Unit V

Declare the variables as follows


Public adcon As New [Link]
Public rs As New [Link]

In the Form_Load event add the following code


Private Sub Form_Load()
[Link] = “DSN=Invoice”
[Link]
[Link]
Set rs = New [Link]
[Link] = adLockPessimistic
[Link] "Customer", adcon, , , adCmdTable
[Link]
End Sub

In the code Module, create a function to display the current row of the Recordset
Sub Showfields()
[Link] = rs!Customer_Name
[Link] = rs!Customer_City
End Sub

To the Next Record Command button add the following code


[Link]
If [Link] Then [Link]
Call Showfields

This code will display the next record record everytime that you click on the Next button. Now let us assume
that the user wants to edit the data that is displayed. To the Edit button add the following code
rs!Customer_Name = [Link]
rs!Customer_City = [Link]
[Link]
This segment of code is enough to update the Recordset. In case you want the System to prompt you about the
changes made. You can write another procedure called UpdateRecord. This procedure will have the following
code.
If MsgBox(“Save all changes?”, vbYesNo) = vbYes Then
[Link]
Else
[Link]
End If
The above code segment will ask for your confirmation before committing the changes made by you. If you
answer yes to the above question, the changes are committed to the data Source. If you answer No then the
changes are rolled back.
*****

Dept. of Computer Science, HiSAC, Erode 121


Visual Basic – Unit V

Crystal and Data Reports


Crystal Reports
The user of the applications would definitely want to know a number of details about the state and status
of the business. For example, the total number of items sold in a day, week, or month. Or the list of items
supplied by a Supplier for a given month. Or the payments due with amount and date. A businessman will need
to know a lot more than this. Our application must provide the means for him to get the all the information
possible based on the data provided to the application.

We can build this functionality into our application with the help of VBA code or through report
generators like Crystal Reports or Data Report. Crystal Reports is a third party product developed, by Seagate
of Singapore. It has been bundled with various data access tools.

Prerequisites for working with Crystal reports


Hardware A printer must be installed. It need not be physically connected though. This is because Crystal
Reports builds the reports based on the properties of the report structure that you want to create.

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

Installation So, Crystal Reports has been installed and you have a rough ‘copy’ of the report that you want. Let
us get started. Click on Add_Ins, Select Report Designer. Click on Field and Select New. Or click on the icon
that represents a new report.

Creating a Report through a Wizard


You are presented with the Create New Report Wizard that will allow you to create new reports. You
can choose the report style. For this exercise, click on Standard. The wizard will now take you through a
number of steps asking you for details. Supply the details to the best of your knowledge. If even you make an
error the reports can be corrected later. Remember that right from the first step you are given an option to

Dept. of Computer Science, HiSAC, Erode 122


Visual Basic – Unit V

preview the report that you are creating. Once you do that you cannot come back to the wizard. Should you
wish to return to the wizard, you will have to start all over again. We will see the various steps required to
create a Standard Report and then call the 'Expert' for a particular step.

The wizard in the dialog box will ask you to select the database(s) that you will be using to generate the
report. Let us select [Link] for a change. Upon selecting the [Link], all the tables and stored queries /
view will get added to the ListBox. After you have added all the databases that you want to work on click on
'Done'.

This figure will display the various tables and the relationship between each of them. If you think there
are too many tables and views and you do not need all of them, then you can delete some of them. Click on the
button ‘Back’. Click on the ‘Back’

You can select the items that you do not need and click on remove to remove them one by one. When
you are sure you have only those tables that you need click Next to continue. It will show the selected tables
and their relationship. Click Next to continue.

In next dialog box you can add the fields that you wish to include in your expert. The fields that you
select here will appear on the report. However the selection criteria for the selected records need not depend on
the fields alone. When you have selected the fields and added them one by one in the ‘Report fields’ ListBox.
Click on the Next to continue.

In next dialog box you can choose the fields on which the report is to be sorted out. For example, you
can sort all the details based on the City, or the Product that a customer uses, or the Turnover of the company,
etc. Select the fields on which the criteria are to be built and then select the sort order. For example, you can
sort the details in the ascending order or descending order. When you are through with this click Next to
continue.

In next dialog box you must select the fields on which you have to perform calculation like group total,
sun-total, etc. For example if you want to know the number of customers in a particular city, the select
Customer_City and add it to the ‘Total Fields’ ListBox. Here you can also choose if you want to total the
number of customers for a city or if you want to the add the figures for a particular column. For our example
choose Count. Then Click Next to continue.

In next dialog box you must choose the fields based on which the records must be selected from the
database. In the Report Fields ListBox you are presented with the fields that you have selected for the report. If
none of these fields meet your requirements to determine the selection criteria, you can scroll down further and

Dept. of Computer Science, HiSAC, Erode 123


Visual Basic – Unit V

select from the fields that have not been included in the report. Build your selection criteria and click Next to
continue.

In next dialog box you can select the layout of the report. Select the report layout style that you think
suits you best. The selection of the style will depend upon the type of data that you are likely to have on the
report. For example, if you are going to have the total amount outstanding from a customer, and your report will
hold the status of customer for customer for a city, or area then you can choose. Trailing Break Style or the
Drop Table style. Next you can preview the report. The preview of the report will look like this. So we have
created a report from scratch with the help of a wizard or an Expert.

Creating a Report without a Wizard


Let us create a sample database file with two tables. The name of the .mdb file can be any name of your
choice. We will call it [Link]. We will work with two tables. The Customer_Data and the Order_Data tables.
The Customer_Data table has these fields
Customer_Code
Customer_Name
Customer_City
The Customer_Data table is indexed on Customer_Code as the primary index. The Order Data table has these
fields
Order_ID
Customer_ID
Order_ Value
Order_Date
The Order_Data table is indexed on Order_ID as the primary index and Customer_Code as the secondary index.
Click on the New File icon or select New from the File Menu. You will see the figure that we saw in the last
session. Instead of selecting Standard, click on 'Custom'. An extended set of buttons will be displayed.

From the extended set of buttons displayed select Custom and then click on the Data File button. You
will be asked to select the database file. Select [Link] in order to complete this example.

This is called the Design/Preview window where you can design and view the report as you go on
adding fields to it.

The Design/Preview Window


This is the window where you design your reports. The default tab is the Design tab. This window is
divided into two parts. The Large white area is where you actually insert the fields and the gray area on the left
side with several rows. The rows will be titled as Title, Page Header, Details, Page Footer and Summary. Each

Dept. of Computer Science, HiSAC, Erode 124


Visual Basic – Unit V

of these titles is separated by a line that extends into the large white area. This is to help you correctly insert and
correct the data that should appear on the report. If you click on the Preview tab, a preview of the report will be
displayed. You can zoom to get a better view of the report.

In the Insert Data Field dialog box displayed over the design window consists of the list of fields that
you can display on the report. Apart from the list box there are three buttons "Insert", "Done" and "Browse
Field Data". To insert a field select it and push the Insert button. Your mouse pointer will suddenly acquire a
square tail. This is tells you that you have selected a field and you can insert it at a location on the report. Move
the pointer to the location where you wish to display the selected field and click on the mouse. The field will get
inserted at that location.

Let us get back to the Insert Data Field Dialog box. Select Customer_Name from the list of fields
displayed in the ListBox. Click on the 'Insert' button. Notice that your mouse pointer has acquired a 'tail'. Move
the mouse pointer to the section ‘Detail' on the 'White Area' and click the left mouse button. The Customer
Name field gets placed there along with the heading. You can change the column heading later if you do not
like the current heading. Similarly add two more columns namely Order_Date and Order_Value to the report.

Click on the Preview tab to view the report. You will see a list of the customers with the Order Date and Order
Value. Some of the problems with this report are:
1. The customer names are repeated.
2. There are no sub-totals for individual customers.
3. There is no grand total of the Order Value.

Let us see how we can correct them. We are at liberty to call on the 'experts' for help. We will first sort the
listing on Customer_Name. Click on the 'Reports' Menu Option. From the menu items select Sort ‘Records'.
You will see the following dialog box. From the list of items in Report Fields ListBox on the left add the
Customer_Name to the Sort Fields ListBox on the right. Select the Ascending order for sorting the records.
Now click the Preview tab to see the result.

To avoid repeating the Customer_Name for every occurrence, click on Format. From the menu click on
‘Fields’. Click on the 'Suppress if Repeated' option button. To include Sub-Totals for the Order_Value for each
customer for each customer, right click the mouse button Order_value in the Detail section. From the pop-up
menu select ‘Insert Sub-Total'.

The message displayed will be "When the report is printed the records will be sorted and grouped by".
Next to this message is a drop-down combo box. Click on the down arrow to View the list of fields that you can
group by. Select Customer_Data Customer Name. A message will appear at the bottom of the dialog box. "The
subtotals will be printed on any change of Customer_Data.Customer_Name". Click OK to accept the changes.
To add the Grand Total to represent the total of all Order_ Values, once again right click the mouse on the
Order_Value in the Details section. From the pop-up menu select 'Insert Grand Total'.

Select 'Sum' from the drop-down ComboBox. You have a wide choice of options to choose from for the
Grand Totals column. Now preview your report. Save the report in your directory. It will have an extension
name “.rpt".

Dept. of Computer Science, HiSAC, Erode 125


Visual Basic – Unit V

Calling Crystal reports from Visual Basic.


Start a new project. The Crystal Reports control should be added to the form, from where you intend to
call the report. You will not find the control on your toolbox. To add it to your toolbox right click the mouse on
the toolbox and select Components from the pop-up menu. From the list of components select Crystal Reports
Control 4.6. Add an instance of the Crystal Reports control on your form. Since this control is not visible during
runtime it will appear as an icon at design time. Right Click on the icon and select Crystal Properties from the
menu.

The most important property to set here is the ReportFileName. This is set in the General Tab. Set it to
the filename under which you saved your report. Under this tab you can also specify if your report should goto
the printer or to the window or to a file. Add a CommandButton to your form. In the click event of the
CommandButton add the following line of code
[Link] = 1
If you are going to use more than one report file in your program then you need to set the ReportFileName
before you run the report. You see the ReportFileName as follows
[Link] = "C:\vb-exersices\[Link]"
[Link] = 1
Most of the properties that you see in the property pages are available at runtime and can be modified when
needed. You can for example use a selection formula to select the records that appear on the report. If you want
the report to display selected records, for example you want to see details of the customer whose
Customer_Code is C455 then add the following line in the SelectionFormula ListBox under the Selection Tab.
{Customer_Data.Customer_Code } = "C455"
Run the program and you will see the details of customer C455 only.

Data Report
Data Report is the new offering from Microsoft perhaps with a view to replacing Crystal Reports in the
long run. Data Report as it stands today is meant for programmers. A general user of computers will not be able
to get around it. Let us take a look at what Data report has to offer and how we about using this tool.

In order to use Data Report you need to use ADO or Data Environment. Since we have covered ADO in
the previous chapter we will work using ADO with Data Report. You need to follow the following steps to
generate a report using the Data Report.
1. Create a data source using ADO.
2. Add the Data Report object to your project.
3. Place Textboxes representing the various fields that you want on the DataReport object.
4. Link the Textboxes to the various fields of the data source.
Dept. of Computer Science, HiSAC, Erode 126
Visual Basic – Unit V

5. Display the report using the Show method.


This sounds like quite a bit of work. Actually it is quite easy if you have already worked with the Data Control
or the ADO Data Control.

Getting acquainted with the Data Report Designer


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

Let us take a look at the DataReport object. This will give us an idea about the approach to be taken for
generating a report. The Data Report Designer is the form on which you design the layout of the report. The
DataReport object is the programmable object that represents the Data Report Designer.

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

Parts of the Data Report


The Data Report consists of three main components.
Data Report object
Section object
Data Report Controls I
You need a form or the area where you arrange the various fields that you want to display. This is the Visual
Designer component of the DataReport object. The designer component can be controlled programmatically
using the DataReport object.

The Data Report Designer consists of a number of Sections like the header, footer, and details sections.
Each of these Section objects can be configured at design time or controlled through code at run time. Each
section has a set of properties that can be manipulated. Finally you have the Data Report controls, which are

Dept. of Computer Science, HiSAC, Erode 127


Visual Basic – Unit V

special control that you can create on the Data Report designer. These tools are placed under a separate tab on
your toolbox.

The default Data Report designer contains these Sections


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

Data Report Controls


Following are the new set of controls that are placed under the Data report tab on your toolbox.
• TextBox Control (RptTextBox) - To display text or other formatted data.
• Label Control (RptLabel) -To display the labels on the report to identify fields or sections.
• Image Control (RptImage) - To display pictures on the report. This control cannot be tied to a data field.
• Line Control (RptLine) -To draw lines on the report.
• Shape Control (RptShape) - To draw rectangles, circles, etc on the report.
• Function Control (RptFunctiop) -This is a special text box that calculates values as the report is generated.

Extracting the Data


We saw earlier in this session that we must first create a data source using ADO. Let us do that now. We
will use our [Link]. Let us create a list that consists of CustomerName, Customer_City and Order_Value.
We need to work with two tables
Dim adocon As [Link]
Dim adors As [Link]
In the above code fragment we have declared as ADO connection and an ADO Recordset object. In the Form
load event add code to create the connection and then to create a recordset. The following lines of code will do
the trick
Set adocon = New [Link]
[Link] “DSN=Invoice”

In the form load event itself you can populate the recordset. But this is not such a good idea. If you are not
going to view / display the report then the recordset is unnecessarily taking up memory. In order to avoid this
add a button to your form. Let the caption be “Display”. In the code window of this CommandButton, enter the
following code.
set adors = [Link](“Select distinctrow Customer_data.customer_name,
Customer_data.address2, orders_data.ordervalue from Customer_data, orders_data where
Customer_data.customer_code = orders_data.customercode”)

Dept. of Computer Science, HiSAC, Erode 128


Visual Basic – Unit V

The above code segment will populate the Recordset. We now have readily available. The Recordset will have
all the fields from both the tables. Next we have to display the fields that the user is supposed to view.

Working with the Data Report In the details section of the Data Report designer, add three of the RptTextBox
controls. Notice that it is just like adding ordinary textbox controls. Also observe that these textboxes contain a
caption called 'Unbound'. This means that these Rpt'IextBox controls are not bound to any data source or data
field.

Binding the RptTextBox to a data field: Bring up the Properties window of the RptTextBox by pressing F4.
Enter the name of the field that you want to display against the Data Field property.

For our Example, the three RptTextBox controls will display the “Customer Name”, “Customer City” and
“Order Value”. Enter the field’s names as they are in the database. If they are wrongly spelt you will get an
error message. Your Data Report designer will look like the figure in the next page.

Displaying the report We are now ready to display data. We have created the recordset. We have assigned the
fields in the Data Report Designer. We need to link the record source to the Data Report. Then we must call the
Show method of the Data Report. The following lines have to be added to the “Display” command button.
Set [Link] = adors
[Link]
Run the program now. Add headers to report using the RptLabelBox controls so that the report looks
meaningful.

Creating Multiple Reports


The users of your application are not going to be happy with just one report. They will want the data
presented in many and every combination. We can cater to this as well. There are two ways of handling the
'multiple reports' situation. For every report that the user wants, we can create a DataReport or we can display
different data using only one or a few DataReport forms. Both the approaches have their merits and demerits.
We have already created one report using one DataReport. Creating more reports using the same method should
not be very difficult. However displaying more than one report using only one DataReport involves little work.

Details like Caption, Page Headers, Footers, etc for each of the reports must be determined. The heading
for the data must also be determined. The data and the source of the data must also be worked out. Depending
upon the number of reports that you may need to display on a form, you have to work out if it is feasible to
create a recordset or a number of recordsets for all the reports. Creating a recordset every time the user asks for
a report may not be a good idea especially in a multi-user environment. At the same time creating a large
number of recordsets and locking up resources will not be the right thing to do.

****** End of Unit V ****

Dept. of Computer Science, HiSAC, Erode 129

You might also like