0% found this document useful (0 votes)
15 views106 pages

VB CS-Final Notes

Visual Basic is a user-friendly, event-driven programming language developed by Microsoft, with its final version being Visual Basic 6.0 before transitioning to Visual Basic.NET. It allows users to create GUI applications easily and includes an Integrated Development Environment (IDE) that provides various tools for application development. Key components of Visual Basic include forms, controls, properties, methods, and event procedures, which collectively facilitate the creation and management of user interfaces and application logic.
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)
15 views106 pages

VB CS-Final Notes

Visual Basic is a user-friendly, event-driven programming language developed by Microsoft, with its final version being Visual Basic 6.0 before transitioning to Visual Basic.NET. It allows users to create GUI applications easily and includes an Integrated Development Environment (IDE) that provides various tools for application development. Key components of Visual Basic include forms, controls, properties, methods, and event procedures, which collectively facilitate the creation and management of user interfaces and application logic.
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
You are on page 1/ 106

UNIT 1

INTRODUCTION
 Visual Basic is a third-generation event-driven programming language first released by
Microsoft in 1991.
 The final version was Visual Basic 6.0 before the release of Visual Basic.NET.
 Visual Basic is a user-friendly programming language designed for beginners, and it
enables anyone to develop GUI window applications easily.
 Features such as easier comprehension, user-friendliness, faster application
development and many other aspects such as introduction to ActiveX technology and
internet features make visual basic an interesting tool to work with.

1.1 GETTING STARTED WITH VB6


VB is an object oriented programming development system for creating sophisticated
professional applications that run under any of the Microsoft windows environments. It was
developed from the programming language called BASIC in the1970s. BASIC means
Beginners' All-purpose Symbolic Instruction Code. Visual Basic provides a convenient
method for building user interfaces. A complete version of Visual Basic 6.0, the enterprise
edition, requires more than 250mb of hard disk space. It has following two major
components:
1. An extensive collection of pre-written tools, called controls.
2. A complete set of programs commands, derived from Microsoft implementation of
the classical basic programming language.
The overall approach tools VB programming is to:
1. Create a user interface i.e., appropriate to the particular applications at hand.
2. Add a group of basic instruction to carry out the actions associated with each of the
controls.
1
1.2 PROGRAMMING ENVIRONMENT
Visual Basic is initiated by using the Programs option ---> Microsoft Visual Basic
6.0 --> Visual Basic 6.0. Clicking the Visual Basic icon, user can view a copyright screen
enlisting the details of the license holder of the copy of Visual Basic 6.0. . The user can work
for a new project by
 Selecting New/Standard EXE.
 Selecting new project from the file menu.
The user can open an existing project by selecting either the Existing tab or the
Recent Tab. Another way a user can open an existing project is to select Open Project from
the File menu, and then select Open project from the file menu, and then select the particular
project of interest.

Form Design window Menu Bar Project Window

Title Bar Tool Bar

Project container Window Properties Window


Toolbox Immediate Window Form layout Window

2
Integrated Development Environment
It is commonly used in the programming world to describe the interface and environment that
we used to create our applications. it is called integrated because we can access virtually all
of the development tools that we need from one screen called an interface. It is commonly
referred to as the design environment or the program.

IDE is made up of a number of components


Menu bar, Toolbar, Project Explorer, Properties Window, Form Layout Window, Tool box,
Form Designer, Object Designer.

MENU BAR
Menu bar displays the command that is required to build an application. The main
menu items have sub menu items that can be chosen when needed, selecting one of the
choices (File, Edit, view, Project, Format,… Help) causes one of Visual Basic’s drop-down
menus to appear. The menus present logical groupings of Visual Basic’s individual features.
The toolbars in the menu bar provide quick
access to the commonly used commands and a button in
the toolbar is clicked one ton carry out the action
represented by it.

TOOL BOX
The Toolbox contains icons that represent
commonly used controls, such as label, text box,
command button, picture box, frame, picture box,
option button, file list box, and so on.
The user can select a control from a toolbox and
place it in the current form design window by double clicking on the control icon, or by
clicking once the control icon, then clicking on the desired location within the Form design
Window and dragging the mouse so that the control has the desired size.

Standard Toolbox Controls

Select Objects
Select Objects is the only item in the Toolbox that doesn't draw a control.

3
Label - Allows to have text that do not want the user to change, such as a caption
under a graphic.

Text Box - Holds text that the user can either enter or change.

Combo Box - Allows to draw a combination list box and text box. The user can either
choose an item from the list or enter a value in the text box.

List Box - Use to display a list of items from which the user can choose. The list can be
scrolled if it has more items than can be displayed at one time.

Check Box - Creates a box that the user can easily choose to indicate if something is
true or false, or to display multiple choices when the user can choose more than one.

Option Button - Allows displaying multiple choices from which the user can choose
only one.

Toggle Button - Creates a button that toggles on and off.

Frame - Allows creating a graphical or functional grouping for controls. To group


controls, draw the frame first, and then draw controls inside the frame.

Command Button - Creates a button the user can choose to carry out a command.

Tab Strip - Allows defining multiple pages for the same area of a window or dialoging
box in application.

Multi Page - Presents multiple screens of information as a single set.

Scroll Bar - Provides a graphical tool for quickly navigating through a long list of
items or a large amount of information, for indicating the current position on a scale, or as an
input device or indicator of speed or quantity.

Spin Button - A spinner control can use with another control to increment and
decrement numbers. It can also use it to scroll back and forth through a range of values or a
list of items.

Image - Displays a graphical image from a bitmap, icon, or metafile on the form.
Images displayed in an Image control can only be decorative and use fewer resources than
a Picture Box.

4
Project Explorer Window
The project window displays a hierarchical list of the files associated with a given
project. These files represent individual forms and modules. The user can display a form or
module within the Project Container Window by double-clicking on the corresponding icon
within the Project Window. The user can select either the Object View or the Code view by
clicking on one of the two leftmost icons within the toolbar at the top of the Project Window.

Properties Window
Every object has properties associated with it. Each object has its unique list of
Properties. The properties window allows the user to assign or change the properties
associated with a particular object.
Active the object by clicking on it; then choose from the corresponding list of properties
shown in the left column of the properties window.

Object Browser
The Object Browser allows to browse through all
available objects in the project and see
their properties, methods and events. In addition,
the procedures and constants that are available
from object libraries in the project. It can easily
display online Help as browse. It can use
the Object Browser to find and the use created
objects, as well as objects from other applications. Get help for the Object Browser by
searching for Object Browser in Help.

To navigate the Object Browser


1. Activate a module.

2. From the View menu, choose Object Browser (F2), or use the toolbar shortcut: .
3. Select the name of the project or library to view in the Project/Library list.
4. Use the Class list to select the class; use the Member list to select specific members
of class or project.
5. View information about the class or member selected in the Details section at the
bottom of the window.
6. Use the Help button to display the Help topic for the class or member selected.

5
Object Related Concepts
Objects: Forms and controls are collectively referred to as objects. Objects are also
associated with their own properties and method.
Forms: In VB a window is called a form. Each form includes a title bar at the top. A
form may also include a menu bar, a status bar, one or more tools bars, slide
bars, etc. A user area occupies the remaining space with in the form.
Controls: The icons with which the user interacts are called controls. The user will
typically activate a control to produce an event.
Properties: Objects includes properties that generally define the appearances and
behaviors. For eg. Name, caption, height, back ground color.
Methods: Some objects also include special program statements called methods. A
method brings about some user predefined action affecting the associated
objects.
Events and Event Procedures
VB is based up on an event driven paradigm, in which each feature included within
the program is activated only when the user responds to a corresponding object within the
user interface. Event: The programs responds to an action taken by the user is referred to as
an event. Event Procedure: The group of basic commands that brings out about this
response is called an event procedure.

1.3 WORKING WITH FORMS


Visual Basic Form is the container for all the controls that
make up the user interface. Every window in a running visual
basic application is a form, thus the terms form and window
describe the same entity
DEFINITION
A form is a window that contains an application code
and has other objects placed on it to create the user interface. Every form object has its own
properties, events and methods associated with it.
The main characteristic of a Form is the title bar on which the Form's caption is
displayed. On the left end of the title bar is the Control Menu icon. Clicking this icon opens
the Control Menu. Maximize, Minimize and Close buttons can be found on the right side of
the Form. Clicking on these buttons performs the associated function.
The control menu contains the following commands:

6
 Restore: Restores a maximized Form to the size it was before it was maximized;
available only if the Form has been maximized.
 Move : Lets the user moves the Form around with the mouse
 Size : Lets the user resizes the control with the mouse
 Minimize: Minimizes the Form
 Maximize : Maximizes the Form
 Close : Closes the Form

Creating a New Form


Creating a Window Forms Application by following
the following steps in Microsoft Visual Studio: File ->
New Project -> Windows Forms Applications. Finally, select OK, Microsoft Visual Studio
creates project and displays following window. Form with a name Form1.

Form Properties

S.No Properties Description

1 BackColor Sets the form background color

2 BorderStyle The BorderStyle property determines the style of the form's


border and the appearance of the form
 None,Sizable,Fixed3D,FixedDialog ,
 FixedSingle, FixedToolWindow
 SizableToolWindow

7
3 Font This property specify font type, style, size

4 Height This is the height of the Form in pixels.

5 MDIchild It specifies if this window must be shown within a multiple


document interface window

6 MinimumSize This specifies the minimum height and width of the window
can minimize.

7 MaximumSize This specifies the maximum height and width of the window
maximize.

8 Name This is the actual name of the form.

9 StartPosition This property determines the initial position of the form when
it's first displayed. It will have any of the following values:
 CenterOwner: The form should be shown in the
center of the form that owns it.
 CenterScreen: The form is center of the user screen.
 Manual: The location and size of the form will
determine its starting position.
 Windows Default: It lets windows decide where the
form should be shown.

10 Text The text, which will appear at the title bar of the form.

11 Width This is the width of the form in pixel.

Loading and Unloading Forms


In order to load and unload the forms, Load and Unload statements are used. The
Load statement has the following syntax:
Load FormName
And the Unload statement has the following syntax:
Unload FormName
The FormName variable is the name of the Form to be loaded or unloaded. Unlike the
Show method which cares of both loading and displaying the Form, the load statement
doesn't show the Form. To call the Form's Show method to display it on the desktop.
Showing Forms
Show method is used to Show a Form. If the Form is loaded but invisible, the Show
method is used to bring the Form on Top every other window. If the Form is not loaded, the
Show method loads it and then displays it. Syntax of the Show method of the Form
FormName.Show mode

8
Hiding Forms
The Hide method is used to hide a Form. The following is the syntax of the Hide Method.
FormName.Hide
To hide a Form from within its own code, the following code can be used.
Me.Hide

1.4 DEVELOPING AN APPLICATION


An application can be created with the project. A project is a collection 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.

Examining the project window


In order to examine the project window, project explorer command is selected from
the view menu. It displays project window in the form. Project window features view code,
view object and toggle folders button. Selecting the desired ones leads either to the code
window or to the form or by toggling the object in project window.

Changing Properties and Adding controls


Before writing an event procedure for the control to response to a user's input, user have to
set certain properties for the control to determine its appearance and how it will work with the
event procedure. set the properties of the controls in the properties window at design time or
at runtime. Text is a typical properties window for a form. It refers particularly to interface of
the program as shown
Private Sub Command1_Click()
a = Val(Text1.Text)
b = Val(Text2.Text)
r=a+b
Text3.Text = r
End Sub

9
Creating an Executable File
User can create an executable file in Visual Basic by choosing Make EXE file command
from the File menu. A Make EXE dialog box appears. Now the File is saved as calculate.exe
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 forms
from memory.

1.5 Variables, Data Types and Modules


Visual Basic uses building blocks such as Variables,
Data Types, Procedures, Functions and Control
Structures in its programming environment. This section concentrates on the programming
fundamentals of Visual Basic with the blocks specified.

MODULES
Code in Visual Basic is stored in the form of modules. The three kinds of modules are
1. Form Modules,
2. Standard Modules and
3. 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 the duplication of code, a separate module containing a procedure is created
that implements the common code. This is a standard Module.

10
Class module (.CLS filename extension) is the foundation of the object oriented
programming in Visual Basic. New objects can be created by writing code in class modules.
Each module can contain:
Declarations: May include constant, type, variable and DLL procedure declarations.
Procedures: A sub function, or property procedure that contain pieces of code that can be
executed as a unit.

DATA TYPES
By default Visual Basic variables are of variant data types. 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 they can store.
The fundamental data types in Visual Basic including variant are integer, long, single,
double, string, currency, byte and boolean. A list of Visual Basic's simple data types are
given below.
1. Numeric

Type name Value range

Byte Store integer values in the range of 0 - 255

Integer Store integer values in the range of (-32,768) - (+ 32,767)

Store integer values in the range of (- 2,147,483,468) -


Long
(+ 2,147,483,468)

Single Store floating point value in the range of (-3.4x10-38) - (+ 3.4x1038)

Double Store large floating value which exceeding the single data type value

store monetary values. It supports 4 digits to the right of decimal


Currency
point and 15 digits to the left

2. String
Use to store alphanumeric values. A variable length string can store approximately 4 billion
characters

3. Date
Use to store date and time values. A variable declared as date type can store both date and
time values and it can store date values 01/01/0100 up to 12/31/9999

11
4. Boolean
Boolean data types hold either a true or false value. These are not stored as numeric values
and cannot be used as such. Values are internally stored as -1 (True) and 0 (False) and any
non-zero value is considered as true.

5. Variant
Stores any type of data and is the default Visual Basic data type. In Visual Basic if we declare
a variable without any data type by default the data type is assigned as default.

VARIABLES
Variables are the memory locations which are used to store 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 character like %, &, !, #, @ or $. Must not
be a reserved word (that is part of the code, like Option, for example). The different ways of
declaring variables in Visual Basic are listed below
 Explicit Declaration
 Using Option Explicit statement
 Scope of Variables

Explicit Declaration
Declaring a variable tells Visual Basic to reserve space in memory. It is not 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.. 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]
For example,
Dim strName As String
Dim intCounter As Integer

12
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, for example 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 = Intcount + 1
This calculation will result in intcount yielding a value of 1 as intcount would have
been initialized to zero. In Visual Basic, 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 all the variables. 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 section of each
module using the following steps.
 Click Options item in the Tools menu
 Click the Editor tab in the Options dialog box
 Check Require Variable Declaration option and then click the OK button
Scope of Variables
A variable is scoped to a procedure-level (local) or module-level variable depending
on how it is declared. The scope of a variable, procedure or object determines which part of
the code in our application is aware of the variable's existence.

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 statements as given below.
Dim sum As Integer
The local variables exist as long as the procedure in which they are declared, is
executing. Variables that are declared with keyword Dim exist only as long as the procedure
is being executed.

Static Variables
Static variables are not reinitialized each time Visual Invokes a procedure and
therefore retain or preserve value even when a procedure ends. In case we need to keep track
of the number of times a command button in an application is clicked, a static counter
13
variable has to be declared. These static variables are also ideal for making controls
alternately 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 a 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.
Example
The following is an example of an event procedure for a CommandButton that counts
and displays the number of clicks made.
Private Sub Command1_Click ( )
Static Counter As Integer
Counter = Counter + 1
Print Counter
End Sub
The first time we click the CommandButton, the Counter starts with its default value
of zero. Visual Basic then adds 1 to it and prints the result.

Module Level Variables


A module level variable is available to all the procedures in the module. They are
declared using the Public or the Private keyword.
public intpermanent As Integer
private intTemp As Integer
At the module level there is no difference between Dim and Private, but Private is
preferred because it makes the code easier to read. Public module-level variable that can be
accessed by all procedures in the module to share data and that also can be accessed from
outside the module. Public variables should not declared within a procedure. Public variables
in different modules can share the same name and they can be differentiated in code.

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 the local variable and references to R outside the
procedure would access the public variable.

14
1.6 PROCEDURES AND CONTROL STRUCTURES
Visual Basic offers different types of procedures to execute small sections of coding
in applications. 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. The benefits of using procedures in
programming are:
 It is easier to debug a program 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 Sub, Function or Property Procedure.

Sub Procedures
A sub procedure can be placed in standard, class and form modules. 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 | Public] [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 namely general procedures and
event procedures.

Event Procedures
An event procedure is a procedure block that contains the control's actual name, an
underscore(_), 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 declarations 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 statements in a separate
procedure (general procedure) and then call them in the event procedure.
15
In order to add General procedure
 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 an Add
Procedure dialog box as shown in the figure given below.
 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.
 Under Scope, Public is selected to create a procedure that can be invoked outside
the module, or Private to create a procedure that can be invoked only from within
the module.

Function Procedures

Functions are like sub procedures, except they return a value to the calling procedure.
They are especially useful for taking one or more pieces of data, called arguments and
performing some tasks with them. Then the function returns a value that indicates the results
of the tasks complete within the function.

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 kind of property
procedures-Property Let procedure that sets the value
of a property, Property Get procedure that returns the
value of a property, and Property Set procedure that
sets the references to an object.

16
CONTROL STRUCTURES
Control Statements are used to control the flow of program's execution. Visual Basic
supports control structures such as if... Then, if...Then ...Else, Select...Case, and Loop
structures such as Do While...Loop, While...Wend, For...Next etc method.
Branching Explanation Syntax Example
If...Then It performs an indicated If <condition> Then If average>75 Then
statement action only when the statement txtGrade.Text = "A"
condition is True; End If End If
otherwise the action is
skipped.

If...Then...Else It allows the programmer If <condition > Then If average>50 Then


statement to specify that a different statements txtGrade.Text = "Pass"
action is to be performed Else Else
when the condition is True statements txtGrade.Text = "Fail"
than when the condition is End If End If
False.

Nested This selection structures If < condition 1 > If average > 75 Then
If...Then...Else test for multiple cases by Then txtGrade.Text = "A"
statement placing If...Then...Else statements ElseIf average > 65 Then
Selection structures ElseIf < condition 2 > txtGrade.Text = "B"
inside If...Then...Else stru Then Else
ctures. statements txtGrade.Text = "F"
Else End If
Statements
End If

Select...Case It is executing multiple Select Case Index Dim average as Integer


statement blocks of statements. It is Case 0 average = txtAverage.Text
more convenient to use Statements Select Case average

17
than the If...Else...End If. Case 1 Case 100 To 75
Statements txtGrade.Text ="A"
End Select
Case 74 To 65
txtGrade.Text ="B"
Case Else
MsgBox "Invalid average
marks"
End Select

Looping Explanation Syntax Example


Do It is used to execute Do While<condition> Dim number As Integer
while...Loop statements until a certain Statements number = 1
Statement condition is met Loop Do While number <= 100
number = number + 1
Loop
While...end A While...Wend statement While<condition> Dim number As Integer
Statement behaves like Statements number = 1
Do while...Loop statement. Wend While number <=100
number = number + 1
Wend
Do... This statement first Do Dim number As Long
Loop While executes the statements and Statements number = 0
Statement then test the condition after LoopWhile<condition> Do
each execution. number = number + 1
Loop While number < 201

18
Do Statements in the body of Do Until<condition> Dim number As Long
Until...Loop a Do Until...Loop are Statements number=0
Statement executed repeatedly as long Loop Do Until number > 1000
as the loop-continuation test number = number + 1
evaluates to False. Print number
Loop

For...Next For...Next repetition For <condition> Dim x As Integer


Loop structure handles all the Statements For x = 1 To 50 Step 2
details of counter-controlled Next Print x
repetition. Next
Op: 1, 3, 5, 7..etc

Exit For The Exit For statement is For < condition > Dim x As Integer
statement executed and it terminates Statements For x = 1 To 10
the For...Next loop. If < condition > Print x
Then If x = 5 Then
Statements Print "The program exited at
Exit For x=5"
End If Exit For
Next End If
Next
Exit Do Do...While loop is Do While < Dim x As Integer
statement terminated using Exit Do condition > Do While x < 10
statement Statements Print x
If < condition > x=x+1
Then If x = 5 Then
Statements Print "The program is exited
Exit Do at x=5"
End If Exit Do
Loop End If
Loop

19
With...End Multiple properties can be With Text1
With set and multiple methods can .Font.Size = 14
statement be called by using .Font.Bold = True
the With...End .ForeColor = vbRed
With statement. .Height = 230
.Text = "Hello World"
End With

ARRAYS
 An array is a consecutive group of memory locations that all have the same name and
the same type.
 To refer to a particular location or element in the array, we specify the array name and
the array element position number.
 The Individual elements of an array are identified using an index.
 Arrays have upper and lower bounds and the elements have to lie within those
bounds.
 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.

Declaring arrays
Arrays may be declared as Public (in a code module), module or local. Module arrays are
declared in the general declarations using keyword Dim or Private. Local arrays are declared
in a procedure using Dim or Static. Array must be declared explicitly with keyword "As".
There are two types of arrays in Visual Basic namely:
Fixed-size array: The size of array always remains the same-size doesn't change
during the program execution.
Dynamic array: The size of the array can be changed at the run time- size changes
during the program execution.
Fixed-sized Arrays
When an upper bound is specified in the declaration, a Fixed-array is created. The
upper limit should always be within the range of long data type.
Declaring a fixed-array
Dim numbers(5) As Integer

20
In the above illustration, numbers is the name of the array, and the number 6 included
in the parentheses is the upper limit of the array. The above declaration creates an array with
6 elements, with index numbers running from 0 to 5.
If we want to specify the lower limit, then the parentheses should include both the
lower and upper limit along with the To keyword. An example for this is given below.
Dim numbers (1 To 6 ) As Integer
A public array can be declared using the keyword Public instead of Dim as shown
below.
Public numbers(5) As Integer

Multidimensional Arrays
 A common use of multidimensional arrays is to represent tables of values consisting
of information arranged in rows and columns.
 To identify a particular table element, we must specify two indexes: The first (by
convention) identifies the element's row and the second (by convention) identifies the
element's column.
 Note that multidimensional arrays can have more than two dimensions. Visual Basic
supports at least 60 array dimensions.
The following statement declares a two-dimensional array 50 by 50 array within a
procedure.
Dim AvgMarks ( 50, 50)
It is also possible to define the lower limits for one or both the dimensions as for fixed
size arrays. An example for this is given here.
Dim Marks ( 101 To 200, 1 To 100)
An example for three dimensional-array with defined lower limits is given below.
Dim Details( 101 To 200, 1 To 100, 1 To 100)

Static and Dynamic arrays


Static arrays must include a fixed number of items, and this number must be known at
compile time so that the compiler can set aside the necessary amount of memory. create a
static array using a Dim statement with a constant argument:
' This is a static array.
Dim Names(100) As String
Visual Basic starts indexing the array with 0. Therefore, the preceding array actually
holds 101 items.
21
Most programs don't use static arrays because programmers rarely know at compile time
how many items and also because static arrays can't be resized during execution. Both these
issues are solved by dynamic arrays. Declare and create dynamic arrays in two distinct steps.
 In general, declare the array to account for its visibility (for example, at the beginning
of a module if to make it visible by all the procedures of the module) using a Dim
command with an empty pair of brackets.
 Then create the array to use ReDim statement:
' An array defined in a BAS module (with Private scope)
Dim Customers() As String
...
Sub Main()
' Here create the array.
ReDim Customer(1000) As String
End Sub
If creating an array that's local to a procedure, do everything with a single ReDim statement:
Sub PrintReport()
' This array is visible only to the procedure.
ReDim Customers(1000) As String
' ...
End Sub

Arrays within UDTs(user defined data tytpe)


UDT structures can include both static and dynamic arrays. Here's a sample structure that
contains both types. A Type statement is used to define an user defined data type in the
general declaration section of a form or module.
Type MyUDT
StaticArr(100) As Long
DynamicArr() As Long
End Type

1.7 CREATING AND USING CONTROLS


 A control is an object that can be drawn on a Form object to enable or enhance user
interaction with an application.
 Controls have properties that define aspects their appearance, such as position, size
and colour, and aspects of their behavior, such as their response to the user input.
22
 For instance, a code could be written in a Command Button control's click event
procedure that would load a file or display a result.
 In addition to properties and events, methods can also be used to manipulate controls
from code.
 Most of the controls provide choices to users that can be in the form of 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 .EXE file and are always included in the ToolBox which cannot be removed.
 ActiveX controls exist as separate files with either .VBX or .OCX extension. They
include specialized controls such as;
1) MSChart control
2) The Communications control
3) The Animation control
4) The ListView control
5) An ImageList control
6) The Multimedia control
7) The Internet Transfer control
8) The WinSock control
9) The TreeView control
10) The SysInfo control
11) The Picture Clip control
Some of these objects support OLE Automation, which allow programming another
application's object from within Visual Basic application.

TabIndex Property of Controls


 It is to determine the control that would receive the focus next when a tab key is
pressed.
 Every time a tab key is pressed, Visual Basic looks at the value of the Tab Index for
the control that has focus and then it scans through the controls searching for the next
highest Tab Index number.

23
 By default, Visual Basic assigns a tab order to control as we draw the controls on the
Form, except for Menu, Timer, Data, Image, Line and Shape controls, which are not
included in tab order. Setting the Tab Index property of controls is compulsory in
development environment.

TEXTBOX CONTROL
A Text Box control, sometimes called an edit field or edit control, displays
information entered at design time.

Setting Properties to a TextBox


 Text can be entered into the text box by assigning the necessary string to the text
property of the control.
 If the user needs to display multiple lines of text in a TextBox, set the MultiLine
property to True.
 To customize the scroll bar combination on a TextBox, set the ScrollBars property.
 Scroll bars will always appear on the TextBox when it's MultiLine property is set to
True and its ScrollBars property is set to anything except None(0).
 If the user set the MultilIne property to True, set the alignment using the Alignment
property. The test is left-justified by default.
 If the MultiLine property is set to False, then setting the Alignment property has no
effect.

Run-Time Properties of a TextBox control


The Text property is the one of the reference most often in code, and conveniently it's the
default property for the TextBox control. Three other frequently used properties are these:
 The SelStart property sets or returns the starting point of selected text.
 The SelLength property returns the number of characters selected.
 The SelText property sets or returns thestring containing the currently selected text.
The selected text can be copied to the Clipboard by using SelText:
Clipboard.SelText text, [format]
In the above syntax, text is the text that has to be placed into the Clipboard, and
format has three possible values.
1. VbCFLink - conversation information
2. VbCFRTF - Rich Text Format
3. VbCFText - Text
24
We can get text from the clipboard using the GetText() function this way:
Clipboard.GetText ([format])
The following Figure summarizes the common TextBox control's properties and methods.

Property/ Method Description

Enabled Specifies whether user can interact with this control or not

Index Specifies the control array index

Specifies the maximum number of characters to be input. Default


MaxLength
value is set to 0 that means user can input any number of characters

Using this we can set the shape of the mouse pointer when over a
MousePointer
TextBox

Text Specifies the text to be displayed in the TextBox at runtime

GotFocus Action happens when the TextBox receives the active focus

LostFocus Action happens when the TextBox loses it focus

KeyDown Called when a key is pressed while the TextBox has the focus

KeyUp Called when a key is released while the TextBox has the focus

LABEL CONTROL
The Label control represents a standard Windows label. It is generally used to display
some informative text on the GUI which is not changed during runtime. Let's create
a label by dragging a Label control from the Toolbox and dropping it on the form.

Properties of the Label Control


The following are some of the commonly used properties of the Label control:

S.No Property Description

1 Autosize Gets or sets a value specifying if the control should be


automatically resized to display all its contents.

2 BorderStyle Gets or sets the border style for the control.

3 Font Gets or sets the font of the text displayed by the control.

4 FontHeight Gets or sets the height of the font of the control.

5 ForeColor Gets or sets the foreground color of the control.

6 Text Gets or sets the text associated with this control.

25
7 TextAlign Gets or sets the alignment of text in the label.

Command Button Controls


It is used to begin interrupt or end a process. If chosen, a command button appears
pushed in and so is sometimes called a push button.
eg:
Private Sub Command1_Click()
' Save data, then unload the current form.
Call SaveDataToDisk
Unload Me
End Sub

Properties of a Command Button control


 To display text on a CommandButton control, set its Caption property.
 An event can be activated by clicking on the CommandButton.
 To set the background colour of the CommandButton, select a colour in the
BackColor property.
 To set the text colour set the Forecolor property.
 Font for the CommandButton control can be selected using the Font property.
 To enable or disable the buttons set the Enabled property to True or False
 To make visible or invisible the buttons at run time, set the Visible property to True or
False.
 Tooltips can be added to a button by setting a text to the Tooltip property of the
Command Button.
 A button click event is handled whenever a command button is clicked. To add a click
event handler, double click the button at design time, which adds a subroutine like the
one given below.
Private Sub Command1_Click( )
..................
End Sub
Option Button Control
OptionButton controls are also known as radio buttons because of their shape. It provides a
set of choices from which a user can select only one button by
 Clicking it at run time.

26
 Assigning the value property to True in code like
Optional.value=true
 Using the shortcut keys specified in the Caption of a
label.
To disable the option button at run time, its Enabled property is
set to false.

LIST BOX
ListBox and ComboBox controls present a set of choices that are displayed vertically
in a column. If the number of items exceed the value that be displayed, scroll bars will
automatically appear on the control. These scroll bars can be scrolled up and down or left to
right through the list. The following Fig lists some of the common ComboBox properties and
methods.

Property/Method Description
Index Specifies the Control array index
String array. Contains the strings displayed in the drop-down
List
list. Starting array index is 0.
ListCount Integer. Contains the number of drop-down list items
Integer. Contains the index of the selected ComboBox item. If
ListIndex
an item is not selected, ListIndex is -1
Style Integer. Specifies the style of the ComboBox's appearance
Boolean. Specifies whether ComboBox receives the focus or
TabStop
not.
Text String. Specifies the selected item in the ComboBox

Adding items to a List


It is possible to populate the list at design time or run time
Design Time: To add items to a list at design time, click on List property in the
property box and then add the items. Press CTRL+ENTER after adding each item as
shown below.
Run Time: The AddItem method is used to add items to a list at run time. The
AddItem method uses the following syntax.
Object.AddItemitem, Index
The item argument is a string that represents the text to add to the list
The index argument is an integer that indicates where in the list to add the new item.
eg: Private Sub Form_Load()

27
Combo1.AddItem 1
Combo1.AddItem 2
Combo1.AddItem 3
Combo1.AddItem 4
Combo1.AddItem 5
Combo1.AddItem 6
End Sub

Removing Items from a List


The RemoveItem method is used to remove an item from a list. The syntax for this is
given below.
Object.RemoveItem index
The following code verifies that an item is selected in the list and then removes the
selected item from the list.
Private Sub cmdRemove_Click()
If List1.ListIndex > -1 Then
List1.RemoveItem List1. ListIndex
End If
End Sub
Sorting the List
The Sorted property is set to True to enable a list to appear in alphanumeric order and
False to display the list items in the order which they are added to the list.

Using the ComboBox


A ComboBox combines the features of a TextBox and a ListBox. This 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 that are represented as shown below.
 Dropdown Combo (style 0)
 Simple Combo (style 1)
 Dropdown List (style 2)

Dropdown Simple combo


Dropdown list
1. A simple combo box displays the combo
contents of its list all the time. The user

28
can select an item from the list or type an item in the edit box portion of the combo
box.
2. 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.
3. The Dropdown list combo box turns the combo
box into a Dropdown list box. At run time , the
control looks like the Dropdown combo box. The user could click the down arrow to
view the list.
4. The difference between Dropdown combo & Dropdown list combo is that the edit
area in the Dropdown list combo is disabled.
Example
This example is to Add , Remove, Clear the list of items and finally close the
application. Open a new Standard EXE project is opened an named the Form as Listbox.frm
and save the project as Listbox.vbp. Design the application as shown below.

Private Sub txtName_Change()


If (Len(txtName.Text) > 0) Then 'Enabling the Add button
'if atleast one character
'is entered
cmdAdd.Enabled = True
End If
End Sub
Private Sub cmdAdd_Click()
lstName.AddItem txtName.Text 'Add the entered the characters to the list box
txtName.Text = "" 'Clearing the text box
txtName.SetFocus 'Get the focus back to the
'text box
lblDisplay.Caption = lstName.ListCount 'Display the number of items in the list box
cmdAdd.Enabled = False ' Disabling the Add button
End Sub

29
The click event of the Add button adds the text to the list box that was typed in the
Text box. Then the text box is cleared and the focus is got to the text box. The number of
entered values will is increased according to the number of items added to the listbox.
Private Sub cmdClear_Click()
lstName.Clear
lblDisplay.Caption = lstName.ListCount
End Sub
Private Sub cmdExit_Click()
Unload Me
End Sub
Private Sub cmdRemove_Click()
Dim remove As Integer
remove = lstName.ListIndex 'Getting the index
If remove >= 0 Then 'make sure an item is selected
'in the list box
lstName.RemoveItem remove 'Remove item from the list box
lblDisplay.Caption = lstName.ListCount 'Display the number of items
'in the listbox
End If
End Sub

SCROLLBAR
 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.
 The Min and Max property represents the minimum and maximum value.
 The value property of the ScrollBar represents its current value, that may be any
integer between minimum and maximum values assigned.
 The HScrollBar and the VScrollBar controls are perfectly identical, apart from their
different orientation.
eg:
Private Sub Text1_GotFocus()
' Pass the focus to the scroll bar.
HScroll1.SetFocus
End Sub
Private Sub HScroll1_Change()
30
' Scroll bar controls the text box value.
Text1.Text = HScroll1.Value
End Sub

1.8 WORKING WITH CONTROL ARRAYS


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

Creating Controls at Design Time


 Assigning same name in the name property for more than one control
 Copying an existing control and then passing it on to the form. This can be done by
focusing the control and choosing the copy from edit menu and then choosing the
paste from the edit ,menu.
 Setting the index property to a value that is not null.
Creating Controls at Run Time
Control arrays can be created at run time using the statements
 Load object (Index %)
 Unload object (Index %)
Where object is the name of the control to add or delete 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 a
control array is loaded, most of the property settings are copied from the lowest existing
element in the array.
Following example illustrates the use of the control array.
* Open a Standard EXE project and save the Form as
Calculator.frm and save the Project as Calculater.vbp.
Dim Current As Double
Dim Previous As Double
Dim Choice As String
Dim Result As Double
The following code is entered in the cmd_Click( )
(Control Array) event procedure
Private Sub cmd_Click(Index As Integer)
txtDisplay.Text = txtDisplay.Text & cmd(Index).Caption
31
'&is the concatenation operator
Current = Val(txtDisplay.Text)
End Sub
The following code is entered in the cmdAC_Click ( ) event procedure
Private Sub cmdAC_Click()
Current = Previous = 0
txtDisplay.Text = ""
End Sub
The below code is entered in the cmdNeg_Click( ) procedure
Private Sub cmdNeg_Click()
Current = -Current
txtDisplay.Text = Current
End Sub
The following code is entered in the click events of the cmdPlus, cmdMinus, cmdMultiply,
cmdDevide controls respectively.
Private Sub cmdDevide_Click()
txtDisplay.Text = ""
Previous = Current
Current = 0
Choice = "/"
End Sub
Private Sub cmdMinus_Click()
txtDisplay.Text = ""
Previous = Current
Current = 0
Choice = "-"
End Sub
Private Sub cmdMultiply_Click()
txtDisplay.Text = ""
Previous = Current
Current = 0
Choice = "*"
End Sub
Private Sub cmdPlus_Click()
txtDisplay.Text = ""
32
Previous = Current
Current = 0
Choice = "+"
End Sub
To print the result on the text box, the following code is entered in the cmdEqual_Click ( )
event procedure.
Private Sub cmdEqual_Click()
Select Case Choice
Case "+"
Result = Previous + Current
txtDisplay.Text = Result
Case "-"
Result = Previous - Current
txtDisplay.Text = Result
Case "*"
Result = Previous * Current
txtDisplay.Text = Result
Case "/"
Result = Previous / Current
txtDisplay.Text = Result
End Select
Current = Result
End Sub
Save and run the project. On clicking digits of user's choice and an operator button, the
output appears.

33
UNIT II

2.1 MENUS
 Menus are intrinsic controls, and as such they deserve a place
in this chapter. On the other hand, menus behave differently
from other controls
 Visual Basic provides an easy way to create menus with the
modal Menu Editor dialog. The below dialog is displayed
when the Menu Editor is selected in the Tool Menu.
 Basically, each menu item has a Caption property (possibly with an embedded &
character to create an access key) and a Name. Each item also exposes three Boolean
properties, Enabled, Visible, and Checked, set both at design time and at run time.

MENU INTERFACE
Visual Basic 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 menu bar appears below the title bar and it may contain one or more menu titles.
An expanded Menu Editor window

An expanded menu

34
Checked: This is unchecked by default and allows the programmer the option of creating a
checked menu item( a menu item that act as a toggle and displays a check mark when
selected. The following is a Check Menu items.

Enabled: specifies whether a menu is disabled or not. If a disabled command in a menu that
means that feature is not available. The Visible checkbox specifies whether the menu is
visible or not.

Creating Menus
Open a new Project and save the form as
menu.frm and save the project as menu.vbp.
Choose Tools ››› Menu Editor and type the
menu items as shown below.

Caption Name

File mnuFile

Open mnuOpen

Save mnuSave

Exit mnuExit

Edit mnuEdit

Copy mnuCopy

Cut mnuCut

Paste mnuPaste

Menu Control Array


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,
indicate4d in the index property box on the menu editor.
Current Menu Structure is: After using Load (mnu(1)) Required menu structure

Mnu Mnu Mnu

---Mnu1 (with index=0) ---Mnu1 (with index=0) ---Mnu1 (with index=0)

35
-------Mnu1a -------Mnu1a -------Mnu1a

-------Mnu1b -------Mnu1b -------Mnu1b

---Mnu2 ---Mnu1 (with index=1) ---Mnu1 (with index=1)

---Mnu3 ---Mnu2 -------Mnu1a

---Mnu3 -------Mnu1b

---Mnu2

---Mnu3

2.2 MOUSE EVENTS


 Visual Basic responds to various mouse events, which are recognized by most of the
controls.
 The main events areMouseDown, MouseUp and MouseMove. MouseDown occurs
when the user presses any mouse button and MouseUp occurs when the user releases
any mouse button.
 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 in an integer called shift. The value of this argument indicates
whether the mouse button was clicked simultaneously with the Shift key, Ctrl key or
Alt key.
 The third and fourth arguments X and Y are the coordinates of the mouse location at
the time the mouse button was clicked. As the Form_MouseDown( ) is executed
automatically whenever the mouse button is clicked inside the Form's area the X, Y
co-ordinates are referenced to the form.

36
Positioning a control
Mouse Down is the commonly used event and it is combined with the move method
to move an Image control to different locations in a Form. The following application
illustrates the movement of objects responding to move events. It makes use of two Option
Button Controls, two image controls and a Command Button. The application is designed in
such a way that when an Option Button is selected, the corresponding image control is placed
anywhere in the form whenever it is clicked. Open a new standard EXE project and save the
Form as Move.frm and save the project as Move.vbp Design the Form as shown below.

Object Property Setting


Form Caption MouseDown
Name frmMouseDown
Credit card is
OptionButton Caption
selected
Name
optCredit
Value
True
OptionButton Caption Cash is selected
Name optCash
Image Name imgCredit
Picture c:/credit.jpg
Image Name imgCash
Picture c:/cash.jpg

The following code is entered in the general declarations 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)

37
If optCredit = True Then
imgCredit.Move X, Y
Else
imgCash.Move X, Y
End If
End Sub
Run the application by keying in F5. when the mouse is clicked on the form
somewhere, the selected image moves to that clicked location. This is shown in the below
figure.

Graphical Mouse Application


The mouse events can be combined with
graphics methods and any number of customized
drawing or paint applications can be created. The
following application combines MouseMove and
MouseDown events, and illustrates a drawing
program.
Open a new Standard EXE project and save
the Form as Draw.frm and save the Project as Draw.vbp. Name the caption of the as
Drawing. Add command button control and name the caption of it as Clear
Enter the following code in the Form_MouseDown ( ) procedure, Form_MouseMove ( )
procedure and cmdClear_Click ( ) procedures respectively.
Private Sub cmdClear_Click()
frmDraw.Cls
End Sub
Private Sub Form_MouseDown(Button As Integer, Shift As Integer, X As Single, Y
As Single)
frmDraw.CurrentX = X
frmDraw.CurrentY = Y
End Sub
Private Sub Form_MouseMove(Button As Integer, Shift As Integer, X As Single, Y
As Single)
If Button = 1 Then
Line (frmDraw.CurrentX, frmDraw.CurrentY)-(X, Y)

38
End If
End Sub
Button value 1 indicates that the left
mouse button is clicked. The code written in the
Mouse Down event changes the Current X and
Current Y to the coordinates where the mouse
button was just clicked.
Run the application. The mouse is
clicked and moved in the Form a line is drawn
corresponding to the mouse movement.
Following figure illustrates the combined action of Mouse Down and Mouse Move.
The program uses two graphics related Visual Basic concepts, the Line method and
the CurrentX and CurrentY properties. Line method is preferred to draw a line in a Form. The
following statement draws a line from the coordinates
X = 2500, Y = 2000, X = 5000, Y = 5500
Line (2500, 2000) - (5000, 5500)

Mouse Move application


Visual Basic does not generate a Mouse Move 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 ( ) event
is executed.
Open a new standard EXE project and save the form as MouseMove.frm and save the
Project as MouseMOve.vbp. Place a Command Button control and name the caption as Clear
and set the name as cmdClear. The following code is entered in the cmdClear_Click (
) and Form_MouseMove ( ) events respectively.
Private Sub cmdClear_Click()
frmMouseMove.Cls
End Sub
Private Sub Form_MouseMove(Button As Integer, Shift As Integer, X As Single, Y
As Single)
Circle (X, Y), 70
End Sub

39
The above procedure simply draws small circles at the mouse's current location using
the Circle method. The parameter x, y represent the centre of the circle, and the second
parameter represent the radius of the circle.

DRAGGING AND DROPING


In computer graphical user interface drag & drop is the action of clicking on an object
(virtual object on screen) and dragging it to a different location (on screen) as required. The
basic sequence involved in drag & drop is
 Press & hold down, the button on the mouse or other pointing device to “grab” the
object.
 “Drag” the object /cursor/ pointing device to the desired location
 “Drop” the object by releasing the button
The drag-n-drop is programmatically done and it is widely used in creating objective
type questions. Both VB6 and VB.NET support a rich variety of drag drop functions as
detailed in the following three examples.
Example:
An example of a simple drag and drop sequence is given below. Fig1 contains two
columns: First column contains animal names, and the second column contains small boxes
where user needs to drop the relevant images.
Animal Name Boxes where relevant images are dropped

Fig 1. Images before being dragged to the target


Fig 2. Gives after the images being dragged and dropped to the correct places.
40
Fig 2. Images after being dragged to the target

Properties of Drag & Drop


Controls have two properties that are related to drag-and-drop:
 DragMode. Set to vbManual (value = 0, the default) for manual drag-and-drop, which
requires use of the Drag method to initiate a drag-and-drop operation.
 DragIcon. Specifies the mouse pointer that is displayed while the control is being
dragged. The default setting displays an arrow with a rectangle.
 Drag method starts or stops manual dragging.

2.3 DIALOG BOXES


A dialog boxes is used to exchange information between the program and the user. It
is a separate form that is generally accessed in response to a selection from a menu or a list.
Dialog boxes typically contain common controls ( e.g., labels, text boxes, option buttons,
check boxes, and command buttons) to enter or display information.
The dialog box features must be accessible from other forms and the information
entered into the dialog box by the user must be recognizable within these forms.

Creating Dialog Boxes


 Predefined Dialog Boxes--Created using InputBox () and MsgBox() function.
 CommonDialog Control--Created by adding controls to the form or by customizing
an existing dialog box.

41
Modal and Modeless dialog boxes
Modal dialog box is the dialog box in which user response is required before
continuing with the program. The Paragraph dialog box of WordPad is a good example of it
when it is displaying, the user cannot use any other part of WordPad unless he or she closes
this object first.
Modeless dialog box is the dialog box in which the screen remain stable and available
to all the user for use at any time but it doesn’t stop there and allow other user work to be
carried out without any interference. For example The Find dialog box of WordPad.

Predefined Dialog Boxes(InputBox())


Displays a prompt in a dialog box, waits for the user to input text or click a button,
and returns a String containing the contents of the text box.

Following is an expanded InputBox

Syntax :
memory_variable = InputBox (prompt[,title][,default])
memory_variable is a variant data type but typically it is declared as string, which accept the
message input by the users. The arguments are explained as follows:
 Prompt - String expression displayed as the message in the dialog box. If prompt
consists of more than one line, separate the lines using the vbCrLf constant
 Title - String expression displayed in the title bar of the dialog box. If omit the title,
the application name is displayed in the title bar
 default-text - The default text that appears in the input field where users can use it as
his intended input or he may change to the message he wish to key in.
 x-position and y-position - the position or the coordinate of the input box.

42
Following is an expanded MessageBox

Syntax :
MsgBox ( Prompt [,icons+buttons ] [,title ] )
memory_variable = MsgBox ( prompt [, icons+ buttons] [,title] )
 Prompt : String expressions displayed as the message in the dialog box. If prompt
consist of more than one line, separate the lines using the vbrCrLf constant.
 Icons + Buttons : Numeric expression that is the sum of values specifying the
number and type of buttons and icon to display.
 Title : String expression displayed in the title bar of the dialog box. If omit title, the
application name is placed in the title bar.
Icons

Constant Value Description


vbCritical 16 Display Critical message icon
vbQuestion 32 Display Warning Query icon
Display Warning message
vbExclamation 48
icon
vbInformation 64 Display information icon

Buttons
Constant Value Description
vbOkOnly 0 Display OK button only
Display OK and Cancel
vbOkCancel 1
buttons
Display Abort, Retry and
vbAbortRetryIgnore 2
Ignore buttons
Display Yes, No and Cancel
vbYesNoCancel 3
buttons
vbYesNo 4 Display Yes and No buttons
Display Retry and Cancel
vbRetryCancel 5
buttons

43
Return Values
Constant Value Description
vbOk 1 Ok Button
vbCancel 2 Cancel Button
vbAbort 3 Abort Button
vbRetry 4 Retry Button
vbIgnore 5 Ignore Button
vbYes 6 Yes Button
vbNo 7 No Button

Custom Dialog Control


Use the following procedure to create a custom dialog box:
1. Create a UserForm
On the Insert menu in the Visual Basic Editor, click UserForm.
2. Add controls to the UserForm
Find the control to add in the Toolbox and drag the control onto the form.
3. Set control properties
Right-click a control in design mode and click Properties to display
the Properties window.
4. Initialize the controls
Initialize controls in a procedure before it shows a form, or it can add code to
the Initialize event of the form.
5. Write event procedures
All controls have a predefined set of events. For example, a command button has
a Click event that occurs when the user clicks the command button. Write event
procedures that run when the events occur.
6. Show the dialog box
Use the Showmethod to display a UserForm.
7. Use control values while code is running
Some properties can be set at run time. Values the user sets for controls in the dialog
box are lost when the dialog box is closed.
Common Dialog Control
 The Common Dialog control provides a standard set of dialog boxes for operations
such as opening, saving, and printing files, as well as selecting colors and fonts and
displaying help.

44
 Any six of the different dialog boxes can be displayed with just one Common Dialog
control.
 A particular dialog box is displayed by using one of the six "Show..." methods of the
Common Dialog control:
ShowOpen, ShowSave, ShowPrinter, ShowColor, ShowFont, or ShowHelp.

The Components Dialog Box Common Dialog


Control Added to
Toolbox

The sample program for this topic will be presented shortly, but first, two properties
of the Common Dialog control, Flags and CancelError, will be discussed briefly.
2.4 MDI
 The Multiple Document Interface (MDI) was designed to simplify the exchange of
information among documents, all under the same roof.
 With the main application, maintain multiple open windows, but not multiple copies
of the application.
 Data exchange is easier when user can view and compare many documents
simultaneously

45
 Each document is displayed in its own window, and all document windows have the
same behavior.
 The main Form, or MDI Form,
isn't duplicated, but it acts as a
container for all the windows, and
it is called the parent window.
 The windows in which the
individual documents are
displayed are called Child
windows.
To create an MDI application, follow these steps:
1. Start a new project and then choose Project >>> Add MDI Form to add the parent
Form.
2. Set the Form's caption to MDI Window
3. Choose Project >>> Add Form to add a SDI Form.
4. Make this Form as child of MDI Form by setting the MDI Child property of the SDI
Form to True. Set the caption property to MDI Child window.
Visual Basic automatically associates this new Form with the parent Form. This child
Form can't exist outside the parent Form; in the words, it can only be opened within the
parent Form.
Parent and Child Menus
 MDI Form cannot contain objects other than child Forms, but MDI Forms can have
their own menus.
 However, because most of the operations of the application have meaning only if
there is at least one child Form open, there's a peculiarity about the MDI Forms.
 The MDI Form usually has a menu with two commands to load a new child Form and
to quit the application.
 The child Form can have any number of commands in its menu, according to the
application. When the child Form is loaded, the child Form's menu replaces the
original menu on the MDI Form
Following example illustrates the above explanation.
* Open a new Project and name the Form as Menu.frm and save the Project as Menu.vbp
* Design a menu that has the following structure.
<> MDIMenu Menu caption
 MDIOpen opens a new child Form
46
 MDIExit terminates the application
* Then design the following menu for the child Form
<> ChildMenu Menu caption
 Child Open opens a new child Form
 Child Save saves the document in the active child Form
 Child Close Closes the active child Form
 At design time double click on MDI Open and add the following code in the click
event of the open menu.Form1.Show
 And so double click on MDI Exit and add the following code in the click event End
 Double click on Child Close and enter the following code in the click event Unload
Me
 Before run the application in the project properties set MDI Form as the start-up
Form. Save and run the application. Following output will be displayed.

47
Unit – III

3.1. History of Open Database Connectivity


ODBC was created by SQL Access Group and first released in September 1992.
Although Microsoft Windows was the first to provide an ODBC product, versions exist
for UNIX, OS/2 and Macintosh platforms as well. Open Database Connectivity (ODBC) is
an open standard application programming interface (API) that allows application
programmers to access any database. The main proponent and supplier of ODBC
programming support is Microsoft, but ODBC is based on and closely aligned with The Open
Group standard Structured Query Language (SQL) Call-Level Interface (CLI). The Open
Group is sponsored by many major vendors, including Oracle, IBM and Hewlett Packard
Enterprise, and this consortium develops and manufactures The Open Group Architecture
Framework (TOGAF). In addition to CLI specifications from The Open Group, ODBC also
aligns with the ISO/IEC for database APIs.

How ODBC works


ODBC consists of four components, working together to enable functions. ODBC
allows programs to use SQL requests that access databases without knowing the proprietary
interfaces to the databases. ODBC handles the SQL request and converts it into a request
each database system understands.

The four different components of ODBC are:


 Application: Processes and calls the ODBC functions and submits the SQL
statements;
 Driver manager: Loads drivers for each application;
 Driver: Handles ODBC function calls, and then submits each SQL request to a data
source; and
 Data source: The data being accessed and its database management system (DBMS)
OS.
 OBDC can also work with MySQL when its driver is called MyODBC. Sometimes,
this is referred to as the MySQL Connecter/ODBC.

48
JDBC vs. ODBC
The Java Database Connectivity (JDBC) API uses the Java programming language to
access a database. When writing programs in the Java language using JDBC APIs, users can
employ software that includes a JDBC-ODBC Bridge to access ODBC-supported databases.

The JDBC-ODBC Bridge (or JDBC type 1 driver) should be viewed as a transitional
approach, as it creates performance overhead because API calls must pass through the JDBC
bridge to the ODBC driver, then to the native database connectivity interface. In addition, it
was removed in Java Development Kit (JDK) 8, and Oracle does not support the JDBC-
ODBC Bridge. The use of JDBC drivers provided by database vendors, rather than the
JDBC-ODBC Bridge, is the recommended approach.

How Does ODBC Function?


Each database vendor provides a program called as ODBC driver, which takes
standard ODBC calls and translates them into the language the database can understand. So
the application uses ODBC calls (called as ODBC API) either directly or indirectly (for
example RDOs calling required ODBC calls) to access the database. And these ODBC calls
are translated by ODBC driver of the specific database to the required native language.
49
The program uses the same ODBC calls irrespective of the database it is accessing
and the ODBC driver takes care of converting the standard calls to the native calls.
ODBC driver manager which is a part of Windows OS loads the required ODBC driver and
passes the calls to driver and takes results from driver and pass the result to Application.
ODBC driver manager comes to know about the driver to be used and the database to be
accessed through using Data source name (DSN) used by the application program.

Data Source Name


An ODBC data source is accessed using DSN. Data source name is a name that
identifies the following:
 The name of the database to be used
 The type of the database and the ODBC driver to be used to access the
database
DSN is created using ODBC Data Source Administrator, which is a program supplied
by Windows OS. It is available in Control panel. When an application intends to access
ODBC data source, it will create ODBC data source name (DSN) and accesses database
through DSN.
Process
1 Application sends ODBC calls to ODBC Driver Manager
2 ODBC Driver Manger sends ODBC calls to the appropriate ODBC Driver
3 ODBC Driver converts ODBC calls to the native calls and accesses the database.

Accessing Oracle Database using ODBC


Accessing Oracle Database using ODBC use either DAOs or RDOs, but when it
comes to accessing ODBC data source, RDO is the obvious choice.
Steps
1. Makes sure Oracle is installed in the system and it is up and running.
2. Makes sure the system contains ODBC driver for Oracle. This can be done with
ODBC Data Source Administrator.
3. Create a DSN for Oracle database. Use ODBC Data Source Administrator.
4. Use DSN in Visual Basic application to access Oracle database.

To create DSN to access Oracle


1. Start ODBC data source administrator by running ODBC (32 Bit) program from
Control Panel of Windows OS.
50
2. Select Driver tab and check whether it have ODBC driver for Oracle. It may have the
name “Microsoft ODBC for Oracle”.
3. Select User DSN tab and click on Add button.
4. Create New Data Source, the dialog is displayed, select Microsoft ODBC for Oracle
(or some other driver meant for Oracle) and click on Finish button
5. In Microsoft ODBC for Oracle setup dialog enter Oracle as Data Source Name,
Oracle 10 database as Description.
6. If user selects Personal Oracle, leave remaining entries as blank. If user are using
Oracle Server (Client/Server Oracle) then enter Oracle service name (enter as Host
String in Sql*plus) as Server.
7. Click on Ok.

Remote Data Control to access Oracle


To access EMP table of user Scott in Oracle database.
1. Create a new project of Standard Exe type
2. Select Project -> Components and select Microsoft Remote Data Control 6.0 to load it
into project.
3. Place remote data control on the form.
4. Change the following properties of Remote data control
Property Value
Data Source Name Oracle
User Name Scott
Password Tiger
Prompt rdDriver NoPrompt
Caption EMP Table From Oracle
SQL Select Empno, Ename from Emp;
SQL property of Remote data control identifies the SQL command that is to be
executed.
5. Place two labels and two text boxes
6. Change the following properties of these controls.
Control Property Value
Label1 Caption Employee Number
Label2 Caption Employee Name
Text1 Data Source MSRDC1
DataField Empno
51
Text2 DataSource MSRDC1
Data Field Ename
Form Caption Details of Employees
7. Run the project using F5.
8. The form at run time should match the form
First row of EMP table displaying through Remote Data Control.

Remote Data Objects to Access ODBC Data Source


To use Remote Data Control to access data in Oracle database through ODBC
interface. To access ODBC data source using RDOs, follow the steps given below:
 Establish a connection using Connection object
 Create a Result Set using Connection object
 Manipulate the Result Set created in step 2.
 User starts the application it prompts the user to enter DSN, username and
password.
 If a valid connection is established then it will display the main form from
where user can enter any query and get the result displayed on the form.
 It is also possible to execute commands other than Select. In this case the
status of the executed command will be displayed.

3.2. DATA ACCESS


Visual Basic has become an application development tool used for developing
Client/Server applications. Visual Basic 6.0 has introduced a new way of accessing data
through ADO & OLEDB.

Data Access Options


Data Access Objects
This is an object model that has a collection of objects using which user can access a
database. This model gives complete control on the database. This model uses Jet Engine,
which is the native database engine used by Visual Basic and MS-Access. This was the first
model to be used in Visual Basic. Though it is possible to access any database using this, it is
particularly suitable for MS-Access database and not suitable for ODBC data sources such as
Oracle and MS-SQL Server.

52
Remote Data Objects (RDO)
These objects are only used to access ODBC data sources such as Oracle. These
objects access databases that are on remote machine (database server). This object model has
less number of objects compared with DAO and more suitable for accessing remote
databases.

ActiveX Data Objects (ADO)


Microsoft has introduced a new object model called ActiveX Data Objects (ADO),
which is based on ActiveX technology, for the first time in Visual Basic 6.0. This object
model has very few objects and it is based on OLE DB interface. OLE DB interface is a new
interface (replacing ODBC and others), through the user can access data of all formats in the
same manner. ADO uses OLE DB providers to access the data. That means each database is
accessed through OLE DB provider. And ADO provides the programming framework to
access OLE DB.

Accessing Ms-Access Database


To access data using a very simple and old method – using data control. Data control
is one of the standard controls used to provide access to data. Data control internally uses
DAO to access data. Accessing BIBLIO.MDB using data control: To access the data of
AUTHORS table of BIBLIO.MDB:
1. Place Data Control on the form.
2. Invoke properties window and select Database Name property and click on three dots
displayed on the right of the property.
3. Visual Basic invokes Database Name Dialog Box. Select BIBLIO.MDB file using the
dialog box. The file is normally placed in D:\Program Files\Microsoft Visual
Studio\VB98\BIBLIO.MDB. However, the exact path of this file may be different on
the system.
4. The complete path of the file is placed in Properties windows.
5. Select Record Source property and click on down arrow to the right of the property.
6. Visual Basic displays the list of tables from the selected database – BIBLIO.MDB.
7. Select AUTHORS table from the list of tables.
8. Change Caption property to “Author Details”

53
Properties of Data control
Following are important properties of data control.
S.No Properties Explanation
1 Database name Contains the name of the database that is to be
accessed.
2 Record source Contains the name of the table that is to be accessed. It
may also contain SELECT command.
3 Read only If set to true, doesn’t allow the data to be updated.
4 Exclusive If set to true, doesn’t allow any other application to
open the database until user close the database.
5 BOF Action Specifies the action data control takes when BOF
property of the underlying record set is true.
6 EOF Action Specifies the action data control takes when EOF
property of the underlying record set is true.
7 Connect Specifies the type of database accessed.
8 Default Cursor Type Specifies the type of cursor driver used by data control.
Applicable only when ODBC Direct is used.
9 Default Type Specifies whether Jet Engine is to be used or ODBC
Direct is to be used.
10 Record set Type Specifies the type of record set to be used.

Methods of Data Control


S.No Methods Explanation
Recreates the underlying record set with current Database
1 Refresh
name, Record source and other related properties
Updates the data bound controls by taking data from
2 Update Control
current record of the record set.
Saves the current data of bound controls to data. This
3 Update Record
method doesn’t cause Validate event.

Events occur in data control


Reposition
Occurs each time data control moves to a different record in the underlying record set.
This event occurs after the new record becomes the current record.

54
Properties and Methods of Record Set object
Record Set object contains the set of records retrieved from database.
S.No Properties Explanation
1 EOF EOF Returns true if record pointer reaches end of record set. End of
record set mark is the position that is after the last record of the
record set .
2 BOF Returns true if record pointer reaches beginning of the record set.
The position before the first record is called as beginning of the
record set.
3 Absolute Returns or sets the relative record number of the record set object’s
Position current record.
4 Sets or returns a bookmark that uniquely identifies the current
Book record in a Record Set object.
Mark
5 Edit Mode Returns the editing state of the record set. The valid options are
none, editing in progress and addition is in progress.
6 Filter Contains the condition that is to be used to filter records when
record set is subsequently reopened using Open Record Set method.
7 Last Returns the bookmarks of the most recently edited or added record.
Modified
8 Lock Edit Specifies whether optimistic lock (where records are locked when
user used Edit method) is to be used or pessimistic locking (where
records are locked only when Update method is used). Setting it to
true chooses pessimistic lock and setting it to false choose optimistic
lock.
9 No Match Returns true if one of the most recently used Find methods (Find
first, Find next, Find Last, Find Previous) or Seek method failed.
10 Record Returns the number of records accessed in the record set. If the
Count record set is of Table-type record set then returns the number of
records in the record set. To get accurate count, prior to using this
use Move Last method.
11 Sort Contains the order in which records are to be arranged if record set
is reopened.

55
Methods of Record Set Object
S.No Properties Explanation
1 Add New Adds a new record at the end of the record set.
Cancels any pending updates that were made after Edit or Add
2 Cancel Update
New methods but before Update method.
3 Close Closes record set.
4 Delete Deletes the current record in the record set.
5 Edit Makes the current record ready for editing.
Searches for the given criteria from the beginning of the record
6 Find First
set.
Searches for the given criteria from the current record of the
7 Find Next
record set.
Searches for the given criteria from the end of the record set in
8 Find Last
backward direction.
Searches for the given criteria from the current record of the
9 Find Previous
record set in backward direction.
Moves the record pointer in the record set by the given number
10 Move
of records. The movement is relative to the current record.
11 Move First Moves to first record.
12 Move Next Moves to next record.
13 Move Last Moves to last record.
14 Move Previous Moves to previous record
Open Record Opens a record set with the information given, such as source
15
Set and type of record set.
Updates the record set by re executing the query on which the
16 Requery
record set is based.
Used to search for a value in the current index. Applicable only
17 Seek for record sets of type table-type and an index is defined for the
underlying table.
Makes the changes made to underlying tables permanent
18 Update

56
Displaying data using Data bound controls
Data bound controls are controls that are bound to columns of a table via data control.
Data bound controls are used to display and modify the data of the database. For instance, a
text box could be used to display and change the data of the corresponding column in the
table. Data bound controls have Data Source and Data Field properties that allow
programmer to bind them to database.

3.3. WHAT IS ACTIVEX?


ActiveX is a new technology (actually a renamed technology). Its predecessor is
OLE; ActiveX allows user to create components based on COM specifications and enables
the user to develop interactive web pages. ActiveX includes both client and server side
technologies. That means it allows creating components that run both on client and server.
An ActiveX component is a reusable piece of data and code (object) created using
ActiveX technology. The best part of ActiveX is it allows user to create components that can
be used in any project (irrespective of language) straight away. This saves a lot of
development time.

Characteristics of ActiveX
 Reusability
 Interoperability means only compiled components are reusable and NOT source code.
ActiveX Components
ActiveX Applications (ActiveX .EXE)
An ActiveX application is a standalone application, such as MS-Word, MS-Excel etc.
These applications provide objects that can access and manipulate programmatically from
an application written in Visual Basic or any application development tool that supports
ActiveX.
Note: Each component has a collection of properties, methods and events that can be
accessed from outside. These properties, methods and events are collectively called as
interface of the component.

ActiveX Code Components (ActiveX .DLL)(Dynamic Link Library)


ActiveX code component is a collection (library) of programmable objects, where
objects are generally related to a specific topic such as, financial functions, date and time
functions etc.
57
ActiveX code components do not run as separate applications; instead they are run in
the same process area as the client (the application that is using the code component).

In-Process and Out-of-Process Servers


An ActiveX code component may be either in-process or out-of-process. In-process
server is implemented as .DLL and out-of-process server is implemented as .EXE. An
application using ActiveX component interacts with it using Client/Server architecture.
Application makes the request to the component and component responds to the request.
Here client is the application that is using the services of the component. And the ActiveX
component is the server. Depending upon where server runs, ActiveX components are
classified into two types.

In-Process Server
An in-process server is an ActiveX .DLL. It runs in the address space of the client
application. It cannot be run as a separate process. The communication between client
(application) and server (code component) will be faster as both of them (client & server)
reside in the same address space. And more importantly there is no context switch
(switching from one process to another). An example for in-process server is ActiveX Data
Objects library.

Out-of-Process Server
An ActiveX code component that is implemented as .EXE is an out-of-process server.
It runs in its own address space. When a client invokes a method of the server, control
switches from client process to server process (context switch occurs). An out-of-process
application can also be run as a standalone application.

Difference
An ActiveX DLL's code is executed within the main program's address space. It
behaves as if the class was created within the main program's code. Because the code lies
inside the program's address space, calling methods is very fast.
An ActiveX EXE's code is run in a separate process. The main program calls an
ActiveX EXE's method, the system marshals’ the call to translate the parameters into the
ActiveX EXE's address space, calls the method, translates the results back into the main
program's address space, and returns the result. This is slower than running an ActiveX
DLL's method inside the main program's address space.
58
Because of the difference in speed, an ActiveX DLL is almost always preferable. The
reason ActiveX EXEs are useful is they can run on a different computer than the main
program while an ActiveX DLL must run on the same computer as the main program. The
EXE can sit on a central computer and work directly with that computer's resources.

Making an ActiveX DLL/EXE Project


Start a new project and select ActiveX EXE or ActiveX DLL. Initially the project is
named Project1 and contains a class named Class1. Change these to meaningful names. The
model Microsoft has in mind is a DLL/EXE contains several related classes that each
performs related functions. For example, a DLL might contain billing system classes named
Customer, Product, and Sales Person. The Customer class would contain methods for
manipulating customer data. Change the project name to Billing Objects. Change Class1's
name to Customer and add two more classes named Product and Sales Person.

Instancing
Set the classes' Instancing properties to determine how the object can be created.

Private
Code outside the DLL/EXE cannot create this object type. Other classes in the
DLL/EXE can use this type of class as a helper but the main program cannot use it.

Public Not Creatable


The main program can use this type of class but cannot create new instances using the
New keyword or with Create Object. In this case, user needs to provide some method within
the other classes to create the new object and return it to the main program.

Single Use
The main program can create the object. Every time create a new object, the system
makes a new ActiveX EXE. Among other things, if the EXE contains global variables then
different objects are creating get different copies of the variables. This option is allowed for
ActiveX EXEs only.

Global Single Use


Similar to Single Use except it can invoke the properties and methods of the class as if
they were simple global functions. This option is allowed for ActiveX EXEs only.
59
Multi Use
The main program can create the object. When it does, the system makes an ActiveX
DLL/EXE component to handle the object. If make other objects, the system uses the same
ActiveX DLL/EXE component to handle them. The user are building a DLL or EXE and If it
is an EXE is running on different computers.
In building of ActiveX DLL, all programs run the DLL code in their own address
spaces. That means different objects created in the same program share the same component
server so they could share global variables defined in the DLL. If the objects are all freed at
the same time, the component server shut down so any global values are lost.
The code in the Shared DLL directory available for download demonstrates this kind
of sharing. The Billing Objects, vbp project contains the project named Billing Objects. This
project holds a BAS module holding a public variable named g_TheNumber. This variable is
visible to other code in the project but not to a main program using the DLL.
The Billing Objects project also contains a Multi Use class named Customer. This
class has Property Let and Property Get procedures that set and get the value of
g_TheNumber. The main program uses two Customer objects like this:
Private m_Customer1 As Object
Private m_Customer2 As Object
Private Sub Form_Load()
Set m_Customer1 = _
CreateObject("BillingObjects.Customer")
Set m_Customer2 = _
CreateObject("BillingObjects.Customer")
End Sub

Private Sub cmdGet_Click()


txtTheNumber.Text = m_Customer1.TheNumber
End Sub

Private Sub cmdSet_Click()


m_Customer1.TheNumber = CInt(txtTheNumber.Text)
txtTheNumber.Text = ""
End Sub
This code simply uses the TheNumber procedures as if they were globally declared.
When the program invokes one of the methods using this global syntax, it creates an instance
60
of the class to use its methods. It continues to use that instance whenever it needs to execute a
global method.

Test Projects
After creating ActiveX DLL project, add a test application. Open the File menu, select
Add Project, and add a Standard EXE. That project can act as the main program to test the
DLL. After the DLL code working, compile it into a DLL file. Then create independent
applications to use it.

Binding
Bind the DLL or EXE either at runtime (late binding) or at design time (early
binding). It is also faster than late binding.

Early Binding
To use early binding, load the main program, open the Project menu, and select
References. Find DLL in the list and select it. If the DLL project's name is Billing Objects,
then look for an entry named Billing Objects. If the project in different locations, it appears as
more than one entry. Click on one and look at the location displayed near the bottom of the
dialog. After that click the Browse button and find the DLL and then selected the DLL, click
OK. Now the program can explicitly refer to the classes in the DLL. For example, it could
declare and create a Customer object like this:
Dim customer1 As Customer
Set customer1 = New Customer

Class does not support Automation or does not support expected interface.
To fix this, load the main program, open the Project menu, and select References.
Deselect the DLL and click OK. Then open the References dialog again and reselect the
DLL.
Type mismatch: To fix this, recompile the main program.

Late Binding
To use late binding, declare references to DLL objects to have type Object. Then use
the Create Object statement to instantiate the objects like this:
Dim customer1 As Object
Set customer1 = CreateObject("BillingObjects.Customer")
61
This code creates an instance of the Customers class that is defined by the DLL
project named Billing Objects. After this the program can use the Public properties and
methods of the customer1 object just as if it had declared it using early binding.

3.4. CREATING AN ACTIVEX EXE


Creating ActiveX EXE and its components like code module and form.
1. Create a new project using File -> New Project and select ActiveX EXE as project type.
2. Visual Basic creates a project with just one class module named Class1.
3. Invoke Project Properties and click on right button.
4. Select Add -> Class Module from popup menu.
5. In Add Class Module dialog select Existing tab and select TIME.CLS.
6. Click right button on Class1 and select Remove Class1 from popup menu. Its prompted to
user to save it or not, that time user select No.
7. Add a form using Project -> Add Form and select a simple form from Add Form dialog
box.
8. Add a code module using Project -> Add Module and click on Open in Add Module dialog
box.
9. Change the following properties of the project.
Project name AEXETIMESERVER
Project Description Time class in Out-of-process server by AVP
Startup object Sub Main
10. Create a procedure with the name Main in code module and write the following code.
Public Sub Main()
If App.StartMode = vbSModeStandalone Then
frmTime.Show
End If
End Sub
Code for Main procedure of code module.
App object is one of the system objects. If Start Mode property contains vbSmode
Standalone, it means ActiveX EXE is run as standalone program. The other option is
vbSmode Automation.
13. Invoke Form designer and place a label and a timer control on the form.
14. Change the following properties of the form and controls.
Object Property Value
Form Name FrmTime
62
Caption ActiveX EXE Server
Label1 Name Lbltime
Caption 00:00:00
Autosize True
Fontsize 14
Borderstyle 1-Fixed Single
Timer1 Interval 1000
15. Write the following code for frmTime form.
General/Declarations
Dim t As New Time
Private Sub Form_Load()
Timer1_Timer
End Sub
Private Sub Timer1_Timer()
t.SetToCurrent
lblTime.Caption = t.GetTime
End Sub
Code in Form.
16. Save the project and its component under the following names (assign different names
also).
Project aexetimerserver.vbp
Form frmtime.frm
Module aexemodule.bas
Class Module aexetime.cls
Time class is taken from previous project. If we make any changes to time class and
save them, the changes will be saved under Time.cls and this might affect the previous
project (timerserer).

To save time.cls under a different name:


1. Select Time class in project explorer and click on right mouse button.
2. Select Save Time.Cls As option from popup menu and enter AEXETIME as the name
of the new file.
3. Time class is now stored under a new name - AEXETIME.CLS. It doesn’t affect
TIME.CLS and previous project continues to use TIME.CLS.

63
Creating .EXE file
1. Select File menu and choose Make aexetimeserver.exe option.
2. Visual Basic creates aexetimeserver.exe in the specified directory and also registers it
in system registry.
Running ActiveX Server as Standalone application
Let us run aexetimerserver.exe as a standalone application. In this case it should
display frmTime, which contains running digital clock.

To run ActiveX exe server as standalone application


1. Click on Start button on Taskbar
2. Select Run option from the start menu
3. Click on Browse button in Run window and select a exetimerserver.exe. (Folder name
different)
4. Running a exetimerserver.exe using Start->Run.
5. After selecting the file click on Ok to run the program.
6. A small window (frmTime) is displayed with running digital clock

Running client application


The same client program that used for ActiveX DLL. But client application should
have a reference to ActiveX EXE. So open client application (timetest.vbp) and follow the
steps given below.
To create a reference to ActiveX EXE
1. Select Project -> References
2. Uncheck Time class by AVP
3. Check Time class in Out-of-process server by AVP.
4. Click on Ok.

3.5. Creating an ActiveX DLL


 Create a project of ActiveX DLL type
 Create as many class modules as required.
 Change properties of project
 Create .DLL file
To creating an ActiveX DLL project:
1. Select File -> New Project and select ActiveX DLL as the type of the project.
64
2. Visual Basic creates a new project with a single class module with Class1 and change
the name to time.
Using Class Builder utility
Class builder utility could be used to create skeleton for methods, properties and
events. Let us use class builder utility to create attributes of Time class.

To invoke Class Builder Utility


1. Select Add-In Manager option of Add-Ins Menu.
2. In Add-In Manager window double click on VB 6 Class Builder Utility
3. Then message Loaded appears under Load Behavior column.
4. Click on Ok.
5. Select Add-Ins menu and choose Class Builder Utility to invoke Class Builder.
6. If Class Builder displays a warning message, just ignore it and continue.

Renaming Class1 to Time


1. Select Class1 in Classes Pane of Class Builder Utility and click on right button.
2. Select Rename option and rename Class1 to Time.

Creating properties, methods and events using Class Builder


1 Click right button on Time class
2 Select New-> Property option from popup menu.
3 Enter the name of the property as hour and change data type to Integer.
4 In declaration group leave the Public Property radio button selected.
5 And click on Ok
At this stage class builder displays a property in the left pane.
1. Repeat the process for Min and Second properties.
2. Click right button on Time class and select New->Method from popup menu.
3. Enter Increment Second as the name of the method.
4. Select Attributes table and enter “Increment time by one second” as the description.
5. Whatever description the user entered that will be displayed in Object Browser when
user selects this method.
6. Click on Ok
7. Repeat the same process for SetToCurrent method. Enter “Sets time to current
systemtime” as the description.

65
8. Again select New->Method from popup menu and enter SetTime as the name of the
method and “Changes the time to the given time. Time must be given in HH: MM: SS
format” as description.
9. Then click on + sign on the right of Arguments list box and enter the following
details.
Name NewTime
Type String
ByVal Checked
Note: if optional checkbox is checked then the argument is optional. If no value is passed to
the argument then the given default value will be stored in that.
1. Create one more method with the name GetTime and specify the Return Data Type as
String.
2. Select New->Event from popup menu of Time class
3. Enter Invalid Time as the name of the event and “Fired when an given hour, min or
second is invalid” as the description
Note: add property, method and event using icons in toolbar also.
Note: Select tab “All” it displays all the attributes of the class.
Otherwise select one of the three tabs (Properties, Methods, and Events) to display the
specific members. To update project with changes made in class builder:
1. Select File-> Update Project option. Class builder updates the class module with
the details furnished so far.
2. Exit Class builder with File-> Exit.
If the Time class module is open, the code contains three properties, two methods and
one event.

Here are the steps to change properties.


1. Select Project ->Project Properties to invoke properties window of the current project.
2. Change Project Name to TimeServer
3. Change Project Description to “Time Class By AVP”.
4. And click on Ok.

Creating .DLL file


Now the final step is to create .DLL file for the project. This DLL file is used by the
client application. At the time of creating .DLL file Visual Basic registers this ActiveX
66
server in system register. Note: All ActiveX components must be registered in the system
registry. Otherwise they cannot be used in client application.

To create .DLL file


1. Select File menu and choose Make TimeProject.dll option.
2. User are prompted to specify the directory and the name of the file, select the
directory.DLL file and leave the filename to default (TimeProject).
3. Click on Ok to create .DLL file.
That is the end of creation of ActiveX in-process server.

Here are the steps to create testing project


1. Start a new project using File -> New Project and select Standard Exe as the
project type.
2. Invoke Form designer and place two labels and four command buttons.
3. Change the properties of the controls and form as follows.

Creating a reference to ActiveX server


1. Select Project - > References Visual Basic displays the list of ActiveX servers that are
registered in the system registry .
2. Search for “Time Class By P.Srikanth”. Because whatever user give as project
description in ActiveX server project, that will be displayed in References window.
3. Once user locate it, check the check box on the left. Also observe that the complete
path of .DLL file is placed at the bottom of the window .
4. After turning on the check box click on Ok to close References window.
5. Save the project as TimeTest.Vbp and form as TimeTest.Frm.
Test Run Now runs the project.

67
Unit IV

4.1. OBJECT LINKING AND EMBEDDING


OLE (Object Linking and Embedding) is a means to interchange data between
applications. Of late OLE has been enhanced to provide not just data but also methods that
can be used by client application.

OLE Server
This is an application that can provide objects to other applications. This is also
called as OLE Source application.

OLE Client
This is an application that uses objects provided by OLE Server. This is also called as
OLE Container as it contains objects provided by OLE Server. Not every application is an
OLE Server. Only a few applications are capable of providing objects. In the same way not
all applications are capable of receiving objects. However, there are applications, such as
MS-Word and MS-Excel that are capable of being OLE source as well as OLE Container.

4.2. OLE FUNDAMENTALS


What is Object Embedding?
In object embedding, an object is embedded in the client application. Along with the
object, client application also stores the information regarding source application (or server)
that created the object. The data stored in client application is separate and no link is
maintained between the data supplied by source application and data stored in client
application.
The advantage with Object Embedding is, client application maintains its own copy
of the data.
The disadvantage is, changes made to original data (in source application) will not
be incorporated in the data maintained by client.
Whenever user double clicks on the object in container application, the source
application will be invoked (as information regarding source application is maintained) and
the data of client application is placed in source application for editing.
The following example, embed a few cells of Excel spreadsheet to a Word document,
will make this process clear:

68
1. A collection of cells from a spreadsheet of MS-Excel is copied to clipboard. As MS-
Excel is an OLE Server, it copies the data in the form of an object.
2. Paste the data (now in the form of an object) from Clipboard to a document in Ms-
Word.
3. Now the data is embedded into MS-World document as an object. Ms-Word
document contains its own copy of the data.
4. If double click on the object in MS-Word, then an instance of MS-Excel is invoked
and data from MS-Word is copied into MS-Excel.
5. User can edit embedded data using MS-Excel.
6. If user saves changes and exits MS-Excel then modified data is placed in MS-Word
document.
In the above example, once an object is embedded into MS-Word, do not have to
invoke source application manually, instead just double click on the object and that will
invoke source application automatically. However, if data is changed in the original
worksheet of MS-Excel then those changes are not copied to the data in MS-Word. This is
because in Object Embedding, source and container applications maintain two different
copies of the data.

What is Object Linking?


Object linking makes changes made to source application available to container
application. This is because container doesn’t store a separate copy of the data; instead it
maintains a link to data in source application.
In object linking, no separate copy of the required portion of spreadsheet is stored in
MS-Word document, instead, the name of the file and the location of the data in the file are
only maintained. Whenever open MS-Word document, the data is taken from the
spreadsheet file from where the data for object is taken. That is the reason why changes
made in spreadsheet file (source) will be available to container application.

Advantages of Object Linking are:


 Changes made in source document are available to clients.
 As no separate copy of data is stored in clients, it saves space on disk.

Disadvantage of Object Linking is:


 If original data is lost, then client Application cannot access data.

69
Fig. Topology of OLE DB applications.
The primary focus of the ODBC is to provide a consistent interface to database
data sources. OLE DB is designed with an even broader goal in mind; to provide a
methodology to access data regardless of the data source. OLE DB becomes the data
access bridge for documents, e-mail systems, file systems, spreadsheets, and database
sources using ODBC drivers.

Inserting a OLE Object


An OLE object is an item that is exposed, or made available, by an OLE server
application. OLE server applications expose different types (or Classes) of objects.

DDE & ActiveX Controls


OLE objects are used in container applications. As Figure illustrates, Excel ( the OLE
server) can expose a worksheet (the OLE object) that can be inserted as is in a Word
document ( the container application).

70
4.3. OLE CONTAINER CONTROL

In Visual Basic, embed or link an object using OLE container control. OLE control is
one of the standard set of controls. This allows the user to either embed or link an object
either at design time or at run time thorough its properties and methods. OLE Container
control can be bound to database using a data control.

To create OLE Container control


1. Select OLE control in Toolbox.
2. Place the control on the form with the required size.
3. As soon as OLE control is placed on the form, Insert Object Dialog is displayed to
allow user to either embed or link an object into OLE Container.
4. The available options in insert dialog are - Create New, in this select an Object
Type and create an object using the appropriate application, or Create From File,
to create an object by selecting a file from file system.

To embed a word document into OLE Container control


1. In Insert Object Dialog box select Create From File radio button.
2. Click on Browse button and select a document file .
3. Click on Ok
4. An object is embedded into OLE Container control and a part of document is
displayed.
5. Run the project using F5.
6. Double click on OLE Container control. This action will invoke MS-Word and
run it in OLE Container control. When OLE Server runs in OLE Client, it is called
as In-Place Activation.
7. Make necessary changes using MS-Word.
8. Press ESC key to come out of In-Place activation.
Note: When user activate object, if OLE Server runs in client application, It is called as In-
place Activation.
A word document in OLE container on Visual Basic form at runtime.

71
The followings are the other options available in Insert Object Dialog box.
S.No Option Explanation
1 Create From File Allows an object to be embedded or linked from a file.

2 Create New Allows creating a new file and then embedding an object
from newly created file.
3 Display As Icon Displays an icon instead of the content of the object.
4 Browse Displays a dialog box from which user can select a file.
5 Link If turn on this checkbox, then object is linked, otherwise
it is embedded..

Properties of OLE container control


The following are the important properties of OLE Container Control.
S.No Property Meaning
1 Class Contains the class name of the embedded object.
2 File Number Contains the number of the file used in last saving or loading
operation.
3 Display Type Determines whether content of the object is displayed – 0, or
an icon -1.
4 OLE Type Contains the status of the control. Valid values are: 0- linked,
1-embedded, or 3 – none.
5 Source Doc Contains the name of the file that is used to create the object.
6 Source Item Specifies which part of Source Doc is to be used to create
object when link object.
7 AppIs Running Indicates whether the application that created the object is
currently running.
8 Auto Verbmenu Specifies whether menu containing available verbs is
displayed when user clicks on right button.
9 OLEType Specifes what type of object OLE container control can
Allowed contain. Valid options are: 0 – only linked, 1- only embedded,
and 2- both.
10 SizeMode Determines how image is displayed in OLE control. The
Property following are the valid options.
11 Update Options Specifies how a linked object is updated in Container when
property the original object is modified.

Option Value Meaning


S.No Option Value Meaning
1 VbOLESizeClip 0 The object is displayed in original size. If the size of
object is larger than the size of control then object is
clipped to the size of the control.
2 VbOLESize Stretch1 The size of the object is resized to the size of OLE
container control.
3 VbOLE SizeAutoSize2 OLE container is automatically resized to the size of
the object.
72
4 VbOLESizeZoom 3 The object is resized to fill the OLE container control
as much as possible while still maintaining the original
proportions (width and height) of the object.
Valid Options
5 VbOLEAutomatic 0 Object is automatically updated whenever
source data is updated.
6 VbOLEFrozen 1 Updates object whenever data in source
application is saved.
7 VbOLEManual 2 Object is updated by invoking Update method
of OLE Control.
8 AutoActivate property Specifies how an object is activated. When
object is activated the source application is
invoked.
9 VbOLEActivateManual 0 Use DoVerb method to activate object.
10 VbOLEActivateGetFocus 1 If object supports single click activation, then
source application is activated whenever OLE
container control receives focus.
11 VbOLEActivateDoubleclick 2 Double clicking on the object activates source
application.
12 VbOLEActivateAuto 3 Activation depends on the type of object.
13 MiscFlags Property Allows to specify how data is to be stored and
whenever in-place activation is enabled.
14 VbOLEMiscFlagMemStorage Causes the control to use memory to store the
object while it's loaded.
15 VbOLEMiscFlagDisableInPlace Overrides the control's default behavior of
allowing in-place activation for objects that
support it.

Methods of OLE Control


S.No Methods Meaning
1 PasteSpecialDlg Displays Paste Special dialog box.
2 Copy Copies the content of OLE container control to clipboard.
3 CreateEmbed Creates an embedded object with the given source document
and class, if given.
4 CreateLink Creates a linked object with the given file and specified data
in the file.
5 Delete Deletes the specified object and frees memory allocated to
object.
6 InsertObjDlg Displays Insert Object Dialog box.
7 Paste Creates an object with the data that is in clipboard.
8 ReadFromFile Creates an object by loading the data that was written to the
file using SaveToFile method.
9 SaveToFile Write the data of object to the given file. The file can be read
using ReadToFile method
10 Close Closes the object.
11 DoVerb Performs the specified operation on the object.
12 Update Used to updates linked data manually.

73
Sample Application
Scode Text(5) Subject code.
Sdes Text(20) Subject description.
Duration Integer Number of hours.
Syllabus Binary Contains the syllabus of the subject in Word document.
The user interface of the data entry screen
The following table will summarize the role played by each control on the form.

Control Meaning
txtScode Bound to Scode column of SUBJECT table.
txtSdes Bound to Sdec column of SUBJECTS table.
txtDur Bound to Duration column of SUBJECTS table.
Data1 Data control that is bound to SUBJECTS table of COURSE.MDB.
OLE Bound to Syllabus column of SUBJECTS table.
Add New Subject command button adds a new blank record to SUBJECTS table by
using AddNew method of Recordset.
Quit Is used to terminate the program.

Create sample application


SUBJECT table of COURSE.MDB.
1. Start a new project using File-> New Project.
2. Select Standard EXE as the type of the project.
3. Place required controls (controls listed in table 23.5 and labels) on the form and
arrangethem in the manner
4. Change the following properties of the controls.
Object Property Value
Data1 DatabaseName C:\BOOKS\VB60\PROGRAMS\COURSE.MDB.
Note: The path may be different on the system.
Recordsource Subjects
Caption Subject Details
Text1 Name txtScode
Datasource Data1
Datafield Scode
Writing Code
Private Sub Cmdaddnew_Click()
74
Data1.Recordset.AddNew
txtScode.SetFocus
End Sub
Private Sub CmdQuit_Click()
Unload Me
End Sub
Private Sub Cmdseldoc_Click()
With CommonDialog1.Filter = "Word Documents|*.doc|All files|*.*".ShowOpen
If .FileName <> "" Then
OLE1.CreateEmbed .FileName
End If
End With
End Sub
Test Run
1. Run the project using F5.
2. If already it have some records in SUBJECTS table then first of those records will
be displayed, otherwise display an empty form.
3. Click on Add New Subject button.
4. When an empty form is displayed enter the following details into first three text
boxes.

4.4. OLE AUTOMATION


The method allows user to programmatically manipulate objects exposed by another
application from within the Visual Basic applications. It’s also a standard that defines how
code is shared between applications and how applications can be controlled form within other
applications. For example, copy a range of cells from an Excel spreadsheet onto a Word
document, embed the range of cells. With OLE Automation, application can request that
Excel perform some calculations and return the result to Word. For example, it can pass a
table to Excel and request that Excel manipulate the numeric data in ways that are not
possible with Word’s tools and then return the processed data to Word.

75
4.5. OLE DRAG AND DROP
OLE Drag and Drop allows to drag data from one control and drop it on another
control. The most interesting of all is its ability to support drag and drop across
applications. That means it is possible to drag some text form a document in MS-Word and
drop it in a textbox in Visual Basic.

Automatic vs. Manual


When a control supports automatic OLE drag, it means need not write any code to
avail the facility. And the same is the case with OLE drop. When a control supports OLE
drag (or OLE Drop) but only in manual mode, then programmer has to write code to
support the facility. Some controls support both automatic OLE Drag mode and OLE Drop
mode. While some other control support only automatic OLE dragging and manual
dropping. Some controls support only automatic dropping and manual dragging. Some
other control may support only manual OLE dragging and OLE dropping.

Properties, Events and Methods related to OLE Drag and Drop


Properties related to OLE Drag and Drop
S.No Property Meaning
1 OLEDragMode Determines whether to use automatic or manual dragging.
This property will not be available if the control does not
support automatic dragging.

2 OLEDropMode Specifies whether to have manual dropping or automatic


dropping.

76
Properties related to OLE Drag and Drop.
The settings for these two properties will be, None, Manual, and Automatic. The
actual options depend upon the extent of OLE Drag and Drop support the control has.

Events related to OLE Drag and Drop


The following are the events that occur during OLE Drag and Drop process. Some of
the events in the list are fired at source (where OLE Drag and Drop was initiated).
S.No Events Meaning
1 Target OLEDragDrop Recognizes when a source object is dropped on
target.
2 Target OLEDragOver Recognizes when a source object is dragged over
target.
3 Target OLEGiveFeedback Provides customized drag icon feedback to the
user, based on the source object.
4 OLE StartDrag Specifies which data formats and drop effects
(copy, move, or refuse data) the source supports
when dragging is initiated.
5 Source OLESetData Provides data when the source object is dropped.
This is called only when data is not passed in
OLEStartDrag event
6 Source Informs the source of the action that was
OLECompleteDrag performed when the object was dropped into the
target.

OLEDrag Method
Starts OLE dragging. This is used to manually start OLE dragging. Dragging text
from MS-Word into a text box using OLE Drag and Drop
Let us now understand the process involved in dragging text entered in MS-Word into
a textbox that is placed on a form in Visual Basic.
1. Start a new project using File-> New Project -> Standard EXE.
2. Place a Textbox on the form.
3. Change OLEDrop Mode property of the textbox (Text1) to 1-Automatic.
4. Run Visual Basic project using F5.
5. Start MS-Word.
6. Type some text in word document
7. Arrange Visual Basic project and MS-Word
8. Select the text in word document and drag the text while holding down ctrl key
into text box of the form.

77
Sample Application for Manual OLE Drag and Drop
The sample application that we are going to develop has a simple form with two
textboxes. First textbox is used as the source and second textbox is used as the target. The
main purpose of the application is to understand the steps involved handling OLE Drag and
Drop manually.
First textbox's OLEDragMode is set to Manual and OLEDropMode property is set to
Automatic.
Second textbox's OLEDragMode is set to Automatic and OLEDropMode is set to
Manual.

The following are the steps to be taken to develop this application.


1. Start a new project using File-> New Project and select Standard EXE as the type
of the project.
2. Place two textboxes along with labels and a command button.
3. Arrange the controls on the form in a neat format.
4. Change the following properties.

Object Property Value


Label1 Caption Source
Text1 Name txtsource Text ""
OLEDragMode 0-Manual
OLEDropMode 2-Automatic.
Text2 Name txtTarget
Text ""
OLEDragMode 1-Automatic
OLEDropMode 1-Manual
Form Caption OLE Drag and Drop
Command1 Name CmdQuit
Caption &Quit

Writing code
Private Sub txtsource_MouseDown(Button As Integer, Shift As Integer, X As Single, Y As
Single)
txtsource.OLEDrag
End Sub
78
Private Sub txtsource_OLECompleteDrag(Effect As Long) If
(Effect and vbDropEffectMove)<>0 Then
txtsource.Text = ""
End If
End Sub
Private Sub txtsource_OLEStartDrag(Data As DataObject, AllowedEffects As Long)
AllowedEffects = vbDropEffectMove Or vbDropEffectCopy
Data.SetData UCase(txtsource.Text)
End Sub
Private Sub txtTarget_OLEDragDrop(Data As DataObject, Effect As Long, Button As
Integer, Shift As Integer, X As Single, Y As Single)
txtTarget.Text = Data.GetData(vbCFText)
Effect = vbDropEffectMove
End Sub

4.6. FILE-SYSTEM CONTROLS


(Directory List Box, Drive List Box, and File List Box)
Many applications must present information about disk drives, directories, and files. To
allow users of applications to explore the file system, Visual Basic provides two alternatives.
1 Standard dialog boxes provided by the common dialog control, and
2 Custom dialogs -combinations of three specialized controls.
 the drive list box,
 the directory list box,
 the file list box.
Each of the file-system controls has been carefully designed to combine flexible and
sophisticated file-system inspection capabilities with easy programming. Each control
performs its file-data retrieval tasks automatically, but user can write code both to customize
their appearance and to specify which information they display.

The file-system controls

79
The file-system controls used together
File-system controls obtain all their information from the operating system
automatically; User can access this information or determine what is displayed by each
control through its properties. For example, the content of the current working directory is
displayed by default (that is, the directory from which the application was launched, or what
became the current directory as the result of a ChDir statement).
Application can also display a list of the files with names matching a pattern, such as
*.frm. Simply draw a file list box on the form and set its Pattern property to *.frm. Here
specify the Pattern property at run time with the following code:
File1.Pattern = "*.FRM"
The file-system controls give the flexibility that is not available with the common
dialog control.

The Drive List Box


The drive list box is a drop-down list box. By default, the current drive is displayed
on the user's system. When this control has the focus, the user can type in any valid drive
designation or click the arrow at the right of the drive list box. When the user clicks the
arrow, the list box drops down to list all valid drives. If the user selects a new drive from the
list, that drive appears at the top of the list box.
Drive property of the drive list box to determine which drive is currently selected.
Application can also specify which drive appears at the top of the list box with this simple
assignment:
Drive1.Drive = "c:\"
The drive list box displays valid available drives. Choosing a drive from the list box
doesn't automatically change the current working drive; however, user can use the Drive

80
property to change drives at the operating system level by specifying it as an argument to the
ChDrive method:
ChDrive Drive1.Drive

The Directory List Box


The directory list box displays the directory structure of the current drive on the user's
system, beginning with the top-level directory. Initially, the name of the current directory
appears highlighted and indented from directories above it in the hierarchy, back to the root.
Subdirectories are indented beneath the current directory in the directory list box. As a user
moves up or down the list, each of the items is highlighted in turn.

Identifying Individual Directories


Each directory in the box has an integer identifier associated with it that allows user to
identify individual directories. This capability is not provided by the common dialog control.
The directory specified by the Path property (Dir1.Path) always has the ListIndex value of 1.
The directory immediately above it has the ListIndex value of – 2, the one above that of – 3,
and so on up to the root. The first subdirectory of Dir1.Path has the ListIndex 0. If there are
multiple directories at the first subdirectory level, the next has the List Index value of 1, then
2, and so on, as shown in Figure.

A directory structure displayed in the directory list box

Setting the Current Directory


Use the Path property of the directory list box to set or return the current directory in
the box (ListIndex = – 1). For example
Drive1.Path= "c:\payroll"
the \Payroll directory becomes selected as the current working directory.
Similarly, assign the Drive property of the drive list box to the Path property of the directory
list box:

81
Dir1.Path = Drive1.Drive
This assignment is executed; the directory list box displays all the available
directories and subdirectories on that drive. By default, the directory list box also displays all
directories above, and any subdirectories immediately below, the current directory of a drive
assigned to the Dir1.Path property. The directory list box doesn't set the current directory at
the operating system level; it merely highlights the directory and gives it the ListIndex value
of – 1.
To set the current working directory, use the ChDir statement. For example, the
following statement changes the current directory to the one displayed in the directory list
box: ChDir Dir1.Path
In an application that uses file controls, set the current directory to the directory where
the application's executable (.exe) file is located with the Application object:
ChDrive App.Path ' Set the drive.
ChDir App.Path ' Set the directory.
The Path property is available only at run time, not at design time.

Clicking a Directory Item


When a user clicks an item in a directory list box, that item is highlighted. When an
item is double-clicked, it is assigned to the Path property, its ListIndex property gets the
value –1, and the directory list box is redrawn to show its immediate subdirectories.

Finding a Directory's Relative Position


The ListCount property returns the number of directories below the currently
expanded directory, not the total number of items in the directory list box. Because the
ListIndex value of the currently expanded directory is always –1.
For example:
' Initialize for currently expanded directory.
GoHigher = 0
' Dir1.List(x) returns empty string if the directory
' doesn't exist.
Do Until Dir1.List(GoHigher) = ""
GoHigher = GoHigher - 1
Loop
' Convert to positive number, if desired.
LevelsAbove = Abs(GoHigher)
82
The File List Box
The file list box displays files contained in the directory specified by the Path property
at run time. Display all the files in the current directory on the current drive using the
following statement:
File1.Path = Dir1.Path
The Pattern property can also accept a list delimited by semicolons. For example, a
line with the following code displays all files with the extensions .frm and .bas:
File1.Pattern = "*.frm; *.bas"
Visual Basic supports the ? wildcard character. For instance, ???.txt displays files that have
base names of only three characters with the extension .txt.

Working with File Attributes


The attributes of the currently selected file (Archive, Normal, System, Hidden, and
ReadOnly) are also available through file list box properties. The default value for the System
and Hidden attributes is False. The default value for the Normal, Archive, and ReadOnly
attributes is True.
To display only read-only files in the list box, for example, simply set the ReadOnly
property to True and the other attribute properties to False:
File1.ReadOnly = True
File1.Archive = False
File1.Normal = False
File1.System = False
File1.Hidden = False
When Normal = True, those files without the System or Hidden attribute are
displayed. When Normal = False, it can still display files with Read Only and/or Archive
attributes by setting these attributes to True. To set file attributes, use the SetAttr statement.
By default, highlight only a single selection in a file list box. To select multiple files,
use the MultiSelect property.

Using File-System Controls Together


If user uses a combination of file-system controls, user can synchronize the information
they display. For example, a drive list box, a directory list box, and a file list box with the
default names Drive1, Dir1, and File1, the sequence of events might work like this:

83
 The user selects a drive in the Drive1 list box.
 A Drive1_Change event is generated, and the display in Drive1 is updated to
reflect the new drive.
 Code in the Drive1_Change event procedure assigns the new selection (the
Drive1.Drive property) to the Path property of the Dir1 list box with the following
statements:
Private Sub Drive1_Change ()
Dir1.Path = Drive1.Drive
End Sub
 The assignment to the Path property generates a Dir1_Change event and updates
the display in Dir1 to reflect the current directory of the new drive.
 Code in the Dir1_Change event procedure assigns the new path (the Dir1.Path
property) to the File1.Path property of the File1 list box:
Private Sub Dir1_Change ()
File1.Path = Dir1.Path
End Sub
 The assignment to the File1.Path property causes the display in the File1 list box to
reflect the Dir1 path specification.
 To change the event procedures and the properties depend on the application uses the
combination of file-system controls.

File-System Controls Scenario: (The Winseek Application)


Because users often want to find a file or group of files available to an application
quickly, many applications provide capabilities for investigating the file system. Following
sample application helps the user browse drives and directories, and displays any category of
files.

File-system controls in the WinSeek application

84
The following table summarizes the controls in Seek.frm from the WinSeek application.
Control Property Setting
Drive list box Name drvList
Directory list box Name dirList
File list box Name Pattern filList *.*
First command button NameCaption cmdSearch
Default &Search True
Secondcommand button Name Caption cmdExit E&xit
List box Name lstFoundFiles

Writing Code for the WinSeek Application


In the drive list box, a Change event is triggered by a single mouse click on an item.
A Change event also occurs when the user selects an item and then changes the focus on the
form. In the directory list box, a DblClick event is necessary to generate a Change event.

When users want to change directories without using a mouse, they typically use the
arrow keys to select the desired directory and then press the ENTER key. Because ENTER is
commonly associated with the default command button control, WinSeek must recognize
when the user simply wants to change directories rather than conduct a search for files.

The WinSeek application resolves this ambiguity by determining if the path of the
dirList box differs from the currently highlighted directory. This situation can occur when the
user single-clicks an item in the directory list box or navigates the directory list box using the
arrow keys. The following code determines whether the dirList.Path is different from the path
of the highlighted directory. If the paths are different, the dirList.Path is updated. If the paths
are the same, the search is performed.
Private Sub cmdSearch_Click()
' If the dirList.Path is different from the currently
' selected directory, update it; otherwise perform the
search.
If dirList.Path <> dirList.List(dirList.ListIndex) Then
dirList.Path = dirList.List(dirList.ListIndex)
Exit Sub
End If
' Continue with search.
End Sub

85
The WinSeek application uses the following procedures to handle significant events:
 The DrvList_Change procedure
 The DirList_Change procedure
 The CmdSearch_Click procedure

The Drive List Box's Change Event


When the user clicks an item in the drive list box, its Change event is generated. The
drvList_Change event procedure is invoked, and the following code is run:
Private Sub drvList_Change ()
On Error GoTo DriveHandler
' If new drive was selected, the Dir1 box
' updates its display.
dirList.Path = drvList.Drive
Exit Sub
' If there is an error, reset drvList.Drive with the
' drive from dirList.Path.
DriveHandler:
drvList.Drive = dirList.Path
Exit Sub
End Sub

The Directory List Box's Change Event


If the user double-clicks an item in the directory list box, or if the Path property of
dirList is changed in code (as in the drvList_Change procedure), the dirList_Change event is
initiated. The following code responds to that event:
Private Sub dirList_Change ()
' Update file list box to synchronize with the
' directory list box.
filList.Path = dirList.Path
End Sub
This event procedure assigns the Path property of the dirList box to the Path property
of the filList box. This causes a PathChange event in the filList list box, which is redrawn;

86
The Command Button's Click Event
This event procedure determines whether the highlighted item in the dirList list box is
the same as the dirList.Path. If the items are different, then dirList.Path is updated. If the
items are the same, then the search is performed.
Private Sub cmdSearch_Click ()
' If the dirList.Path is different from the
' currently selected directory, update it;
' otherwise perform the search.
If dirList.Path <> dirList.List _
(dirList.ListIndex) Then
dirList.Path = dirList.List(dirList.ListIndex)
Exit Sub
End If
' Continue with search.
End Sub

DragDrop Event
Occurs when a drag-and-drop operation is completed as a result of dragging a control
over an object and releasing the mouse button or using the Drag method with its action
argument set to 2 (Drop).
Syntax
Private Sub Form_DragDrop(source As Control, x As Single, y As Single)
Private Sub object_DragDrop([index As Integer,]source As Control, x As Single, y As Single)

The DragDrop event syntax has these parts:


Part Description
object An object expression that evaluates to an object in the Applies To list.
Index An integer that uniquely identifies a control if it's in a control a array.
source The control being dragged. It include properties and methods in the event
procedure with this argument — for example, Source.Visible = 0.
x, y A number that specifies the current horizontal (x) and vertical (y) position of
the mouse pointer within the target form or control. These coordinates are
always expressed in terms of the target's coordinate system as set by the
ScaleHeight, ScaleWidth, ScaleLeft, and ScaleTop properties.

87
Remarks
Use a DragDrop event procedure to control what happens after a drag operation is
completed. For example, it moves the source control to a new location or copy a file from one
location to another.
When multiple controls can potentially be used in a source argument:
 Use the Type Of keyword with the If statement to determine the type of control used
with source.
 Use the control's Tag property to identify a control, and then use a Drag Drop event
procedure.
Note Use the Drag Mode property and Drag method to specify the way dragging is initiated.
Once dragging has been initiated, it handles events that precede a Drag Drop event with a
Drag over event procedure

4.7. FILE HANDLING


A file is a collection of bytes stored on the disk with a given name (called as
filename). Every development tool provides access to these files on the disk.
The following are three important steps in handling a file.
1. Opening the file
2. Processing the file, i.e. either reading the content of the file or writing the
required data into file or both.
3. Closing the file

File access types


i. Depending upon the requirement to use any of the three different file access types
ii. Sequential For reading and writing text files in continuous blocks.
iii. Random For reading and writing text or binary files structured as fixed-length
records.
iv. Binary For reading and writing arbitrarily structured files.

Opening the file using Open statement


A file is opened using OPEN statement in Visual Basic. At the time of opening a file,
to specify the following.

 Name of the file to be opened

88
 The mode in which file is to be opened. The mode specifies which operations are
allowed on the file.
 File number. Each open file contains a file number. This file number is used to access
the file once the file is opened. The file number must be unique.

Open pathname For mode [Access access] [lock] As [#] filenumber [Len=reclength]
The first step in working with files in Visual Basic is to open the file. This is achieved
using the Visual Basic FileStream class. The FileStreamconstructor accepts the file name to
be opened as the first parameter, followed by a number of other parameters defining the mode
in which the file is to be opened.
These fall into the categories of FileMode, FileAccess and FileShare. The options
available as listed in the following tables:

FileMode Options

<google>ADSDAQBOX_FLOW</google>

Mode Description
If the file exists it is opened. Any writes are appended to the end of the file.
Append
Requires FileAccess.Write mode
Create Creates a new file, removing old file if it already exists
CreateNew Creates a new file and returns error if file already exists
Open Opens an existing file. Returns error if file does not exist
OpenOrCreate If file already exists it is opened, otherwise a new file is created
Truncate Opens an existing file and deletes all existing content

FileAccess Options
Mode Description
Read Opens the file for reading only.
ReadWrite Opens the file for both reading and writing
Write Opens the file to writing only

89
FileShare Options
Mode Description
The file cannot be opened by any other program until it is closed by the
None
current program
Other programs may simultaneously open and read from the file, but not
Read
write to it.
Other programs may simultaneously open and read and write from/to the
ReadWrite
file.
Other programs may simultaneously open and write to the file, but not read
Write
from it.

Dim textFileStream As New IO.FileStream("C:\Temp\test.txt", IO.FileMode.OpenOrCreate,


IO.FileAccess.ReadWrite, IO.FileShare.None)
textFileStream.Close()
Note that the above code example assumes that the 'C:\Temp' directory already exists. If it
does not, the code will fail.

Writing to a file with VB


Once a file has been opened with the appropriate options, it can be written to using
the Visual Basic StreamWriter class. The StreamWriterconstructor takes a FileStream as the
sole parameter. The Write() and WriteLine() methods of the StreamWriter class are then used
to write to the file. Write() writes the text with no new line appended to the end of each
line. WriteLine() on the other hand, appends a new line to end of each line written to the file.
In the following code excerpt a StreamWriter object is created using the FileStream, and a
For loop writes 11 lines to the file:
Dim textFileStream As New IO.FileStream("C:\Temp\test.txt",
IO.FileMode.OpenOrCreate,IO.FileAccess.ReadWrite, IO.FileShare.None)
Dim myFileWriter As New IO.StreamWriter(textFileStream)
Dim intCounter As Integer
For intCounter = 0 To 10
myFileWriter.WriteLine("This is line " & CStr(intCounter))
Next intCounter
myFileWriter.Close()
textFileStream.Close()

90
Reading from a File using VB
Now that we have created and written to a file the next step is to read some data from
the file. This is achieved using the Visual Basic StreamReader object.
The StreamReader ReadLine() method can be used to read the next line from the file stream
including the new line. The Read() method reads a line from the file but removes the new
line. The ReadToEnd() method can be used to read from the current line in the file to the end
of the file. The following example reads the data back from the file after it has been written
and display the contents in a MessageBox:
Dim textFileStream As New IO.FileStream("C:\Temp\test.txt",
IO.FileMode.OpenOrCreate,IO.FileAccess.ReadWrite, IO.FileShare.None)
Dim myFileWriter As New IO.StreamWriter(textFileStream)
Dim myFileReader As New IO.StreamReader(textFileStream)
Dim intCounter As Integer
Dim strFileContents As String
For intCounter = 0 To 10
myFileWriter.WriteLine("This is line " & CStr(intCounter))
Next intCounter
strFileContents = myFileReader.ReadToEnd
MessageBox.Show(strFileContents)
myFileWriter.Close()
myFileReader.Close()
textFileStream.Close()
Detecting a Change to a File
A Visual Basic can monitor a file and receive notification from the OS when the file
is changed by any program. This is achieved using the FileSystemWatcher class. Start Visual
Studio and create a new Windows Application project. Access the Toolbox and double click
on the FileSystemWatchercontrol from the Components section of the list. The new object
will appear beneath the Form design area with the name FileSystemWatcher1. Select the
object and use the Properties panel to change the Path to C:\Temp and the Filter property
to test.txt. Double click on the FileSystemWatcher1 object to access the event procedure code
and modify the changed event as follows:
Private Sub FileSystemWatcher1_Changed(ByVal sender As System.Object,
ByVal e As System.IO.FileSystemEventArgs) Handles FileSystemWatcher1.Changed
MessageBox.Show("File changed")
End Sub
91
Unit V

5.1. ADDITIONAL CONTROLS


Several other standard controls are included in the Visual Basic toolbox. Some
controls are useful for working with large amounts of data contained in an external database.
Other controls can be used to access the Windows file system. Still other controls defy
categorization, but are useful nonetheless.

Data Access Controls


In today's business, most information is stored in one or more central databases. Visual
Basic includes several data access controls for accessing most popular databases, including
Microsoft Access and SQL Server.
 The ADO Data control is used to connect to a database. Think of it as a pipeline
between the database and the other controls on their form. Its properties, methods,
and events allow to navigate and manipulate external data from within own
application.
 The DataList control is similar to the list box control. When used in conjunction
with an ADO Data control, it can be automatically filled with a list of data from a
field in an external database.
 The DataCombo control is like a combination of the DataList control and a text box.
The selected text in the text box portion can be edited, with the changes appearing
in the underlying database.
 The DataGrid control displays data in a grid or table. It is used in conjunction with
an ADO Data control; it presents fully editable data from multiple fields in an
external database.
 The Microsoft Hierarchical Flex Grid control is a unique control for presenting
multiple views of data. Think of it as a combination of a grid and a tree or outline
control. At run time, the user can rearrange columns and rows to provide different
views of the data.

File System Controls


The DriveList Box control looks like a combo box. It provides a drop-down list of
drives from which the user can select.
The DirList Box is similar to a list box control, but with the built-in capability of
displaying a list of directories in the currently selected drives.
92
The FileList Box control also looks like a list box with a list of file names in a
selected directory.

Miscellaneous Controls
 The timer control can be used to create an event in their application at a
recurring interval. This is useful for executing code without the need for user
interaction.
 The OLE container control is an easy way to add capabilities like linking and
embedding to the application. Through the OLE container control, It can
provide access to the functionality of any OLE-enabled application such as
Microsoft Excel, Word and many others.
 The common dialog control adds built-in dialog boxes to the application for the
selection of files, colors, fonts, and printing functions.

5.2. SSTab CONTROL


The SSTab control provides a group of tabs, each of which acts as a container for
other controls. 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.
An SSTab control is like the dividers in a notebook or the labels on a group of file
folders. Using an SSTab control, user can define multiple pages for the same area of a
window or dialog box in application.
Using the properties of this control:
 Determine the number of tabs.
 Organize the tabs into more than one row.
 Set the text for each tab.
 Display a graphic on each tab.
 Determine the style of tabs used.
 Set the size of each tab.
To use this control, first organize the controls after place into various tabs. Set the
Tabs and TabsPerRow properties to create the tabs and organize them into rows. Then select
each tab at design time by clicking the tab. For each tab, draw the controls. Set the Caption,
Picture, TabHeight, and TabMaxWidth properties as needed to customize the top part of
the tab.

93
SSTab control using the Style, ShowFocusRect, TabOrientation, and WordWrap
properties.

Changing the Appearance of the Dialog


Five key properties of the SSTab control its overall appearance: Style, TabHeight,
TabMaxWidth, TabOrientation and WordWrap.
The style property controls whether the tab looks like those in Microsoft Office for
Windows 3.1 or the property page tabs of Windows 95 applications. The TabOrientation
property controls the placement of the tabs in relation to the body of the control. Then Placed
the tab at the top of the control (Default), the bottom of the control, or on the right or left side
of the control.
If a picture is used, the SSTab control places as much of the picture on the tab as
possible. The picture is centered vertically and horizontally on the tab. From side to side, the
picture and the caption are centered together. This means that the caption text appears to the
right of the picture.

5.3. SETTING PROPERTIES AT RUN RIME


Declares a Set property procedure used to assign a value to a property.
Syntax
Copy
[ <attributelist> ] [ accessmodifier ] Set (ByVal value [ As datatype ])
[ statements ]
End Set
Parts
Attributelist Optional.
Accessmodifier
Optional on at most one of the Get and Set statements in this property. Can be one of the
following:
 Protected
 Friend
 Private
 Protected Friend
Value Required Parameter containing the new value for the property.

94
Datatype
Required if Option Strict is On. Data type of the value parameter. The data type specified
must be the same as the data type of the property where this Set statement is declared.
Statements
Optional. One or more statements that run when the Set property procedure is called.
End Set Required. Terminates the definition of the Set property procedure.
Remarks
Every property must have a Set property procedure unless the property is marked ReadOnly.
The Set procedure is used to set the value of the property.
Visual Basic automatically calls a property's Set procedure when an assignment statement
provides a value to be stored in the property.
The Set procedure defaults to the access level of its containing property unless user
use access modifier in the Set statement.

Behavior
Returning from a Property Procedure. The Set procedure returns to the calling code,
execution continues following the statement that provided the value to be stored. Set property
procedures can return using either the Return Statement or the Exit Statement. The Exit
Property and Return statements cause an immediate exit from a property procedure. Any
number of Exit Property and Return statements can appear anywhere in the procedure, and
mix Exit Property and Return statements.
Example
The following example uses the Set statement to set the value of a property.
Class propClass
Private propVal As Integer
Property prop1() As Integer
Get
Return propVal
End Get
Set(ByVal value As Integer)
propVal = value
End Set
End Property
End Class

95
5.4. LIST BOXES AND COMBO BOXES
List boxes and combo boxes present a list of choices to the user. By default, the
choices are displayed vertically in a single column, although user can also set up multiple
columns. If the number of items exceeds it can be displayed in the combo box or list box,
scroll bars automatically appear on the control. The user can then scroll up and down or left
to right through the list.
Single-column list box

A combo box control combines the features of a text box and a list box. This control
allows the user to select either by typing text into the combo box or by selecting an item
from its list.
Combo box

In contrast to some other controls that contain a single value; for example the label's
Caption property or the text box's Text property, list boxes and combo boxes contain
multiple values or a collection of values. They have built-in methods for adding, removing
and retrieving values from their collections at run time. To add several items to a list box
named List1, write the following code .
List1.AddItem "Paris"
List1.AddItem "New York"
List1.AddItem "San Francisco"
List boxes and combo boxes are an effective way to present a large number of choices to
the user in a limited amount of space.

96
5.5. THE TabStrip CONTROL
A TabStrip control is like the dividers in a notebook or the labels on a group of file
folders. By using a TabStrip control, user can define multiple pages for the same area of a
window or dialog box in application.
The control consists of one or more Tab objects in a Tabs collection. At both design
time and run time, user can affect the Tab object's appearance by setting properties. User can
also add and remove tabs using the Properties Page of the TabStrip control at design time, or
add and remove Tab objects at run time using methods.
The Style property determines whether the TabStrip control looks like push buttons
(Buttons) or notebook tabs (Tabs). At design time put a TabStrip control on a form, it has one
notebook tab. If the Style property is set to tabTabs, then there will be a border around the
TabStrip control's internal area. The Style property is set to tabButtons, no border is
displayed around the internal area of the control, however, that area still exists.
To set the overall size of the TabStrip control, use its drag handles and/or set the Top,
Left, Height, and Width properties. Based on the control's overall size at run time, Visual
Basic automatically determines the size and position of the internal area and returns the
Client-coordinate properties – ClientLeft, ClientTop, ClientHeight, and ClientWidth. The
MultiRow property determines whether the control can have more than one row of tabs, the
TabWidthStyle property determines the appearance of each row, and, if TabWidthStyle is set
to tabFixed, use the TabFixedHeight and TabFixedWidth properties to set the same height
and width for all tabs in the TabStrip control.

The TabStrip control is not a container.


To contain the actual pages and their objects, use Frame controls or other containers
that match the size of the internal area which is shared by all Tab objects in the control. If use
a control array for the container, it can associate each item in the array with a specific Tab
object, as in the following example:
Option Explicit
Private mintCurFrame As Integer' Current Frame visible
Private Sub Tabstrip1_Click()
If Tabstrip1.SelectedItem.Index = mintCurFrame _
Then Exit Sub ' No need to change frame.
' Otherwise, hide old frame, show new.
Frame1(Tabstrip1.SelectedItem.Index).Visible = True
Frame1(mintCurFrame).Visible = False
97
' Set mintCurFrame to new value.
mintCurFrame = Tabstrip1.SelectedItem.Index
End Sub
The Tabs property of the TabStrip control is the collection of all the Tab objects. Each
Tab object has properties associated with its current state and appearance.

5.6. MSFLEX GRID CONTROL


One of the most impressive controls of Visual Basic is the MSFlexGrid control. The
MSFlexGrid control is a descendant of theold Grid control. The MSFlexGrid control provides
all the functionality for building spreadsheet applications, just as the RichTextBox control
provides all the functionality for building word processing applications. Once masters its
basic properties, writing spreadsheet- like applications for displaying data will just be a
question of setting its properties.
The MSFlexGrid control is an extremely useful tool for displaying information in a
tabular form. In the figure it looks a lot like a spreadsheet: the first row and column are fixed
and they contain titles, and the rest of the cells contain text (including numbers) or
graphics arranged in rows and columns, which can vary in width and height. The scroll
bars give the user easy access to any part of the control (although all the cells can scroll, the
fixed cells always remain visible).

Despite external similarities, the MSFlexGrid control is not a complete spreadsheet in


the same sense that the TextBox control is not a complete word processor, Although it can be
the basis of a spreadsheet, this is not the purpose for which the MSFlexGrid control was
designed. It is meant to display information in tabular form, but not for data entry.
Most of the properties of this control pertain to the placement of the data and their
appearance; there are no properties or events for the immediate editing of the cells’ contents.
However, it’s not too difficult to take control of the KeyPress event to capture keystrokes and
add data entry capabilities to the control.

98
Basic Properties
The address of a cell is given by its Row and Col properties, whose values start at
0. Row 0 is the fixed title row, and column 0 is the fixed title column.
Grid.Row= 1
Grid.Col = 1
After specify the cell’s address, examine its contents with a statement like:
Cell Value = Grid.Text .
or set its contents with a statement like:
Grid.Text = “January”
This method of reading or setting cell values requires too many statements for such a
simple task, and it’s probably available to be compatible with the old Grid control. The
simplest way to address a cell on the grid is by means of the TextMatrix property, which has
the following syntax :
Grid.TextMatrix(row, col)
The row and col arguments are the cell’s coordinates in the grid. To extract the value of the
first editable cell, use’ a statement like:
Cell Value = Grid.TextMatrix(1, 1)
The names of the months and the corresponding profit figures of the grid shown in
Figure are assigned with the following loop, which is executed from within the Display Data
button’s event handler:
Using the Format String Property
Dim I row As Integer
For I row=1 to 12
Grid.TextMatrix(irow, 1)=MonthNames(irow)
Grid.TextMatrix(irow, 2)=Formats(profit97 (irow),”#, ###”)
Grid.TextMatrix(irow, 3)=Formats(profit96(irow),”#, ###”)
Grid.TextMatrix(irow, 4)=Formats(Grid.TextMatrix(irow, 3)- Grid.TextMatrix(irow, 2))
Grid.TextMatrix(irow, 5=Formats(100* (Grid.TextMatrix(irow, 3) -Grid.TextMatrix(irow,
2))/ Grid.TextMatrix(irow, 2)- ),”#, ###”)&”%”
Next

The array MonthNames holds the names of the months and the arrays Profit 96 and Profit
97 contain the numeric values. Notice that the contents of the last two columns (Gain and
Gain [%]) are calculated.

99
A third way to access the cells of the grid is by means of the TextArray
property, which is similar to the Text Matrix property, but it uses a single index to address
a cell. It has the following syntax: “
Grid.TextArray(cellindex)
To calculate the cellindex argument, which determines the location of the desired cell,
multiply the desired row by the Cols property and add the desired. The following statement
calculates the value of the cellindex arguments row (row) and column (001) number:
cellindex = row * cols + col
The Text Array property is less convenient than the Text Matrix property because to
convert the actual address of the desired cell to a single number, Use the Tex tArray property
to assign values to the grid’s cells if the values are already stored in a one-dimensional array.

5.7. CREATING REPORTS USING CRYSTAL REPORTS


Crystal Report Writer is a report generation tool. It is used to generate simple to
slightly complex reports. CRW is not a product from Microsoft. It is from Segate Software. A
report created using Crystal Reports is accessed from a Visual Basic project using an ActiveX
Control Crystal Report Control. The best part of Crystal Reports is its user friendliness. Even
an end-user will be able to generate a report in a few minutes. It is also powerful enough to
enable application developer to generate moderate to complex reports.

A simple sample report


Generate a report to display the details of all the publishers using PUBLISHERS table
of BIBLIO.MDB. Here are the major steps in creating the report:
 Start CRW and select Tabular Style.
 Select the data to be used in the report
 Arrange the fields
 Preview the report
 Save report
 Run report from Visual Basic Project using ActiveX Control.

Starting CRW
1. Click on Start button

100
2. Select Programs-> Microsoft Visual Studio 6.0 -> Crystal Reports. In which group
crystal reports are placed depends upon the group selection at the time of
installation.
3. If user prompted to enter registration details, cancel it or register and then click on
Ok.
4. The initial screen of Crystal Reports will be displayed.

To create a new Report


Take the following steps to create a new report that displays the details of publishers.
1. Start -> Crystal Reports, select File menu and New option.
2. Crystal Reports displays Create New Report window containing various report
styles.
3. Select Listing type

Create New Report dialog displaying available report styles.


1. Crystal Reports displays another window, if user can select the data file or ODBC
data source to be used to retrieve data.
2. Click on Data File button to get Choose Database File dialog.
3. Select BIBLIO.MDB and either double click on the file or click on Add button.
4. Once tables are listed in Crystal Reports Expert, then click on Done to close Choose
5. Database File dialog.
6. Crystal Reports Expert displays list of tables and the links between the tables in Links
tab.
7. Select Fields tab in the report from PUBLISHERS table.
8. Click on Preview Sample button. Crystal Reports prompts to enter number of records
to be displayed Select First 100 Records radio button and click on Ok.
9. Crystal Reports displays the report.
10. Select Report menu and Zoom option to increase the size of the characters.
11. In Preview mode, Select Design tab at the upper –left corner to get into design mode.
12. Sections in Report-Each report contain a few sections. The number of sections may
vary from report to report.

But the following are the general and common sections.


Section Description
Title Displays the title of the report. Information placed here is displayed
101
Only once at the top of the report.
Page Header This is displayed at the top of each printed page.
Details Data placed here is displayed for each row of the data that report has
Retrieved.
Page Footer Displays the information at the bottom of each printed page.
Summary Displays the information only on the last page of the report.

Hiding/showing a Section
Each section can be hidden or displayed by selecting context menu (popup menu
invoked using right button) and then selecting Hide Section option, when section is
displayed or Show Section option, when section is hidden.

Enhancing the sample report


Let us enhance the sample report as follows:
1. Change format of current date and add text “Date” before the date. Remember date is
automatically placed at the upper left corner.
2. Add a title to report.
3. Get into design mode by selecting Design table before enhancing report.
To change date format:
1. Select date that is placed in Page Header section.
2. Invoke context menu of the field using right button.
3. Select Change Format… option
4. When Format Date dialog is displayed, change Month to March, Day to 01 and Year
to
5. 1999.
6. Select DMY radio button to display date in Day month and year format.
7. Click on Ok to close dialog box.
8. Move date towards right to create space for text ‘Date:’
9. Select Insert -> Text Field
10. Enter Date in text box.
11. Click on Accept button.
12. Then a small rectangle moves along with mouse pointer. Move it on the left of date
and click there. Text “Date:” is placed on the left of date field.
To add a title to report
1. Select Insert-> Text Field
102
2. Enter “Publishers Details” as the text and place the field in Title section.
3. Change the following font attributes for the title using Change Font options of context
menu.
To add lines around headings
1. Select Line tool in toolbar.
2. Drag a line above the headings3. Drag a line below the
headings.
To save report
1. Select File -> Save option
2. When Crystal Reports displays Save As dialog box, enter the name of the report file -
3. PubDet.

5.8. DATA REPORT


The process of obtaining such information is known as creating a data report. There
are two steps to creating a data report. First, to create a Data Environment. This is designed
within Visual Basic and is used to tell the data report what is in the database. Second, create
the Data Report itself. This, too, is done within Visual Basic. The Data Environment and
Data Report files then become part of the Visual Basic project developed as a database
management system.
The Visual Basic 6.0 data report capabilities are vast and using them is a detailed
process. The use of these capabilities is best demonstrated by example i.e Report creation by
building a tabular report for our phone database.

Example - Phone Directory - Building a Data Report


Build a data report that lists all the names and phone numbers in our phone database.
We will do this by first creating a Data Environment, then a Data Report. Reopen the phone
database management project and add data reporting capabilities.
Creating a Data Environment
1. Start a new Standard EXE project.
2. On the Project menu, click Add Data Environment. If this item is not on the menu,
click Components. Click the Designers tab, and choose Data Environment and
click OK.
3. In the Data Environment window, right-click the Connection1 tab and select
Properties. In the Data Link Properties dialog box, choose Microsoft Jet 3.51

103
OLE DB Provider. Click Next to get to the Connection tab. Click the ellipsis
button. Find phone database (mdb) file. Click OK to close the dialog box.
4. Right-click the Connection1 tab and click Rename. Change the name of the tab to
Phone. Right-click this newly named tab and click Add Command to create a
Command1 tab. Right-click this tab and choose Properties. Assign the following
properties:
Command Name - PhoneList
Connection - Phone
DataBase Object - Table
ObjectName - PhoneList
5. Click OK. All this was needed just to connect the environment to our database.
6. Display the properties window and give the data environment a name property of
denPhone. Click File and Save denPhone As. Save the environment in an appropriate
folder. Add this file to our phone database management system. At this point, my data
environment window looks like this (I expanded the PhoneList tab by clicking the +
sign):

Creating a Data Report


Once the Data Environment has been created, and then creates a Data Report. Next
drag things out of the Data Environment onto a form created for the Data Report.
1. On the Project menu, click Add Data Report. If this item is not on the menu, click
Components. Click the Designers tab, and choose Data Report and click OK.
2. Set the following properties for the report:
2. Name - rptPhone
Caption - Phone Directory
DataSource - denPhone (phone data environment - choose, don’t type)
DataMember - PhoneList (the table name - choose don’t type)
104
3. Right-click the Data Report and click Retrieve Structure. This establishes a report
format based on the Data Environment.
4. There are five sections to the data report: a Report Header, a Page Header, a Detail
section, a Page Footer, and a Report Footer. The headers and footers contain
information it printed in the report and on each page. To place information in one of
these regions, right-click the selected region, clicks Add Control, and then chooses the
control. These controls are called data report controls.
5. The Detail section is used to layout the information printed for each record in
database. Now place two field listings (Name, Phone) there. Click on the Name tab in
the Data Environment window and drag it to the Detail section of the Data Report.
Two items should appear: a text box Name and a text box Name (Phone List). The
first text box is heading information. Move this text box into the Page Header section.
The second text box is the actual value for Name from the Phone List table. Line this
text box up under the Name header. Now, drag the Phone tab from the Data
Environment to the Data Report. Adjust the text boxes in the same manner. Our data
report will have page headers Name and Phone. Under these headers, these fields for
each record in our database will be displayed. When done, the form should look as

In this form, resized the labels a bit and added a Report Header. Any space left
in this section will be inserted after each entry.
6. Click File and Save rptPhone As. Save the environment in an appropriate folder.
Now reopen our phone database manager and attach this and the data environment to
that project and add capabilities to display the report.

105
Accessing the Data Report
1. Reopen the phone directory project. Add a command button named cmd Report and
give it a Caption of Show Report. (There may be two tabs in the toolbox, one named
General and one named Data Report.)
2. Now add the data environment and data report files to the project. Click the Project
menu item, and then click Add File. Choose denPhone and click OK. Also add
rptPhone. In Project Window files should be listed under Designers.
3. Use this code in cmdReport_Click:
Private Sub cmdReport_Click()
rptPhone.Show
End Sub
4. This uses the Show method to display the data report.
5. Save the application and run it. Click the Show Report button and this should appear:

106

You might also like