0% found this document useful (0 votes)
16 views

Visual Basic

The document provides an introduction to Visual Basic 6.0 including details about the programming environment, forms, variables, controls, and properties, methods, and events. It describes installing and launching VB6, the integrated development environment components, and basic concepts for working with forms, controls, and objects in VB6.

Uploaded by

tmithunns
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
16 views

Visual Basic

The document provides an introduction to Visual Basic 6.0 including details about the programming environment, forms, variables, controls, and properties, methods, and events. It describes installing and launching VB6, the integrated development environment components, and basic concepts for working with forms, controls, and objects in VB6.

Uploaded by

tmithunns
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 137

VISUAL BASIC

UNIT 1
INTRODUCTION TO VB

Getting Started with VB6, Programming Environment, working with Forms, Developing an
application, Variables, Data types and Modules, procedures and control structures, arrays.
Working with Controls: Creating and using controls, working with control arrays.

Getting started with visual basic 6.0


Introduction to Visual Basic:
Visual Basic is a third-generation event-driven programming language first released by Microsoft in
1991. It evolved from the earlier DOS version called BASIC. BASIC means Beginners' All-purpose
Symbolic Instruction Code. Since then Microsoft has released many versions of Visual Basic, from
Visual Basic 1.0 to the final version Visual Basic 6.0. Visual Basic is a user-friendly programming
language designed for beginners, and it enables anyone to develop GUI window applications easily.

Visual Basic 6.0 Programming Environment:


Visual Basic is initiated by using the
Programs option > Microsoft Visual Basic 6.0 > Visual Basic 6.0
Installation
 First, to run setup as administrator.
 Next, choose custom installation.
 Clear the checkbox for Data Access.
 Finally, click next and wait for the installation to complete.

After installing the vb6 compiler, the icon will appear on your desktop or in your programs menu.
Click on the icon to launch the VB6 compiler. Visual Basic 6.0 will display the following.
The Integrated Development Environment:
One of the most significant changes in Visual Basic 6.0 is the Integrated Development Environment
(IDE). IDE is a term commonly used in the programming world to describe the
Interface and environment that we use 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. The IDE is also commonly referred to as the design
environment, or the program.

The Visual Basic IDE is made up of a number of components


Menu Bar
Tool Bar
Project Explorer
Properties window
Form Layout Window
Toolbox
Form Designer
Object Browser

First finalize the project commercial, educational or recreational value. Next, click on the Standard
EXE icon to go into the actual Visual Basic 6 programming environment. The Visual
Basic 6 Integrated Programming Environment. It consists of the toolbox, the form, the project explorer
and the properties window.
The earlier visual basic version IDE was designed as a Single Document Interface (SDI). In a
Single Document Interface, each window is a free-floating window that is contained within a main
window and can move anywhere on the screen as long as Visual Basic is the current application.
But, in Visual Basic 6.0, the IDE is in a Multiple Document Interface (MDI) format. In this
format, the windows associated with the project will stay within a single container known as the
parent. Code and form-based windows will stay within the main container form.

Menu Bar
This Menu Bar displays the commands that are required to build an application.
The main menu items have sub menu items that can be chosen when needed.
The toolbars in the menu bar provide quick access to the commonly used commands and a
button in the toolbar is clicked once to carry out the action represented by it.

Toolbox
 The Toolbox contains a set of controls that are used to place on a Form at design time thereby
creating the user interface area.
 Additional controls can be included in the toolbox by using the Components menu item on the
Project menu.
Control Description
Pointer Provides a way to move and resize the controls
form
Picture Box Displays icons/bitmaps and metafiles. It
displays text or acts as a visual
container for other controls.
Textbox Used to display message and enter text.
Frame Serves as a visual and functional container for
controls
Command Button Used to carry out the specified action when the
user chooses it.
Checkbox Displays a True/False or Yes/No option.
Option Button Option Button control which is a part of an
option group allows the user to
select only one option even it displays mulitiple
choices.
ListBox Displays a list of items from which a user can
select one.
ComboBox Contains a Textbox and a List Box. This allows
the user to select an ietm from
the dropdown ListBox, or to type in a selection
in the TextBox.
HScrollBar and These controls allow the user to select a value
VScrollBar within the specified range of
Values
Timer Executes the timer events at specified intervals
of time
DriveListBox Displays the valid disk drives and allows the
user to select one of them.
DirListBox Allows the user to select the directories and
paths, which are displayed.
FileListBox Displays a set of files from which a user can
select the desired one.
Shape Used to add shape (rectangle, square or circle)
to a Form
Line Used to draw straight line to the Form
Image Used to display images such as icons, bitmaps and
metafiles. But less
capability than the PictureBox
Data Enables the use to connect to an existing database
and display information
from it.
OLE Used to link or embed an object, display and
manipulate data from other
windows based applications.
Label Displays a text that the user cannot modify or
interact with.

Project Explorer

Docked on the right side of the screen, just under the toolbar, is the Project Explorer window. It
provide a quick reference to the various elements of a project namely form, classes and modules. A
simple project will typically contain one form. It is possible to develop any number of forms for use
in a program, although a program may consist of a single form. In addition to forms, the Project
Explorer window also lists code modules and classes.

Properties Window

The Properties Window is docked under the Project Explorer window.

 The Properties Window exposes the various characteristics of selected objects.


 Each and every form in an application is considered an object.
 Each object in Visual Basic has characteristics such as colour and size. Other characteristics
affect not just the appearance of the object but the way it behaves too.

 A form has properties and any controls placed on it will have properties too.

 All of these properties are displayed in the Properties Window.

Object Browser
The Object Browser allows us to browse through the various properties, events and methods

that are made available to us.

It is accessed by selecting Object Browser from the View menu or pressing the key F2. The

left column of the Object Browser lists the objects and classes that are available in the

projects that are opened and the controls that have been referenced in them.

After an object is picked up from the Classes list, we can see its members (properties,

methods and events) in the right column.

A property is represented by a small icon that has a hand holding a piece of paper. Methods

are denoted by little green blocks, while events are denoted by yellow lightning bolt icon.

Object naming conversions of controls (prefix)


Form – frm Label – lbl TextBox - txt

CommandButton – cmd CheckBox – chk, OptionButton - opt

ComboBox – cbo ListBox – lst Frame - fme


PictureBox – pic Image – img Shape - shp

Line –lin, HScrollBar – hsb VScrollBar – vsb

Visual Basic 6.0 - Properties, Methods and Events


All the controls in the ToolBox except the Pointer are objects in Visual Basic. These objects have
associated properties, methods and events.

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


object such as Size, Color etc. or sometimes the way in which it behaves.

For example, a TextBox accepts properties such as Enabled, Font, MultiLine, Text, Visible,
Width, etc.

Enables property allows the TextBox to be enabled or disabled at run time depending on the
condition set to True or False.

Font property sets a particular font in the TextBox.

MultiLine property allows the TextBox to accept and display multiple lines at run time.

Text property of the TextBox control sets a particular text in the control.

Visible property is used to hide the object at run time.

Width property sets the TextBox to the desired width at design time.

These properties are design-time properties that can be set at the design time by selecting the

Properties Window. But certain properties cannot be set at design time.

Example: The CurrentX and CurrentY properties of a Form cannot be set at the design time.

A method is an action that can be performed on objects. For example, a cat is an object. Its
properties might include long white hair, blue eyes, 3 pounds weight etc. In object-oriented
programming, a method is a connected or built-in procedure, a block of code that can be invoked to
impart some action on a particular object. A method requires an object to provide them with a
context. For example, the word Move has no meaning in Visual Basic, but the statement,

Text1.Move 700, 400 performs a very precise action. The TextBox control has other associated

methods such as Refresh, SetFocus, etc.

The Refresh method enforces a complete repaint of the control or a Form. For example,

Text1.Refresh refreshes the TextBox.


The Setfocus method moves the focus on the control. For Example Text1.SetFocus sets the

focus to TextBox control Text1.

Event Driven Programming


Visual Basic programs are built around events. Events are various things that can happen in a

program.

This will become clearer when studied in contrast to procedural programming.

In procedural languages, an application is written is executed by checking for the program

logically through the program statements.

While in an event driven application, the program statements are executed only when a

particular event calls a specific part of the code that is assigned to the event.

Example: The TextBox control supports various events such as Change, Click, MouseMove and

many more that will be listed in the Properties dropdown list in the code window for the TextBox

control.

The code entered in the Change event fires when there is a change in the contents of the

TextBox

The Click event fires when the TextBox control is clicked.

The MouseMove event fires when the mouse is moved over the TextBox

Working with Forms in Visual Basic 6

The Appearance of Forms


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 following figure illustrates the appearance of a Form


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

Setting the Start-Up Form


A typical application has more than a single Form. When an application runs the main Form is
loaded. By setting the Project properties you can control which Form is to be displayed in the Start-
Up of the application. Following figure illustrates the Project property window.

By default, Visual Basic suggests the name of the first Form created when the project started.

Loading and Unloading Forms


In order to load and unload the forms, Load and Unload statements are used.

Syntax :Load FormName 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, just call the Form's Show method to display it on the desktop.

Showing and Hiding 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 :FormName.Show mode

The FormName variable is the Form's name, and the optional argument mode determines whether the
Form will be Modal or not. It can have one of the following syntax:

* 0-Modeless (default Normal forms, forms interact with the user and the user allowed to switch to
any other Form of the application. Default the mode is set to modeless.

* 1-Modal Modal Forms takes the total control of the application where user cannot switch to any
other Forms in the application unless the Form is closed.

Hiding Forms The Hide method is used to hide a Form. Syntax:FormName.Hide

To hide a Form from within its own code, the following code can be used.

Me.Hide

Forms that are hidden are not unloaded; they remains in the memory and can be displayed instantly
with the Show Method. When a Form is hidden, possible to access its properties and code. Also can
change the settings of its Control Properties or call any Public functions in the Form.

The following is an example illustrates the Show method and Mode statement

* Open a new Project and save the Project

Design the application as shown below


The following code is typed in the Click event of the command buttons

Finding out the difference between Unload and Hide method

The difference between Unload and Hide methods .

Example: Open a new project and save the project. Draw two buttons on the form and name those as
shown above.

In the click event of the Hide button Following code is entered.

Me.Hide

In the click event of the Unload button following code is entered.

Unload Me

Save the project and run the application. To click on Hide button that the Form is invisible but

the application is still running. But when click on Unload button that the application is terminated.
Developing an application:
Two steps are there,

1.Visual programming step-involves designing an application with various tools that come along

with the VB project.

2.Code programming step

Variables in Visual Basic 6


Variables are the memory locations which are used to store values temporarily. A defined
naming strategy has to be followed while naming a variable. These are the rules to follow when
naming elements in VB - variables, constants, controls, procedures, and so on:
 A name must begin with a letter.
 May be as much as 255 characters long (but don't forget that somebody has to type the stuff!).
 Must not contain a space or an embedded period or type-declaration characters used to
specify a data type; these are ! # % $ & @
 Must not be a reserved word (that is part of the code, like Option, for example)
 The dash, although legal, should be avoided because it may be confused with the minus sign.
 Instead of First-name use First_name or FirstName.
There are many ways of declaring variables in Visual Basic. Depending on where the variables are
declared and how they are declared. The different ways of declaring variables in Visual Basic are,
1. Explicit Declaration
2. Using Option Explicit statement
3. 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.
Though this type of declaration is easier for the user, to have more control over the variables,
it is advisable to declare them explicitly. The variables are declared with a Dim statement to name
the variable and its type. The As type clause in the Dim statement allows to define the data type or
object type of the variable. This is called explicit declaration.
Syntax: Dim variable [As Type]
For example,Dim strName As String
Dim int Counter As Integer
Using Option Explicit statement
It may be convenient to declare variables implicitly, but it can lead to errors that may not be
recognized at run time. Example a variable by name int count 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. This is because the intcount variable has been mityped as incont in the right hand
side of the second variable. But Visual Basic does not see this as a mistake and considers it to be new
variable and therefore gives a wrong result. In Visual Basic, to prevent errors of this nature, 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 user can thus
rectify the error on seeing this error message. The Option Explicit statement can be explicitly placed
in the general declaration section of each module using the following steps.
1. Click Options item in the Tools menu
2. Click the Editor tab in the Options dialog box
3. 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 are aware of the variable's existence. A variable is declared in general declaration section
of the Form, and hence is available to all the procedures. Local variables are recognized only in the
procedure in which they are declared. They can be declared with Dim and Static keywords. If we
want a variable to be available to all of the procedures within the same module, or to all the
procedures in an application, a variable is declared with broader scope.

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

Static Variables: Static variables are not reinitialized each time Visual Invokes a procedure and
therefore retains or preserves value even when a procedure ends. To keep track of the number of
times a command button in an application is clicked, a static counter variable has to be declared.
These static variables are also ideal for making controls alternately visible or invisible.

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. The value of a local
variable can be preserved using the Static keyword. The following procedure calculates the running
total by adding new values to the previous values stored in the static variable value.

Function RunningTotal ( )
Static Accumulate
Accumulate = Accumulate + num
RunningTotal = Accumulate
End Function

If the variable Accumulate was declared with Dim instead of static, the previously accumulated
values would not be preserved accross calls to the procedure, and the procedure would return the
same value with which it was called. To make all variables in a procedure static, the Static keyword
is placed at the beginning of the procedure heading as given in the below statement.

Static Function RunningTotal ( )


Example: 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.
Puplic intPermanent As Integer
Private intTemp As Integer
Declaring a variable using the public keyword makes it available throughout the application
even for the other modules. At the module-level there is no difference between Dim and Private, but
is preferred because it makes the code easier to read. Public variables should not be declared within a
procedure. It is in different modules can share the same name and they can be differentiated in code.
Example: If the public integer variable intY is declared in both Form1 and Module1of a project
it can be referred as Form1.intY and Module1.intY.
Public vs Local Variables :
A variable can have the same name and different scope. Example, 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.
Modules:
Code in Visual Basic is stored in the form of modules. The three kind of modules are Form
Modules, Standard Modules and Class Modules. A simple application may contain a single Form,
and the code resides in that Form module itself. As the application grows, additional Forms are added
and there may be a common code to be executed in several Forms. To avoid the duplication of code,
a separate module containing a procedure is created that implements the common code. This is a
standard Module. Class module (.CLS filename extension) are 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 in Visual Basic 6
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. Visual Basic supports a
vast array of data types. Each data type has limits to the kind of information and the minimum and
maximum values it can hold.
1. Numeric:

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

Operators in Visual Basic


Arithmetical Operators
Relational Operators

Logical Operators

Procedures in Visual Basic 6


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.

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.

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

Function Procedures

Functions are like sub procedures, except 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 functions returns a value that indicates the results of the tasks complete
within the function. The following function procedure calculates the third side or hypotenuse of a
right triangle, where A and B are the other two sides. It takes two arguments A and B (of data type
Double) and finally returns the results.

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,
Property Set procedure that sets the references to an object.

Control Structures in Visual Basic 6.0


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.
If...Then selection structure
The If...Then selection structure performs an indicated action only when the condition is True;
otherwise the action is skipped.
Syntax of the If...Then selection
If <condition> Then
statement
End If
e.g.: If average>75 Then
txtGrade.Text = "A"
End If

If...Then...Else selection structure


The If...Then...Else selection structure allows the programmer to specify that a different action
is to be performed when the condition is True than when the condition is False.
Syntax of the If...Then...Else selection
If <condition > Then
statements
Else
statements
End If
e.g.: If average>50 Then
txtGrade.Text = "Pass"
Else
txtGrade.Text = "Fail"
End If
Nested If...Then...Else selection structure
Nested If...Then...Else selection structures test for multiple cases by placing If...Then...Else
selection structures inside If...Then...Else structures.
Syntax of the Nested If...Then...Else selection structure
You can use Nested If either of the methods as shown above
Method 1
If < condition 1 > Then
statements
ElseIf < condition 2 > Then
statements
ElseIf < condition 3 > Then
statements
Else
Statements
End If
Method 2
If < condition 1 > Then
statements
Else
If < condition 2 > Then
statements
Else
If < condition 3 > Then
statements
Else
Statements
End If
End If
EndIf
e.g.: Assume you have to find the grade using nested if and display in a text box
If average > 75 Then
txtGrade.Text = "A"
ElseIf average > 65 Then
txtGrade.Text = "B"
ElseIf average > 55 Then
txtGrade.text = "C"
ElseIf average > 45 Then
txtGrade.Text = "S"
Else
txtGrade.Text = "F"
End If
Select...Case selection structure
Select...Case structure is an alternative to If...Then...ElseIf for selectively executing a single
block of statements from among multiple block of statements. Select...case is more convenient to use
than the If...Else...End If. The following program block illustrate the working of Select...Case.
Syntax of the Select...Case selection structure
Select Case Index
Case 0
Statements
Case 1
Statements
End Select
e.g.: Assume you have to find the grade using select...case and display in the text box
Dim average as Integer
average = txtAverage.Text
Select Case average
Case 100 To 75
txtGrade.Text ="A"
Case 74 To 65
txtGrade.Text ="B"
Case 64 To 55
txtGrade.Text ="C"
Case 54 To 45
txtGrade.Text ="S"
Case 44 To 0
txtGrade.Text ="F"
Case Else
MsgBox "Invalid average marks"
End Select

VB Array - Arrays in Visual Basic 6


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, need to 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.
Each index number in an array is allocated individual memory space and therefore users must
evade declaring arrays of larger size than required.
Possible to 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 occupy space in memory. The programmer specifies the array type and the number of
elements required by the array so that the compiler may reserve the appropriate amount of memory.
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
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
In the above statement, an array of 10 elements is declared but with indexes running from 1 to 6. A
public array can be declared using the keyword Public instead of Dim as shown below.
Public numbers(5) As Integer
Multidimensional Arrays
Arrays can have multiple dimensions. 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.
Tables or arrays that require two indexes to identify a particular element are called two
dimensional arrays.
Multidimensional arrays can have more than two dimensions. Visual Basic supports at least 60
array dimensions, but most people will need to use more than two or three dimensional-arrays.
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. You 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.
Most programs don't use static arrays because programmers rarely know at compile time how many
items you need and also because static arrays can't be resized during execution. Both these issues are
solved by dynamic arrays. Declaring and creating dynamic arrays in two distinct steps.
In general, declaring the array to account for its visibility (for example, at the beginning of a
module if you want to make it visible by all the procedures of the module) using a Dim command
with an empty pair of brackets.
Then you create the array when you actually need it, using a ReDim statement:

' An array defined in a BAS module (with Private scope)


Dim Customers() As String
...
Sub Main()
' Here you create the array.
ReDim Customer(1000) As String
End Sub
If you're creating an array that's local to a procedure, you can do everything with a single ReDim
statement:
Sub PrintReport()
' This array is visible only to the procedure.
ReDim Customers(1000) As String
' ...
End Sub
If you don't specify the lower index of an array, Visual Basic assumes it to be 0, unless an Option
Base 1 statement is placed at the beginning of the module. If you want to explicitly use a lower index
different from 0, use this syntax instead:

ReDim Customers(1 To 1000) As String

Dynamic arrays can be re-created at will, each time with a different number of items. When re-create
a dynamic array, its contents are reset to 0 (or to an empty string) and lose the data it contains. To
resize an array without losing its contents, use the ReDim Preserve command:

ReDim Preserve Customers(2000) As String

When resizing an array, need not change the number of its dimensions nor the type of the
values it contains. Moreover, using ReDim Preserve on a multidimensional array, can resize only its
last dimension:
ReDim Cells(1 To 100, 10) As Integer
...
ReDim Preserve Cells(1 To 100, 20) As Integer ' This works.
ReDim Preserve Cells(1 To 200, 20) As Integer ' This doesn't.
Finally, you can destroy an array using the Erase statement. If the array is dynamic, Visual
Basic releases the memory allocated for its elements (and you can't read or write them any longer); if
the array is static, its elements are set to 0 or to empty strings.
Use the LBound and UBound functions to retrieve the lower and upper indices. If the array
has two or more dimensions, need to pass a second argument to these functions to specify the
dimension you need:
Print LBound(Cells, 1) ' Displays 1, lower index of 1st dimension
Print LBound(Cells) ' Same as above
Print UBound(Cells, 2) ' Displays 20, upper index of 2nd dimension
' Evaluate total number of elements.
NumEls = (UBound(Cells) _ LBound(Cells) + 1) * _
(UBound(Cells, 2) _ LBound(Cells, 2) + 1)
Working with controls in Visual Basic 6
Controls are used to receive user input and display output and has its own set of properties,
methods and events.
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.
They can respond to events initiated by the user or set off by the system. For instance, a code
could be written in a CommandButton 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. For instance, the move method can be used with some controls to change their location
and size.
Most of the controls provide choices to users that can be in the form of OptionButton or
CheckBox controls, ListBox entries or ScrollBars to select a value.
Classification of Controls
Visual Basic cojntrols 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;
MSChart control
The Communications control
The Animation control
The ListView control
An ImageList control
The Multimedia control
The Internet Transfer control
The WinSock control
The TreeView control
The SysInfo control
The Picture Clip control
TabIndex property of Controls
Visual Basic uses the TabIndex property 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
TabIndex for the control that has focus and then it scans through the controls searching for the next
highest TabIndex number. When there are no more controls with higher TabIndex value, Visual
Basic starts all over again with 0 and looks for the first control with TabIndex of 0 or higher that can
accept keyboard input.
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.At run
time, invisible or disabled controls also cannot receive the focus although a TabIndex value is given.
Setting the TabIndex property of controls is compulsory in development environment.
Using TextBox Control In Visual Basic 6
TextBox controls offer a natural way for users to enter a value in your program. For this
reason, they tend to be the most frequently used controls in the majority of Windows applications.
TextBox controls, which have a great many properties and events, are also among the most complex
intrinsic controls.
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 you set the MultilIne property to True, you can set the alignment using the Alignment
property.
The test is left-justified by default. If the MultiLine property is et to False, then setting the Alignment
property has no effect.
Run-Time Properties of a TextBox control
 The SelStart property sets or returns the position of the blinking caret (the insertion point
where the text you type appears).
 The SelLength property returns the number of characters in the portion of text that has been
highlighted by the user, or it returns 0 if there's no highlighted text.
 The SelText property sets or returns the portion of the text that's currently selected, or it
returns an empty string if no text is highlighted.

When you want to append text to a TextBox control, you should use the following code (instead of
using the concatenation operator) to reduce flickering and improve performance:

Text1.SelStart = Len(Text1.Text)

Text1.SelText = StringToBeAdded

One of the typical operations you could find yourself performing with these properties is selecting
the entire contents of a TextBox control. You often do it when the caret enters the field so that the
user can quickly override the existing value with a new one, or start editing it by pressing any arrow
key:

Private Sub Text1_GotFocus()


Text1.SelStart = 0
' A very high value always does the trick.
Text1.SelLength = 9999
End Sub

Always set the SelStart property first and then the SelLength or SelText properties. When you assign
a new value to the SelStart property, the other two are automatically reset to 0 and an empty string
respectively, thus overriding your previous settings.
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
To 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.
Using a Label Control
Most people use Label controls to provide a descriptive caption and possibly an associated hot
key for other controls, such as TextBox, ListBox, and ComboBox, that don't expose the Caption
property Caption is the default property for Label controls. Be careful to set the Label's TabIndex
property so that it's 1 minus the TabIndex property of the companion control. Other useful properties
are BorderStyle(if you want the Label control to appear inside a 3D border) and Alignment (if you
want to align the caption to the right or center it on the control). In most cases, the alignment depends
on how the Label control relates to its companion control: for example, if the Label control is placed
to the left of its companion field, you might want to set its Alignment property to 1-Right Justify.
The value 2-Center is especially useful for standalone Label controls.
If the caption string is a long one, you might want to set the Label's WordWrap property to true so
that it will extend for multiple lines instead of being truncated by the right border of the control.

Alternatively, you might decide to set the AutoSize property to True and let the control
automatically resize itself to accommodate longer caption strings.

If you want to show a character string somewhere on the form but at the same time you don't want
to obscure underlying objects, set the Back Style property to 0-Transparent.

If you're using the Label control to display data read from elsewhere—for example, a database
field or a text file—you should set its Use Mnemonics property to False.

Frame Controls

Frame controls are similar to Label controls in that they can serve as captions for those controls
that don't have their own.

Moreover, Frame controls can also (and often do) behave as containers and host other controls.

In most cases, you only need to drop a Frame control on a form and set its Caption property. If you
want to create a borderless frame, you can set its BorderStyle property to 0-None.

Controls that are contained in the Frame control are said to be child controls. Moving a control at
design time over a Frame control—or over any other container, for that matter—doesn't
automatically make that control a child of the Frame control.

After you create a Frame control, you can create a child control by selecting the child control's
icon in the Toolbox and drawing a new instance inside the Frame's border.

Alternatively, to make an existing control a child of a Frame control, you must select the control,
press Ctrl+X to cut it to the Clipboard, select the Frame control, and press Ctrl+V to paste the control
inside the Frame

Frame controls, like all container controls, have two interesting features. If you move a Frame
control, all the child controls go with it.

If you make a container control disabled or invisible, all its child controls also become disabled or
invisible. You can exploit these features to quickly change the state of a group of related controls.
]CommandButton Controls in VB6

Using CommandButton controls is trivial. Just draw the control on the form's surface, set its Caption
property to a suitable string (adding an & character to associate a hot key with the control if you so
choose), and finished, at least with user-interface issues. To make the button functional, need to write
code in its Click event procedure, as in this fragment:

Private Sub Command1_Click()

' Save data, then unload the current form.

Call SaveDataToDisk

Unload Me

End Sub

Two other properties at design time to modify the behavior of a CommandButton control. Set the
Default property to True if it's the default push button for the form (the button that receives a click
when the user presses the Enter key—usually the OK or Save button).

Similarly, set the Cancel property to True if you want to associate the button with the Escape key.
The only relevant CommandButton's run-time property is Value, which sets or returns the state of the
control (True if pressed, False otherwise). Value is also the default property for this type of control.

Command1.Value = True

The CommandButton control supports the usual set of keyboard and mouse events (KeyDown,
KeyPress, KeyUp, MouseDown, MouseMove, MouseUp, but not the DblClick event) and also the
GotFocus and LostFocus events, but you'll rarely have to write code in the corresponding event
procedures.

Properties of a CommandButton 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 CommandButton.

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

OptionButton Controls in VB6

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

Set an OptionButton control's Caption property to a meaningful string, and change its Alignment
property to make the control right aligned. If the control is the one in its group that's in the selected
state, also set its Valueproperty to True. (The OptionButton's Value property is a Boolean value
because only two states are possible.) Value is the default property for this control.

At run time, typically query the control's Value property to learn which button in its group has been
selected. Let's say you have three OptionButton controls, named optWeekly, optMonthly, and
optYearly. You can test which one has been selected by the user as follows:

If optWeekly.Value Then

' User prefers weekly frequency.

ElseIf optMonthly.Value Then

' User prefers monthly frequency.

ElseIf optYearly.Value Then

' User prefers yearly frequency.

End If
Strictly, avoid the test for the last OptionButton control in its group because all choices are
supposed to be mutually exclusive. But the approach I just showed you increases the code's
readability. A group of OptionButton controls is often hosted in a Frame control. This is necessary
when there are other groups of OptionButton controls on the form.
Example
Open a new Standard EXE project and the save the Form as Option.frm and save the project as
Option.vbp. Design the Form as per the following specifications table.
The application responds to the following events

The change event of the TextBox reads the value and stores it in a form-level numeric
variable.

The click event of optOct button returns curretval in octal.

The click event of the optHex button curerntval in hexadecimal

The click event of the optDec button returns the decimal equivalent of the value held
currentval.

The following code is entered in the general declarations section of the Form.

Dim currentval as variant

The variable is initialized to 0 by default. The change event procedure checks to ascertain the
number system (Octal, Hexadecimal) that is in effect and then reads in the number.

Private Sub Text1_Change()


If optOct.Value = True Then
currentval = Val ("&O" & LTrim (Text1.Text) & "&")
Elseif optDec.value = True Then
currentval = Val (LTrim (Text1.Text) & "&")
Else
currentval = Val ("&H" & LTrim (Text1.Text) & "&")
End if
End Sub
The Val function is used to translate string to a number and can recognize Octal and
Hexadecimal strings. The LTrim function trims the leading blanks in the text. The following
code is entered in the click events of the OptionButton controls.
Private Sub optOct_Click()
Text1.Text = Oct(currentval)
End Sub
Private Sub optHex_Click()
Text1.Text = Hex(currentval)
End Sub
Private Sub optDec_Click()
Text1.Text = Format(currentval)
End Sub
The follwoing code is entered in the click event of the Close button.
Private Sub cmdClose_Click()
Unlod Me
End Sub
The Application is run by pressing F5 or clicking on the Run icon in the tool bar. By pressing the
Exit button the program is terminated.

Using ListBox and ComboBox Controls In Visual Basic 6


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

Theitem argument is a string that represents the text to add to the list

Theindexargument is an integer that indicates where in the list to add the new item. Not giving
the index is not a problem, because by default the index is assigned.

Following is an example to add item to a combo box. The code is typed in the Form_Load event

Private Sub Form_Load()

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.
Selecting an item from a list box

Use listIndex and List properties. It sets the index number of the currently selected item. The first
item in the list is index number 0. If it is 1 no item is selected.Listcount always one more than the
index number of the last item in the list.NewIndex property returns the index of the last item added
to the list.

List1.addItem “Television”

List1.ListIndex=List1.NewIndex

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)

The Simple Combo box displays an edit area with an attached list box always visible
immediately below the edit area. A simple combo box displays the contents of its list all the
time. The user can select an item from the list or type an item in the edit box portion of the
combo box. A scroll bar is displayed beside the list if there are too many items to be displayed in
the list box area.

The Dropdown Combo box first appears as only an edit area with a down arrow button at the
right. The list portion stays hidden until the user clicks the down-arrow button to drop down the
list portion. The user can either select a value from the list or type a value in the edit area. The
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. The difference between Dropdown combo & Dropdown list combo is that the edit area in
the Dropdown list combo is disabled. The user can only select an item and cannot type anything
in the edit area. Anyway this area displays the selected item.

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.


The following event procedures are entered for the TextBox and CommandButton controls.

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

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

Remove button removes the selected item from the list as soon as you pressed the Remove
button. The number of items is decreased in the listbox and the value is displayed in the label.
The code for the clear button clears the listbox when you press it. And the number of items
shown in the label becomes 0.

VB ScrollBar - Using ScrollBar Control In Visual Basic 6 (VB6)

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
default initial value for those two properties is 1, but you'll probably have to change
LargeChange to a higher value. For example, if you have a scroll bar that lets you browse a
portion of text, SmallChange should be 1 (you scroll one line at a time) and LargeChange should
be set to match the number of visible text lines in the window.

The most important run-time property is Value, which always returns the relative position of the
indicator on the scroll bar. By default, the Min value corresponds to the leftmost or upper end of
the control: There are two key events for scrollbar controls: the Change event fires when you
click on the scroll bar arrows or when you drag the indicator; the Scroll event fires while you
drag the indicator.
Working with control arrays:
Control Arrays in Visual Basic 6
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. A control array can be created only at design time, and at
the very minimum at least one control must belong to it. You create a control array following
one of these three methods:
You create a control and then assign a numeric, non-negative value to its Index property; you
have thus created a control array with just one element.
You create two controls of the same class and assign them an identical Name property. Visual
Basic shows a dialog box warning you that there's already a control with that name and asks
whether you want to create a control array. Click on the Yes button.
You select a control on the form, press Ctrl+C to copy it to the clipboard, and then press
Ctrl+V to paste a new instance of the control, which has the same Name property as the original
one. Visual Basic shows the warning mentioned in the previous bullet.
Control arrays are one of the most interesting features of the Visual Basic environment, and
they add a lot of flexibility to your programs:
Controls that belong to the same control array share the same set of event procedures; this
often
dramatically reduces the amount of code you have to write to respond to a user's actions.
You can dynamically add new elements to a control array at run time; in other words, you can
effectively create new controls that didn't exist at design time.
Elements of control arrays consume fewer resources than regular controls and tend to produce
smaller executables. Besides, Visual Basic forms can host up to 256 different control names, but
a control array counts as one against this number. In other words, control arrays let you
effectively overcome this limit.
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.
* Design the form as shown below.
The following variables are declared inside the general declaration
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
'&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 = ""
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
UNIT 2
MENUS IN VB

Menus, Mouse events and Dialog boxes: Mouse events, Dialog boxes, MDI and
Flex grid: MDI, Using the Flex grid control.

Introduction:
Menu Interface:
It offers a convenient and consistent way to group commands and an easy for users to access
them. Visual Basic provides an easy way to create menus with the modal Menu Editor dialog.
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, which can be set both at design time and at run time. At design time, you
can assign the menu item a shortcut key so that your end users don't have to go through the menu
system each time they want to execute a frequent command.
An expanded Menu Editor window.
One of the most annoying defects of the Menu Editor tool is that it doesn't permit you to reuse
the menus you have already written in other applications. The programmer can create menu
control arrays. The Index TextBox specifies the menu's index in the control array.The Menu
Editor dialog also provides several CheckBoxes to control the appearance of the Menu.

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 you see a disabled command in a menu
that means that feature is not available. The Visible checkbox specifies whether the menu is
visible or not. To add commands to the Form's menu bar, enter a caption and a name for each
command. As soon as you start typing the command's caption, it also appears in a new line in the
list at the bottom of the Menu Editor window. To add more commands click Enter and type the
Caption and the Name.

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.
Run the application by pressing F5. You can see that you can select a menu.

Application Standardization includes the structure of your toolbars, menus, and overall look and
feel of your applications. All Windows applications look similar, and yours should be designed
to enable the users to learn the application quickly. For example: Most Windows applications
have a File menu dealing with file-oriented tasks. Imagine how difficult it would be for a new
user to figure out that you have put your printing functionality under a menu called, for example,
Technical Tasks -

> Hardware -> Printers -> Print.

Creating a Menu

1. Click the MenuEditor component at the bottom of the screen. This will allow you to start

entering menu items. Type in Fileand press Enter.

2. Click File, then underneath File where it displays text, as shown in Figure 1, type Open.

3. Repeat the steps to enter the Save, Recent, and Exit items to the File menu.

4. Add a menu item 'Edit' next to File and Add Cut, Copy, and Paste underneath it.

5. Add a Help menu with About, and Online items.

Now that you have the main menu sorted, let's take it a step further and add a submenu to the
Open

menu item. To do this, follow these steps:


1. Click the Open menu item.

2. To the right of the Open menu item, you should see the 'Type Here' section.

3. Enter Text.

4. Underneath the Text menu item.

Adding Alt Key Shortcuts

Alt key shortcut enables you to press the Alt key and then the underlined letter to display the
menu. For example: If you press Alt + F, it should open the File menu. To make a letter in the
menu display underlined and act as an Alt key shortcut, follow these steps:

1. Click the desired Menu item.

2. Open the Properties Window.

3. Add an ampersand in front of the desired letter to be used as a shortcut, added an ampersand
in front of the O in Open.

Adding Keyboard Shortcut Keys to Menus

Shortcut keys are usually a combination of Ctrl and a letter. For example, Ctrl + C is the
keyboard shortcut for Copy and Ctrl + V is the Keyboard shortcut for Paste. To add a keyboard
shortcut key to a menu item, follow these steps:

1. Click the desired Menu Item.

2. Open the Properties Window.

3. Find the Shortcut keys Property.

4. Set the desired Shortcut.


The Shortcut will be displayed next to the Menu item's text.

Adding Icons to Menu Items

To add a small icon next to the Menu Item, follow these easy steps:

1. Click the desired menu item.

2. Open the Properties Window.

3. Select the Icon Property.

Once you click on the button, the Select Resource box will appear. Here, you can select from
already added icons inside your project, or add new items to your project's resources.

Adding a Separator Bar inside the Menu

To Add a Separator bar to your menu, follow these steps:

1. Click the Menu Item that you want to separate from other menu items.

2. When the 'Type Here' text appears, look closely. There is a small drop-down arrow next to it,

as shown in Figure 2.

3. Select Separator from the displayed list.

Opening Files

Add the following Namespace and code to make use of the OpenFileDialog to open a file. The
code is slightly different for the Text and Other file types (according to the menus):
Imports System.IO
Private Sub TextToolStripMenuItem_Click(sender As Object, _
e As EventArgs) Handles TextToolStripMenuItem.Click
OpenFileDialog1.Filter = "*.txt|*.txt"
If OpenFileDialog1.ShowDialog = DialogResult.OK Then
OpenFile(OpenFileDialog1.FileName
Saving a File
SaveFileDialog1.Filter = "TXT Files (*.txt*)|*.txt"
. If SaveFileDialog1.ShowDialog = _
Windows.Forms.DialogResult.OK Then
My.Computer.FileSystem.WriteAllText _
(SaveFileDialog1.FileName, TextBox1.Text, True)

Cut, Copy, and Paste


1. Private Sub CopyToolStripMenuItem_Click(sender As Object, _
2. e As EventArgs) Handles CopyToolStripMenuItem.Click
3.
4. Clipboard.SetText(TextBox1.SelectedText)
5.
6. End Sub
7.
8. Private Sub CutToolStripMenuItem_Click(sender As Object, _
9. e As EventArgs) Handles CutToolStripMenuItem.Click
10.
11. Clipboard.SetText(TextBox1.SelectedText)
12. TextBox1.SelectedText = ""
13.
14. End Sub
15.
16. Private Sub PasteToolStripMenuItem_Click(sender As Object, _
17. e As EventArgs) Handles PasteToolStripMenuItem.Click
18.
19. TextBox1.SelectedText = Clipboard.GetText
20.
21. End Sub
Mouse Events In Visual Basic 6
Visual Basic responds to various mouse events, which are recognized by most
of the controls. The main events are MouseDown, MouseUp and MouseMove.
MouseDown occurs when the user presses any mouse button and MouseUp occurs
when the user releases any mouse button.
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 argumnet
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.
Positioning a control
MouseDown is the commonly used event and it is combined with the move
method to move an Image control to different locations in a Form. 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.
The follwoing 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)
If optCredit = True Then
imgCredit.Move X, Y
Else
imgCash.Move X, Y
End If
End Sub
Run the application by keying in F5. You can notice that when the mouse is
clicked on the form
somewhere, the selected image moves to that clicked location.

Graphical Mouse Application In Visual Basic 6


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)

End If

End Sub

Button value 1 indicates that the left mouse button is clicked. The code written in the
MouseDown event changes the CurrentX and CurrentY to the coordinates where the mouse
button was just clicked.

Run the application. You can notice that when 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

MouseDown and MouseMove.

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) The CurrentX and CurrentY properties are not visible in the
properties window of the Form because it cannot be set at the design time. After using the Line
method to draw a line in a Form, Visual Basic automatically assigns the coordinate of the line's
end point to the CurrentX and CurrentY properties of the Form on which the line is drawn.
MouseMove application

Visual Basic does not generate a MouseMove event for every pixel the mouse moves over and a
limited number of mouse messages are generated per second by the operating environment. The
following application illustrates how often the Form_MouseMove ( ) 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 CommandButton 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

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

Creating Dialog Boxes

A dialog box is simply a form in a program that contains input controls designed to receive
information. To make your programming faster, Visual Basic includes an ActiveX control,
named CommonDialog.

Using the Common Dialog Control

To add the CommonDialog control to the toolbox

1. From the Project menu, click Components.

2. Click the Controls tab.

3. Ensure that the Selected Items Only box is not checked.

4. Place a check mark next to Microsoft Common Dialog Control, and then click OK.

To create a common dialog object on your form

1. In the toolbox, double-click the CommonDialog control.

2. When the common dialog object appears on your form, drag it to an out -of-the-way location.

This table lists the name and purpose of the six standard dialog boxes that the common dialog
object provides and the methods you use to display them:
Common Dialog Object event Procedures

Creating an Open Dialog Box

Creating a Color Dialog Box

Creating an Open Dialog Box

The following code window shows an event procedure named mnuOpenItem_Click. You can
use this event procedure to display an Open dialog box when the user clicks the Open command
on the File menu. The event procedure assumes that you have already created a File menu
containing Open and Close commands and that you want to open Windows metafiles (.wmf).

Private Sub mnuOpenItem_Click()

CommonDialog1.Filter = "Metafiles (*.WMF)|*.WMF"

CommonDialog1.ShowOpen

Image1.Picture = LoadPicture(CommonDialog1.FileName)

mnuCloseItem.Enabled = True

End Sub

Creating a Color Dialog Box

If you need to update the color of a user interface element while your program runs, you can
prompt the user to pick a new color with the Color dialog box displayed by using the Common
Dialog object. The color selections provided by the Color dialog box are controlled by the Flags
property, and the Color dialog box is displayed with the ShowColor method. The event
procedure assumes that you have already created a menu command named TextColor with the
Menu Editor. See the code given below

Private Sub mnuTextColorItem_Click()

CommonDialog1.Flags = &H1&

CommonDialog1.ShowColor

Label1.ForeColor = CommonDialog1.Color

End Sub

EXERCISE: Creating a File Menu and Common Dialog Object Step by Step

In this exercise, you use the Menu Editor to create a File menu with Open, Close , and Exit
commands for your program. You also assign access keys and shortcut keys to the commands,
so you can run them from the keyboard.

To create a File menu


1. Start Visual Basic and open a new, standard Visual Basic application.

2. On the toolbar, click Menu Editor to open the Menu Editor dialog box.

3. In the Caption text box, type &File.

4. In the Name text box, type mnuFile, and then click Next. By placing the & character before
the letter F, you specify F as the menu access key.

To assign access and shortcut keys

1. In the Caption text box, type &Open….

2. In the Name text box, type mnuOpenItem.

3. To indent the selected (highlighted) command, click the right arrow button.

4. In the Shortcut drop-down list, click CTRL+O for a shortcut key, and then click Next.

5. In the Caption text box, type &Close.

6. In the Name text box, type mnuCloseItem.

7. In the Shortcut drop-down list, click CTRL+C for a shortcut key, and then click Next.

8. In the Caption text box, type E&xit.

9. In the Name text box, type mnuExitItem.

10. In the Shortcut drop-down list, click CTRL+X for a shortcut key, and then click OK.

To save your project

1. From the File menu, click Save Project As.

2. Save your form and project to disk under the name “Picture”. Visual Basic will prompt you
for two

file names — one for your form file (Picture.frm), and one for your project file (Picture.vbp).

To create a common dialog object

1. Verify that the CommonDialog control is in your project toolbox. If it isn't, add it now by
using the

Project menu Components command.

2. To add a common dialog object to your form, double-click the CommonDialog control in the

toolbox, and then drag the object to the lower right-hand side of the form.

To create the image object

1. Click the Image control and create a large image object in the middle of your form. When you
run
your program, the image object displays picture files with *.jpg extension on a form.

2. On the form, click Image1. To restore the Properties window to full size, double-click the

Properties window title bar.

If you cannot see the Properties window, click Properties on the toolbar to display it.

3. Click the Stretch property and set it to True.

When you run your program, Stretch makes the metafile fill the entire image object.

4. On the toolbar, click Save Project to save these changes to your program.

To write event procedures

1. In the Project window, click View Code , click the Code window Object drop-down list box,
and

then click mnuOpenItem.

2. In the mnuOpenItem_Click event procedure, type the following code:

CommonDialog1.Filter = "JPEG FILES (*.JPG)|*.JPG"

CommonDialog1.ShowOpen

Image1.Picture = LoadPicture(CommonDialog1.Filename)

mnuCloseItem.Enabled = True

3. In the Object drop-down list box, click mnuCloseItem, and then type the following code:

Image1.Picture = LoadPicture("")

mnuCloseItem.Enabled = False

4. In the Object drop-down list box, click mnuExitItem, and then type End in the event

procedure.

5. On the toolbar, click Save Project to save your changes.

To run the program

1. On the Visual Basic toolbar, click Start.

Visual Basic loads the program and the form with its File menu.

2. From the File menu, click Open.

3. When the Open dialog box appears, load a picture file from your computer.

The picture selected should appear correctly sized in your image object.
4. From the File menu, click Close.

Your program should clear the picture file and turn off the Close command.

5. Try using the access keys and the shortcut keys to run the File menu commands. When you’re

finished, click the File menu Exit command.

The Multiple Document Interface (MDI) in Visual Basic 6

The Multiple Document Interface (MDI) was designed to simplify the exchange of information
among documents, all under the same roof. With the main application, you can maintain
multiple open windows, but not multiple copies of the application. Data exchange is easier when
you can view and compare many documents simultaneously.

An MDI application must have at least two Form, the parent Form and one or more child Forms.
Each of these Forms has certain properties. There can be many child forms contained within the
parent Form, but there can be only one parent Form. The parent Form may not contain any
controls. While the parent Form is open in design mode, the icons on the ToolBox are not
displayed, but you can't place any controls on the Form. The parent Form can, and usually has its
own menu.

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

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

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.

And as soon as you click MDI Open you can notice that the main menu of the MDI Form is

replaced with the Menu of the Child Form. The reason for this behavior should be obvious. The

operation available through the MDI Form are quite different from the operations of the child

window. Moreover, each child Form shouldn't have it's own menu.
Using the FlexGrid control

Using Microsoft's FlexGrid control (MSFLXGRD.OCX) you can create utilities to

display, filter, edit, validate and update your data. For example, such utilities could include:

1. data entry & validation

2. high level reports

3. ported spreadsheet macro applications retaining cell layout & format

Most of the other grid objects are specifically designed for data binding, whereas the

FlexGrid has many collections of properties, methods and events that lend themselves to

several environments in addition to just data-binding.

One of the most powerful applications of the FlexGrid is in managing data from

database tables in an unbound state. That is, to populate & edit the FlexGrid and write the

contents back to the database in code. This may seem a pointless exercise as objects such

Microsoft's Data Bound Grid Control are written specifically for this purpose, except these

grids simply display the contents of a recordset, record by record, field by field. Whereas the

FlexGid can populate the grid in any manner, examples of which are:

1. separating grouped data with blank rows/columns,

2. adding sub/grand-total rows/columns,

3. changing the colour of the cell background or text in individual or multiple cells,

4. reacting to the state of the data, e.g. highlighting negative values,

5. validating entered data e.g., numeric values, positive values, permitted date ranges etc.

That said, most of the functionality found in these third party grids can be accessed

with FlexGrids .

Using the FlexGrid

To use the FlexGrid in your application, right click the Toolbox or select the Project menu and

choose 'Components'.
Select Microsoft FlexGrid Control and copy the control onto your form from the Toolbox. The
default FlexGrid will appear on the form.

There are a few simple formatting tips to improve to appearance of the FlexGrid:

First of all, it's good practice to determine the initial number of grid rows and columns using
the Row and Col properties respectively. Then set the number of fixed rows and columns with
the FixedRow and FixedCol properties respectively.

To ensure the columns are the correct width to fit inside to FlexGrid, first set a variable to the
width of the FlexGrid, allowing for a vertical Scrollbar width. Then use this variable to resize to
individual column widths, by dividing it by the number of columns.

The height of individual rows can be changed to accommodate multi-line headings. This is
done by simply multiplying the appropriate row height by a scaling factor, in this case two, to
double the height.

When increasing the size of a row height, to make sure text uses the extra available space, use
the WordWrap property the ensure text continues on the the next cell line.

Regarding writing text to the grid there are two main methods. The first one is using the
Additem method, this writes text to an entire row in one action and is therefore useful for adding
headings. The vbTab constant is used to distinguish adjacent cells.
The second method to populate grid cells with text is to directly address individual cells and
using the TextMatrix or Text property and set the cell's text.

An example of grid initialisation code would be as follows:

Dim lngWidth As Long

Dim intLoopCount As Integer

Const SCROLL_BAR_WIDTH = 320

With MSFlexGrid

lngWidth = .Width - SCROLL_BAR_WIDTH

.Cols = 4

.FixedCols = 1

.Rows = 0

.AddItem vbTab & "Heading Text One" & vbTab & _

"Heading Text Two" & vbTab & "Heading Text Three" & _

vbTab & "Heading Text Four"

.Rows = 12

.FixedRows = 1

.WordWrap = True

.RowHeight(0) = .RowHeight(0) * 2

.ColWidth(0) = lngWidth / 4

.ColWidth(1) = lngWidth / 4

.ColWidth(2) = lngWidth / 4

.ColWidth(3) = lngWidth / 4

For intLoopCount = 1 To (.Rows - 1)

TextMatrix(intLoopCount, 0) = "Item " & intLoopCount

Next intLoopCount

End With

The initialised FlexGrid should appear on the form.


Changing Cell Background & Foreground Colours

The ability to change the individual cell background colour and cell font colour is useful for
highlighting particular data states, e.g. values exceeding a specified ceiling, negative values,
cells where data cannot be entered etc. To set the background colour of a cell, first reference the
cell by setting the Row and Col properties to the appropriate cell, then use the CellBackColor
property to set its colour. Similarly use the CellForeColor property to change the colour of the
text displayed in a cell. Examples of available colours are found in the FlexGrid's Properties
Window under any of the colour properties, especially the palette tab as this displays a wider
range of colours. To set a range of cells to a selected colour each cell must be referenced in turn,
unless all the cells in the grid are to have their colour set to the same colour in which case the
BackColor and ForeColor property can be used which sets the entire grid's colour.
UNIT 3
ODBC AND DATA ACCESS OBJECTS

ODBC and Data Access Objects: Data Access Options, ODBC, Remote data objects, ActiveX
EXE and ActiveX DLL: Introduction, Creating an ActiveX EXE Component, Creating
ActiveX DLL Component.

Introduction
Data Access Options
Visual Basic provides variety of options when it comes to accessing the data stored in the
database.
Find all options below:
(i) Data Access Objects (DAO):It communicates with the Microsoft access and other ODBC
compliant data sources through the JET engine.
(ii) ODBC Direct :It allows accessing ODBC data sources through the RDO (Remote Data
Objects) and DAO objects bypassing the JET database engine.
(iii) Data Control:It binds data-aware controls to Microsoft access or other ODBC data sources.
(iv) Remote Data Objects (RDO):It provides a frame work for using code to create and
manipulate components of a remote ODBC database system.
(v) Remote Database Control:It binds to controls to an ODBC remote database.
(vi) Open Database Connectivity(ODBC):This is an API call interface to the ODBC libraries
and drivers to provide data access to Oracle and other databases that provide an ODBC driver.
(vii)Visual Basic Library for SQL Server(VBSQL): It is an implementation of the DB library
API and it provides access to SQL Server through a VB application.
(viii) Active Data Objects(ADO):It is a programming model designed to provide a common
bridge between different databases, file systems and e-mail servers.
Data access objects
A Data Access Object is a collection of object classes that model the structure of a Relational
Database System. They provide properties and methods that allow the user to accomplish all the
operations like creating a database, defining tables, navigating and querying a database. Visual
Basic supports data access objects such as DB Engine, Workspace, Database, TableDef, Field,
Index and Record set objects.
The following figure represents the Data Access Objects Hierarchy:

DB Engine: Top level database object and corresponds to the Jet database engine used to set
database engine system parameters and default workspace.

Workspace: Supports simultaneous transactions as acts as a container for open database. A


default workspace Workspaces (a) is created when the DAO is referenced in the language at run
time.

It is always available never closed or removed.

Database Object: It corresponds to a Jet native or external database or a direct ODBC


connection. It is used to define the database’s table, relations and stored queries and to open
record set objects.

Table Def: It corresponds to a stored table definition. It represents the definition of a table in the
current database or an attached table in the external database.

Query Def : It is a stored query definition, which is a precompiled SQL statement.

Recordset: This object corresponds to a cursored view into a database table. It stores rows of
data in buffer and points to one row of data at a time called current record.

Field Object: Field Object corresponds to a column of datatype.

Index Object: It is a stored index associated with Table def or table type Recordset object.

Parameter Object : It represents a parameter associated with a Query Def object created from a
parameter query.

User Object : It is used to define and enforce database security.

Group : Collection of users with similar access rights.

Relation : This object represents a relationship between files in tables or queries. The DBEngine
enforces certain update and delete conditions to maintain referential integrity.

Property Object: It represents a built-in or user defined characteristic of a data access object.
Document Object : It includes information about one instance of a type of object.

Container Object : It holds information describing the objects that are grouped into that
container.

Accessing and navigating databases:

To work with data access objects, reference has to be set to the appropriate DAO library. The
two

DAO libraries supported by Visual Basic 6.0 are:

Microsoft DAO 3.51 Object Library

Microsoft DAO 2.5/3.51 Compatibility Layer

Steps to be followed to set a reference to the DAO library:

Select references from the Project Menu

Select the DAO 3.51 object library

Click on OK.

Opening a Database

To open an existing database, the openDatabase method of the Workspace Object is used.

Syntax: OpenDatabase(dbname,[options], [readonly], [connect])

Example: Dim db as Database

Set db=OpenDatabase(“employee_details”)

Variable db represents the Database object employee_details database. Code to use the database
is

Set db = OpenDatabase(“employee_details”,True)

The statement to open the database in the readonly mode is

Set db=OpenDatabase(“employee_details”,False,True)

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

TableTypeRecordset: Fastest type of Recordsets representing a single table used to add, change
or delete records.

DynasetTypeRecordset:It represents a table, or attached tables or the results of queries.


Dynaset enables us to update data from more than one table.

Snapshot Type Recordset:Snapshot can refer to any table, attached table or query. It cannot be
updated and does not reflect any changes made by users.
Dynamic Type Recordset:It represents a query result set from one or more table. We can add,
change or delete records from row-returning query. It is only available in ODBC Direct
Workspaces.

Forward Only Type Recordset: This is identical to snapshot recordset except that we can only
scroll forward through its records.

Creating a Recordset: OpenRecordset method is used to open a Recordset and create a


Recordset variable.

Example: The following code creates a read only Recordset for the table employee

Dim rs as Recordset

Set rs= db.OpenRecordset(“employee”,dbOpentable,dbReadOnly)

Variable db represents Database object

dbOpenTable specifies the Recordset type

Navigating a Recordset:

MoveFirstmethod ---> Moves to the first row in the Recordset

MoveNext method ---> Moves to the next row in the Recordset

MovePrevious method ---> Moves to the previous row in the Recordset

MoveLast method ---> Moves to the Last row in the Recordset

Usinhg BOF and EOF to navigate through Recordsets:

The EOF(End of File) property is True when the user moves beyond the last record in the
recordset.

The BOF(Beginning of File) property is True when the user has moved to a position before the
first record in the recordset.

Modifying and Deleting Records:

Edit Method ---> Used to edit the current record.

Update Method ---> Used to save the necessary changes made to the record.

AddNewMethod ---> Used to create a new record.

Delete Method ---> used to delete an existing record in the dynaset or table type recordset.

Finding Methods:

It is used to locate a record.

FindFirst ---> Finds first record satisfying the specified criteria.


Find Last ---> Finds Last record satisfying the specified criteria.

Find Next ---> Finds next record satisfying the specified criteria.

Find Previous ---> Finds Previous record searches backward.

No Match Property ---> set to true if no match is found.

Performing Indexed Searches Using the Seek Method:

Seek Method ---> Used to locate a record in a table type recordset.

Dynasets and Snapshots cannot use the Seek Method.

Manipulating Stored Queries Using TheQueryDef Object:

Query Def object contains information about a stored SQL Query Def Objects runs faster than
SQL

Query. Two basic methods to work with QueryDefs

Execute Method ---> Perform action queries.

Open Recordset Method ---> Used to retrieve data from the tables.

Creating Parameterized Queries Using The Parameter Object:

Parameter Query ---> Created using the parameters collection of a QueryDef object.

TableDef Data Object :It contains detailed definition about each data table in the database.The
following five methods are available to use with this object:

OpenRecordset ---> Used to open a table – Dynaset or Snapshot Recordset from the
TableDef object.

Refresh Link ---> To update and refresh any attached table links for the TableDef object.

CreateProperty---> Used to create and store a user-defined property.

CreateIndex ---> Used to add an index to the TableDef object.

CreateField ---> Used to add a new field to an existing TableDef object.

Modifying and Deleting Existing Tables:New fields can be added or existing fields can be
deleted using the Append or Delete methods respectively on the TableDef object.

Creating a table in Oracle Using SQL*PLUS:

Create table<tablename>(column_name1 datatype, column_name2 datatype,…)

Inserting Values in a Table

Insert Command is used to add rows to a table.

Syntax: Insert into <tablename> values<data_list>


Open database connectivity(odbc)

Open database connectivity (odbc) is a Windows technology that lets a database client
application connect to an external database. To use ODBC client machine should be configured
with ODBC driver. The destination of the database, login id and password should also be
configured. This is called a Data Source. It is possible to access heterogeneous data from client.

ODBC has three parts. They are

A Driver manager

One or more drivers

One or more data sources.

Creating an ODBC Data Source

ODBC drivers must be installed before using.

Create Data Source Name using control panel.

Steps to set up an Oracle Data Source:

Double click on the ODBC configuration option under control panel

A list of ODBC data sources is displayed.

Create a new data source using the ODBC driver for Oracle

Select the Add button to add a new ODBC data source. Select the ODBC driver for Oracle
from the

list of ODBC drivers displayed in the system.

Steps for creating an odbc data source name on the client

Double click on the Oracle ODBC driver. The Oracle DSN configuration dialog box is
displayed. This screen gathers login and connection information.

Enter the Data Source Name as XYZ company in the Data Source Name box. Enter the
description as xyz company database in the Description box. Provide the user name as user1 and
the server name as server1.

Click the Next button to continue and display the screen that allows us to choose more options

Click the select button that allows us to choose appropriate translators.


Click the drivers tab to view the list of drivers installed in the system.

Using odbc with dao

The properties and methods of DAO can be used in conjunction with the ODBC type database.
OpenDatabase – This method creates a connection between the application and the ODBC
database and assigns it to a database type object.

Syntax:

Dim db as Database

Set db = OpenDatabase(“<Data Source Name>”, <dbdriverpromptinformation>,<Readonly>,

“ODBC;UID=<User ID; PWD=<Password>”)

db is a variable that represents the Database object.

Example : To view the details of all the employees in a company named XYZ company

Add a new Form to the project and set its caption as Emp Details.

Add controls -- six label controls, six textboxes and nine command buttons to the form.

Dim dbAs Database

Dim rsAsRecordset

Write the following code in the Form_Load event procedure.

Private Sub Form_Load()

Set db= OpenDatabase (“XYZCompany”, False,F alse,_”ODBC; UID=USER1; PWD=SSI;

DSN=XYZCompany)

Set rs=db.OpenRecordset(“select * from emp”)

Txt_empno.Text=rs.Fields(“Emp_no”)

Txt_name.Text=rs.Fields(“Emp_name”)

Txt_sal.Text=rs.Fields(“Sal”)

Txt_date.Text=rs.Fields(“Joindate”)

Txt_dept.Text=rs.Fields(“Dept_no”)

Txt_desig.Text=rs.Fields(“Desig”)

End Sub

To move to the First, Last,Previous and Next records , the code has to be attached in the Click
event of the
Command buttons cmdFirst, cmdLast, cmdPrev and cmdNext.

Private Sub cmdFirst_Click()

rs.MoveFirst

MoveFields

End Sub

Private Sub cmdLast_Click()

rs.MoveLast

MoveFields

End Sub

Private Sub cmdPrev_Click()

rs.MovePrevious

If rs.BOF Then

rs.MoveFirst

End If

MoveFields

End Sub

Private Sub cmdNext_Click()

rs.MoveNext

If rs.EOF Then

rs.MoveLast

End If

MoveFields

End Sub

To add a new record the following code is added in the click event of cmdAdd command button

Private Sub cmdAdd_Click()

Txt_empno.Text=””

Txt_name.Text=””

Txt_sal.Text=””
Txt_date.Text=””

Txt_dept.Text=””

Txt_desig.Text=””

rs.AddNew

End Sub

To save the changes after entering the details the following code is added in the click event of
cmdSave

command button.

Private Sub cmdSave_Click()

If rs.EditMode=dbEditAdd Then

rs(“Emp_no”)=Txt_empno.Text

rs(“Emp_name”)=Txt_name.Text

rs(“sal”)=Txt_sal.Text

rs(“Joinmdate”)=Txt_date.Text

rs(“Dept_no”)=Txt_dept.Text

rs(“Desig”)=Txt_desig.Text

End If

rs.Update

End Sub

To modify or change any fields in a record add the following code in the click event of
cmdModify command

button

Private Sub cmdModify_Click()

If rs.EditMode=dbEditNone Then

rs.Edit

End If

End Sub

To delete a record from a database using Delete method as below:

Private Sub cmdDelete_Click()


rs.Delete

rs.MoveNext

If rs.EOF Then

rs.MoveLast

End If

MoveFields

End Sub

Create a Sub procedure called MoveFields as below to assign the values of the Recordset to the
text property

of the textboxes.

Public Sub MoveFields()

Txt_empno=rs(“Emp_no”)

Txt_name=rs(“Emp_name”)

Txt_sal=rs(“sal”)

Txt_date=rs(“Hiredate”)

Txt_dept=rs(“Dept_no”)

Txt_Desig=rs(“Desig”)

End Sub

Finding a specific record

A particular record from a table can also be viewed using Find methods. FindFirst method finds
the first record satisfying the specified criteria, searching forward from the beginning of the
Recordset. FindLast method finds the last record satisfying the specified criteria, searching
backward from the end of the Recordset. FindPrevious method finds the previous record
satisfying the specified criteria, searching backward from the current record. FindNext method
finds the first record satisfying the specified criteria, searching forward from the current record.

Example:

Dim mydbAs Database, MySet As Recordset, MyWs As Workspace

Dim Total As Long

Private Sub Form_Load ()

Set mydb=OpenDatabase(“XYZCompany”, False, False, _


“ODBC;UID=USER1;PWD=SSI;DSN=XYZCompany)

Set MySet=mydb.OpenRecordset(“Emp”, dbOpenDynaset)

End Sub

Private Sub CmdFindFirst_Click()

Dim a As String

a=Text1.Text

MySet.FindFirst “[emp_no]=” &CInt(Text1.Text)

If MySet.NoMatch Then

MsgBox “The Given Record is not Found”

Else

MySet.Edit

Text1.Text=MySet(0)

Text2.Text=MySet(1)

Text3.Text=MySet(2)

Text4.Text=MySet(3)

Text5.Text=MySet(4)

End If

End Sub

Adding a field to a table

A field can be added to an existing table of a database at run time by appending a field to an
existing collection

of fields.

Example:

Dim newTdAsTableDef

Dim newFldAs Field

Set myDb=OpenDatabase(“XYZCompany”, False, False, “ODBC;UID=sa;PWD=”)


Set newTd=myDb.TableDefs(“emp”)

Set newFld=newTd.CreateField(“Address”, dbText,30)

newTd.Fields.AppendnewFld

MsgBox “Field Added”

myDb.Close

Adding an index to a table

The Append method can be used to add a new Index object.

Dim dbAs Database

Dim td AsTableDef

Dim indAs Index

Private Sub Form_Load()

Set db=Open Database(“XYZCompany”, False , False, _

“ODBC;UID=USER1;PWD=SSI;DSN=XYZCompany)

Set td=db.TableDefs(“emp”)

Set ind=td.CreateIndex(“NameIndex”)

ind.Fields.Appendtd.CreateField(“emp_name”)

td.Indexes.Appendind

MsgBox “Index Created”

End Sub

Deleting index from a table

Deleting an Index is similar to the way a table is deleted.

Dim dbAs Database

Dim td AsTableDef

Private Sub Form_Load()

Set db=OpenDatabase(“XYZCompany”, False, False, _

“ODBC;UID=USER1;PWD=SSI;DSN=XYZCompany)

Set td=db.TableDefs(“emp”)

Td.Indexes.Delete “NameIndex”
MsgBox “Index Deleted”

End Sub

db.TableDefs(“Emp”).Indexes.Delete “empno_index”

Using transactions to control changes

Visual Basic supports three transaction methods such as BeginTrans, CommitTrans and
Rollback. They are:

BeginTrans --->Method to begin a new transaction.

CommitTrans --->Method that commits all changes till the most recent invoking of the
BeginTrans method

Rollback --->This method cancel all changes till the most recent invoking of the BeginTrans
method.

Example:Function changeDeptno()

Dim dbAs Database, myWs As Workspace, rs As Recordset

Set myWs= DBEngine.Workspaces(0)

Set db= myWs.OpenDatabase(“XYZCompany”,False,False._

“ODBC;UID=USER1;PWD=SSI;DSN=XYZCompany)

Set rs = db.OpenRecordset(“Emp”,dbOpenDynaset)

myWs.BeginTrans

Do Until rs.EOF

If rs(“dept_no”) =9 Then

rs.Edit

rs(“dept_no”) = 10 Then

rs.Update

End If

rs.MoveNext

Loop

If MsgBox(“Save all changes?”, vbQuestion + vbYesNo, “Save Changes”) = vbYes

Then

myWs.CommitTrans
Else

myWs.Rollback

End If

rs.Close

End Function

Accessing odbc databases using data control

A Data control is used to create applications that display, edit and update information from
numerous

types of existing databases. In addition, data control allows the user to access and manipulate
external Open

Database Connectivity(ODBC) databases such as Microsoft SQL Server and Oracle.The Data
Control

implements data access by using the Microsoft Jet database engine. It can be added the form and
perform the

following tasks without writing any code:

Connect to a local or external database

Open a specified database

Attach data fields to bound controls, where values can be displayed and changed

Add new records or update a database with the data displayed on the bound controls.

Close the database.

Using dbgrid control

The dbgrid control is a spreadsheet-like bound control that displays a series of rows and columns
representing rows and fields from a recordset object. the dbgrid control’s datasource property
can be set to a data control so that the control is automatically filled and its column headers are
set automatically from a data control’s recordset object. it can hold text or picture values but not
linked or embedded objects. accessing client server data source odbcdirect can be used to
access client server data by enabling without loading jet database engine. to set up a vb
application that tests the oracle data source name, the following steps have to be followed. create
a standard exe project.

from the project components menu, add a reference to the microsoft data bound grid control.

the dbgrid control appears in the project’s toolbox. add an instance of the dbgrid control and a
standard

data control to the project’s form.


change the data control’s defaulttype property to 1-use odbc.

in the data control’s connect property, enter the following text

odbc;uid=user1;pwd=ssi;dsn=xyzcompany

in the data control’s recordsource property, enter the following sql string.

select * from emp set the dbgrid control’s datasource property to data1

To add new employee details attach the following code in the click event of Add command button:

Private Sub Add_Click ()

Data1.Recordset. AddNew

End Sub

To delete an employee from the database include the following code in the click event of delete
command:

Private Sub Delete_Click()

Data1,Recordset.Delete
Data1,Recordset.MoveNext

If Data1.Recordset.EOF Then

Data1,Recordset.MoveLast

End If

End Sub

To save the changes made to the record, add the following code in the click event of update
command :

Private Sub Update_Click ()

Data1.UpdateRecord

End Sub

To cancel the changes made to the data , the following code is attached to the cancel command :

Private Sub Cancel_Click()

Data1.UpdateControls

End Sub

Using the remote data control

The Remote Data Control is another way for accessing remote data in Visual Basic Application.

To use a Remote Data Control the following procedure is used:

In Visual Basic, select Components item from Project menu.

From the list of Components, select Microsoft Remote Data Control 2.0. Also add a reference to
the

Microsoft Data Bound Grid Control.

Click Ok. The Remote Data and Databound Grid controls appear in the Visual Basic toolbox.

Click the Remote Data Control from the toolbox and add it to the form.

Also add a DataBound Grid Control to the form.

Change the Remote Data Control’s UserName property to the user’s choice.

The Remote Data Control’s Password property is changed as per user’s choice.

Set the Remote Data Control’s SQL property to select * from emp.

In the DataSourceName property of the Remote Data Control, select the DSN namely XYZ
company
for the SQL Server database.

Set the DBGrid control’s DataSource property to MSRDC1 which is the name of the Remote
Data

Control.

Press F5 to run the application. The application retrieves the contents of the table emp and displays
it in the

data grid.

Remote data objects

The basic idea behind Remote Data Objects is to give the user an object-oriented, implementation –

independent way of acquiring access to client server data. The following are the steps to get started
with

Remote Data Objects:

Select References from Visual Basic’s Project Menu. The References dialog appears.

Select Microsoft Remote Data Object 2.0 from the list.

Click Ok. Remote Data Objects will be available now in the application.

The RDO consists of objects and collections that form a framework for manipulating the
components

of a remote ODBC database system. The relationships among objects and collections represent the

logical structure of the database system.

REMOTE DATA OBJECTS HIERARCHY

rdoEngine: object is the top-level object used to access all remote data and it handles all the
requests. rdoEngine creates one or more rdoEnvironment object which contains information about
current environment for data connections.

rdoEnvironment: objects can create rdoConnectionobjects.This object contains the details needed
to establish a connection between an application and the remote data source. Each rdoConnection
can create one or more rdoResultset objects. This object contains a direct reference to all the rows
and columns in the dataset and it creates a collection of records after a connection is made to the
remote data source. The complete hierarchy of Remote Data Objects is shown in the following
figure.

\
The rdoTable object has information about each column in the base table that exists on the
remote

data source.

The rdoColumn object has the information about each column in the rdoTable or rdoResultset
object.

The rdoQuery object provides a method for creating and excuting defined queries or views on
the

remote data source. rdoQuery objects are accessed through the rdoQueries collection object.

The rdoParameter object manages the parameters that are passed during the processing of
queries.

More than one rdoParameter object can be defined for each rdoQuery object.

To access a database through RDO the steps to be followed are:

The user must create an rdoConnection object to the database

After the connection is established and the database is opened, the user can execute SQL
statements

and store procedures against the database.

The results are returned in a rdoResultset object. With the rdoResultset object’s methods and

properties, the user can access the records, edit them and save them.

Establishing a connection
Syntax to establish a connection is:

Set connection = environment.OpenConnection(dsName[, prompt[, readonly[, connect[,


options]]]])

OpenConnection method ---> opens a connection to an ODBC data source.

connection --->object expression that evaluates to rdoConnection object.

Environment ---> object expression that evaluates to rdoEnvironment object.

dsName --->ODBC data source name.

prompt ---> Variant or Constant that determines the way of operation.

Readonly---> Boolean Value

connect ---> String expression used to pass arguments to the ODBC driver manager for opening the

database.

Options ---> Variant or Constant that determines how the operation is carried out.

Executing sql statements

OpenResultSet method of the Connection object is used to run queries against the database.

Syntax

Set rs= rdoConn.OpenResultSet(name, type, locktype, option)

name ---> string specifying the source for new rdoResultSet object. It can specify the name of a

rdoTable or rdoquery or sql statement.

type ---> specifies the type of cursor and can have anyone of the following values:

rdOpenForwardOnly – opens a forward only type resultset.

rdOpenKeyset – opens a keyset-type resultset.

rdOpenDynamic – opens a dynamic type resultset.

rdOpenStatic – opens a static type resultset.

locktype ---> determines the way in which other users can access the data in the resultset.and it can

take the following values:

rdConcurReadOnly --->used when the user opens the resultsets that will not be updated.

rdConcurLock ---> Locks the page that contains the record and frees it only after the application

moves to a record in another page.


rdConcurRowVer--->Locks the entire page containing the record being edited, but only while the

record is being updated.

rdConcurValues ---> Optimistic concurrency based on row values.

rdConcurBatch ---> Optimistic concurrency using batch mode updates.

Using rdo to insert, update and delete records

Records can be inserted, existing records can be modified and unwanted records can be deleted
using

RDO objects.

Example: Create a new project called employee details and add the controls as in the figure shown:

Dim envAsrdoEnvironment

Dim cnAsrdoConnection

Dim rsAsrdoResultset

Select the Data Source Name. Use OpenConnection method in the Form_Load event to prompt the
user to

select a DSN name.

Set env=rdoEnvironments(0)

Env.CursorDriver=rdUseOdbc

Set cn=env.OpenConnection(dsname:=””, Prompt:=rdoDriverPrompt, ReadOnly:=False,


Connect:=””)

Call loademp

End Sub

The employee detail sis retrieved using the following sub routine loademp()

Private Sub loademp()

Dim s As String

S=”select * from emp1”


Set rs=cn.OpenResultset(Name:=s, Type:=rdOpenDynamic, LockType:=rdConcurRowVer)

If rs.EOF<>True Then

Call Displayrecord

Else

MsgBox “No records Found”

End If

To scroll through the records add the following code in the click event of the cmdFirst,

cmdNext,cmdLast and cmdPrev command buttons.

Private Sub cmdFirst_Click()

rs.MoveFirst

Call Displayrecord

End Sub

Private Sub cmdNext_Click()

If rs.EOF<>True Then

rs.MoveNext

If rs.EOF=True Then

rs.MoveLast

Else

Call Displayrecord

End If

End If

End Sub

Private Sub cmdPrev_Click()

If rs.BOF<>True Then

rs.MovePrevious

If rs.BOF=True Then

rs.MoveFirst

Else
Call Displayrecord

End If

End If

End Sub

Private Sub cmdLast_Click()

rs.MoveLast

Call Displayrecord

End Sub

Add the following code in the add command click event and to store the details in the database add
the coding

as below in the Save command button click event.

Private Sub Add_Click()

Call ClearRecord

rs.AddNew

End Sub

Private Sub Save_Click()

rs(“emp_no”) = txtempno.Text

rs(“emp_name”) = txtempname.Text

rs(“sal”) = txtsal.Text

rs(“Joindate”) = txtdate.Text

rs(“dept_no”) = txtdept.Text

rs.Update

End Sub

To delete a record add the following rcode in the click event of delete command button as follows:

Private Sub Del_Click()

rs.Delete

Call Displayrecord

End Sub
Add the following routines in the form for displaying and retrieving.

Private Sub Displayrecord()

txtempno.Text=rs(“emp_no”)

txtname.Text=rs(“emp_name”)

txtsal.Text=rs(“sal”)

txtdate.Text=rs(“Joindate”)

txtdept.Text=rs(“dept_no”)

End Sub

Private Sub ClearRecord()

txtempno.Text=””

txtname.Text=””

txtsal.Text=””

txtdate.Text=””

txtdept.Text=”” End Sub

Creating parameterized queries using rdo parameter object

Add a new form to the project and name it as Emp_details.

Add a textbox , list box and two command buttons.

Declare the object variables as below:

Dim cnAs New rdoConnection

Dim envAsrdoEnvironment

Dim q As New rdoQuery

Dim rsAsrdoResultset.

Add the following code in the Form_Load event for prompting the user to specify the data source
name.

Private Sub Form_Load()

WindowState=2

Set env=rdoEnvironments(0)

Env.CursorDriver=rdUseOdbc
Set cn=env.OpenConnection(dsname:=””,Prompt:=rdDriverPrompt,ReadOnly:=False,Connect:=””)

End Sub

Attach the following code in the click event of the command button to retrieve the details of the
employees.

Private Sub Command1_Click()

q.SQL=”select * from emp1” & “ where emp_name Like?”

Set q.ActiveConnection=cn

q.rdoParameters(0)=”%” & Text1.Text & “&”

Set rs=q.OpenResultSet

List1.Refresh

Do Until rs.EOF

List1.AddItem “ Name-“ & “ “ &rs(“emp_name”) & “ “ & “ Emp_No- “ & “ “ &rs(“emp_no”) & “
“&“

Salary- “ &rs(“Sal”)

rs.MoveNext

Loop

End Sub

Press F5 to run the Form.

Accessing table with the rdo table object

The rdoTable object contains information about every column in the database table that exists in the

remote data source. The rdoTables collection can be used to obtain the list of all the tables available
in a

particular database.

Example: Design a Form with a command button and a list box.

Add the following code in the declaration section of the form to dimension the object variables for
the

environment, connection, query and the resultset.

Dim envAsrdoEnvironment

Dim rsAsrdoResultSet

Dim cnAsrdoConnection
Dim q AsrdoQuery

Add the following code in the Form_ Load event to specify the DSN name to open a connection.

Private Sub Form_Load()

Set env=rdoEnvironments(0)

env.CursorDriver=rdUseOdbc

Set cn= env.OpenConnection(dsname:=””, Prompt:=rdoDriverPrompt, ReadOnly:-False,


Connect:=””)

End Sub

Now add the following code in the click event of the Command button to display all the table
names that are

available in the database.

Private Sub Command1_Click()

Cn.rdoTables.Refresh

List1.Clear

For Each t In cn.rdoTables

List1.AddItem t.Name

Next

End Sub

Introcuction to activex exe and activex dll

Class based projects , Provides the feature of code reusability. Advantage of other technology such
as remote distribution of objects.

ActiveX DLL

An ActiveX DLL is an in-process server. It runs on the same thread as client. They are faster so
they become part of the application that uses them.

ActiveX EXE

An ActiveX EXE is an out-of process server. It runs as a separate process. A single EXE server can
service multiple clients. More efficient in terms of resource allocation but slow in exchanging
information between servers.

Creating an activex exe component


An ActiveX EXE component can be developed and run independently. The procedure of creating
an ActiveX EXE application, compiling and registering the same and then testing it using a client
application is elucidated here.

Developing a calculator to perform simple Arithmetic calculations like Addition, Subtraction,


Multiplication, Division and Modulus.

To create the Calculator (ActiveX EXE Component)

Go to Program ---> Visual Basic 6.0 ---> and the New Project dialog box opens. Select ActiveX
EXE as shown in the Figure:

A class module namely class1 opens by default. Press F4 and edit the properties

Include the following code in the general declaration section of the class module to perform
addition

of any two digits. The function is named as Addn .

Public Function Addn(A As Single, B As Single) As Double

Addn=A+B

End Function

Define a Function Diff in the general declaration section to find the difference between any two

numbers as given below:

Public Function Diff(A As Single, B As Single) As Double

Diff= A-B

End Function
The same logic holds good for the code given below to perform multiplication for any two
numbers and the

function defined is Prod.

Public Function Prod(A As Single, B As Single) As Double

Prod= A*B

End Function

The division is performed by defining a function Div as follows:’

Public Function Div(A As Single, B As Single) As Double

Div= A/B

End Function

Include a function named modulus in the general declaration section as below using mod
operator:

Public Function Modulus(A As Single, B As Single) As Double

Modulus= A Mod B

End Function

This completes the development of the ActiveX EXE component Calculator. This has to be run
and compiled.

Before running select File ---> Save Project As and save it as ActiveXCalculator.vbp and the
class module as

Calculator.cls.

Compiling and registering the calculator component

The Calculator control can be run by Pressing F5.

Then select File ---> Make EXE to make component an executable.

Make Folder dialog appears as shown in the figure. Choose a folder to save EXE and click OK.

Now the ActiveXCalculator is compiled and registered it can be used in any projetcs.

Testing the calculator project with a standard exe application

Open a new Standard EXE project and save it as Calclient.vbp.


To include the ActiveX Calculator , Select References from the Poject menu and select ActiveX

Calculator from the list.

Create instances of class Calculator in the general declaration section and use it in the project as
given below:

Dim CalcobjAs New Calculator

Add the following code in the click event of cmdAdd com, cmdSubtract ,cmdMultiply and
cmdDivide and

cmd Modulus as given below:

Private Sub cmdAdd_Click()

Dim I As Single, V As Single

I=InputBox(“Enter a Value:”, “Calculation with two numbers”)

V=InputBox(“Enter a Value:”, “Calculation with two numbers”)

Text1.Text=” The Sum of the given two numbers is “&Calcobj.Addn(I,V)

End Sub

Private Sub cmdSubtract_Click()

Dim I As Single, V As Single

I=InputBox(“Enter a Value:”, “Calculation with two numbers”)

V=InputBox(“Enter a Value:”, “Calculation with two numbers”)

Text1.Text=” The Difference of the given two numbers is “&Calcobj.Diff(I,V)

End Sub

Private Sub cmdMultiply_Click()

Dim I As Single, V As Single

I=InputBox(“Enter a Value:”, “Calculation with two numbers”)


V=InputBox(“Enter a Value:”, “Calculation with two numbers”)

Text1.Text=” The Product of the given two numbers is “&Calcobj.Prod(I,V)

End Sub

Private Sub cmdDivide_Click()

Dim I As Single, V As Single

I=InputBox(“Enter a Value:”, “Calculation with two numbers”)

V=InputBox(“Enter a Value:”, “Calculation with two numbers”)

Text1.Text=” The Division of the given two numbers is “&Calcobj.Div(I,V)

End Sub

Private Sub cmdModulus_Click()

Dim I As Single, V As Single

I=InputBox(“Enter a Value:”, “Calculation with two numbers”)

V=InputBox(“Enter a Value:”, “Calculation with two numbers”)

Text1.Text=” The Modulus of the given two numbers is “&Calcobj.Modulus(I,V)

End Sub

Now run the application. An input box appears as shown in the figure and on entering a number,
another input box appears asking for the second number.
Creating activex dll component

Steps to create a new ActiveX DLL component are:

Determine the features the component will provide

Determine the objects required to divide the functionality of the component in a logical
fashion.

Design any Forms the component will display.

Design the interface that is, the properties, methods and events for each class provided by the

component.

Create a project group consisting of the users component project and a test project.

Implement the Forms required by the component.

Implement the interface of each class.

As each interface element or feature is added, features are added to the test project to exercise
the new

functionality.

Compile the DLL and test it with all potential target applications.

Example:

Start an instance of Visual Basic and select an ActiveX DLL project and it opens into a class
module by

default as in an ActiveX EXE.

The properties of the class module can be set as given in the

Option Explicit

Public gdatServerStartedAs Date

Sub Main()

gdatServerStarted= Now

Debug.Print “Executing Sub Main”

End Sub
Step by Step Procedures to create two properties and one method for the Interest class.

Option Explicit

Public Name As String

Option Explicit

Public Function FixInterest(P As Single, T As Single)

Dim R As Integer

R=10

FixInterest=(P*R*T)/100

End Function

Public Function RecInterest(P As Single, T As Single) As Single

Dim R As Single

R=8.0

RecInterest=(P*R*T)/100

End Function

Public Function CumInterest(P As Single, T As Single) As Single

Dim R As Single

R=7.5

RecInterest=(P*R*T)/100

End Function

Save the project as Interest.vbp and class as Interest.cls.

To test the ActiveX DLL project, select Add project from File menu and select a Standard EXE .

The controls are placed in the form with properties.

Goto References from the project menu and then select the InterestCalculator component and
click

OK. Declare the instances of the class as below:

Dim IntobjectAs New Interest

The user has to give the input for principal amount, time period and select the choice of deposit

scheme. Add the following code in the click event of cmdResult command:
Private Sub cmdResult_Click()

Dim I As Single, v As Single, b As Single

Dim a As Single

I= txtPamt.Text

V=txtTime.Text

A=Combochoice(1).Text

If the Deposit Scheme is selected as Fixed Deposit, the interest is calculated by calling
FixInterest function

referenced by the instance of the class Intobject .

If Combochoice(1).Text=”Fixed Deposit” Then

txtIamt.Text=”The Simple Interest amount for the given principle is “ &Intobject.FixInterest(I,v)

c=Intobject.FixInterest(I,v) + 1

If the Deposit Scheme is selected as Recurring Deposit, the interest is calculated by calling
RecInterest

function referenced by the instance of the class Intobject .

If Combochoice(1).Text=”Recurring Deposit” Then

txtIamt.Text=”The Recurring Interest amount for the given principle is “


&Intobject.RecInterest(I,v)

c=Intobject.RecInterest(I,v) + 1

If the Deposit Scheme is selected as Cumulative Deposit, the interest is calculated by calling
CumInterest

function referenced by the instance of the class Intobject .

ElseIfCombochoice(1).Text=”Cumulative Deposit” Then

txtIamt.Text=”The Cumulative Interest amount for the given principle is “


&Intobject.CumInterest(I,v)

c=Intobject.CumInterest(I,v) + 1

End If

Lastly the total amount is calculated as given below:

txtTamt.Text=”The total amount is” & c

End SubPress F5 to run the application. Interest Calculator Form.


UNIT 4
OBJECT LINKING AND EMBEDDING

Object Linking and Embedding: OLE fundamentals, Using OLE Container Control, Using
OLE Automation objects, OLE Drag and Drop, File and File System Control: File System
Controls, Accessing Files.

Introduction
OLE is a means of communication, which gives any application the power to directly use and
manipulate other Windows applications. OLE specification gives the user to link and embed
objects and also to edit the object within the container application.

OLE fundamentals
DDE is an acronym for Dynamic Data Exchange. It is the basic foundation for inter process
communication between applications. While using DDE, unformatted data is exchanged. OLE
enables the programmer to create an application that can display data from many different
applications. The user can edit the data from within the application in which it was created. It
contains the correct underlying object so the information is fully editable.

Objects and classes


A class defines each object in Visual Basic. An object refers to a discrete unit of data supplied
by an application. An application can expose several types of objects.

Three ways of creating an object in Visual Basic:

The object is added to the Toolbox using the Custom Controls command on the Tools menu.
It embeds the object within the interface of a Form in our application.

The CreateObject or GetObject functions can be used for creating the objects in code. This
technique creates the object in a running instance of the application that provides the object.

The object can be embedded or linked within an OLE container control. This technique
permits the change of objects on the Form. The controls in the toolbox in Visual Basic represent
a class. This object known as a control does not exist until it is placed on a Form. The instance of
the class created is the object that is referenced to an application. The Form we work with during
design time is a class. During run time Visual Basic creates an instance of a class.

OLE automation

Some applications provide objects that support OLE automation and some support linking and
embedding. The properties and methods of these objects can be accessed using Object property.
Container application

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

Linked objects

Data associated with a linked object is stored by the application that supplied the object. This
application stores only link references that displays a snapshot of the source data. Any
application containing a link to that object can access the object’s data and change it. The OLE
container control can be used to create a linked object in our Visual basic application.

Embedded objects

When an embedded object is created, all the data associated with that object is contained in the
object. For Example: if a spreadsheet is an embedded object, all the data associated with the cells
would be contained in the OLE container control. The name of the application that created the
object is saved along with the data. On selecting the embedded object, the spreadsheet
automatically gets started, so that we can edit those cells. When an object is embedded in an
application, no other application has access to the data in the embedded object.

Using OLE container control

The OLE container control allows adding objects from other applications. An OLE control can
have only one object at a time. Using OLE control we can do the following:

Create a placeholder in our application for an object.

Create a linked object in our application

Blind the OLE container control to a database.

Create objects from the data that was copied onto the clipboard.

Display objects as icons.

Perform an action if the user moves, sizes or updates the objects in the OLE control.

Provide backward compatibility with an application that includes many OLE container
controls.

Creating objects at design time

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

This example creates a link from an existing application. An OLE control is drawn on the Form.
This displays an Insert Object dialog box as in the following figure: The Create from File option
is clicked and the Browse button is chosen. A Browse dialog box appears. The desired file is
selected from the directory and the OK button is clicked. The Insert Object dialog is displayed
again. The Link CheckBox is selected and the OK button is clicked. When a linked object is
created, the data displayed in the OLE control exists in one place, which is the source file. The
file can be edited in its original application and saved. The object’s data can be accessed from
any of the other applications that contain links to that data and the data in the source file can be
changed from within any application.

To create an embedded object at design time

Example:

An OLE control is drawn on the Form. This displays an Insert Object dialog box. The Create
from File option is clicked and the Browse button is chosen. A Browse dialog box appears.

The desired file is selected from the directory and the OK button is clicked. The Insert Object
dialog box returns. The OK button is clicked.

When an embedded object is created, we can either embed data from a file or create a new
empty object that can be filled later with data. When the data is embedded from a file, a copy of
the specified file’s data is displayed in the OLE container control.

When a new object is created, the application that created the object is invoked and data can
be entered into the object.

Example:

This example creates a new file using OLE container. OLE control is drawn on the Form. Insert
dialog box is displayed at this point of time. Create New option is chosen and Microsoft Excel
Worksheet is selected from the list of options displayed as shown in the Figure:
Now right click on the OLE container and choose option. This takes us to the Excel application.

The details required are entered in the excel worksheet and the file is saved as “student.xls”.

Creating objects using paste special dialog box

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

Example :

An Excel worksheet containing data that is to be linked or embedded is opened. The desired
data is selected from the sheet.

From the Edit Menu, the Copy command is chosen.

Right click the OLE control drawn in a Visual Basic form and choose Paste Special command
from the pop-up menu.

It will display the Paste Special Dialog Box as shown in the figure:
Choose Paste option to create an embedded object and Paste Link option to create a linked
object.

Creating objects at run time

To create a linked or embedded object at run time, various methods and properties are used in
the code.We can create a linked object at run time using the SourceDoc property and CreateLink
method. The following code fragment creates a linked object at run time. (Assume we have a file
called ole.xls).

OLE1.CreateLink “C:\OLE.xls”

Creating an empty embedded object at run time

The CreateEmbed method can be used to specify an empty embedded object at run time. The
following code fragment inserts a file template for a Microsoft Excel Worksheet in the OLE
container control.

OLE1.CreateEmbed “”, “Excel.sheet”

The following code creates an empty embedded object and the application is created using the
DoVerb action.

OLE1.CreateEmbed “”, “Excel.sheet”

OLE1.DoVerb -5

The Insert Object dialog box can be displayed at run time, with which we can create a variety of
objects. This can be used in document-centered applications, where the user combines data from
different applications to create a single document. The InsertObjDlg method is used to display
the Insert Object dialog box. The following code fragment displays the dialog box.

Consider an OLE control and a CommandButton are added to a Form. The following code is
entered in the Command1_Click() procedure

Private Sub Command1_Click()

OLE1.InsertObjDlg

If OLE1.OLEType=vbOLENone Then

MsgBox “Object not created”

End If

End Sub

Once the dialog box is displayed, the user can make a choice from the options that are displayed.
If the user cancels the dialog, an object is not created. If the user selects a choice, the selected
object is displayed.
Any changes made to the object can be updated in the OLE control by choosing Update from the
File menu in that object. Once the application is chosen to be linked, it is necessary to check if
the application is running. To check if the application is running, the following code
(OLE1.AppIsRunning) is used.

Moving or sizing the ole container

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

Example:

An OLE control is added to a Form. The following code is entered in the OLE1_ObjectMove()
procedure.

Private Sub OLE1_ObjectMove(Left As Single, Top As Single, Width As Single, Height As


Single)

OLE1.Move OLE1.Top, OLE1.Left, Width, Height

OLE1.Move Top, Left, OLE1.Width, OLE1.Height

End Sub

Using ole automation objects

OLE Automation is an industry standard technology that applications use to expose their OLE
objects to development tools, macro languages, and other applications that support OLE
Automation. For example, a

A word processor might expose objects such as application, document, paragraph, sentence,
bookmark or selection. When an application supports OLE Automation, the objects it expose can
be accessed by Visual Basic. Visual Basic could be used to manipulate these objects by invoking
methods on the object or by getting and setting the object’s properties. For example, if we create
an OLE Automation object named MyObj, the following code could be written for manipulating
the object.

MyObj.Insert “Hello, World.”

MyObj.Bold = True

MyObj.FileSaveAs “C:\WORDPROC\DOCS\TESTOBJ.DOC”

The following functions are used to access an OLE Automation object.

CreateObject creates a new object of a specified type.

GetObject retrieves an object from a file.


Referencing an object using an object library

The objects, functions, properties and methods supported by an application are usually defined
in the application’s object library. Every application that supports OLE automation provides at
least one type of object. For example, a word processing application may provides an application
object, a document object, and a toolbar object. To create an OLE Automation object, assign the
object returned by CreateObject to an object variable which is shown as follows:

Dim WordBasicObjectAs Object

Set WordBasicObject =CreateObject(“Word.Basic”)

When this code is executed , the application creating the object is started (Microsoft Word in the
illustration given below). If it is already running , a new instance of the application is started ,
and an object of the specified type is created. Once an object is created, we reference it in code
using the object variable we have defined. In the above example, we access properties and
methods of the new object using the object variable, WordBasicObject.

For example

WordBasicObject.filenew

WordBasicObject.Insert “Hello, world.”

WordBasicObject.FilePrint

WordBaasicObject.FileSaveAs “C:\DOCS\TEST.DOC”

Filenew in the above code opens a new file in the word object. Similarly, we can pass the object
returned by the CreateObject function to a function expecting an object as an argument. For
example

Call MySub (CreateObject(“Word.Basic”))

The CreateObject method is used when there is no current instance of the object. The following
example uses the CreateObject function to set a reference (myApp) to Microsoft Excel. It uses
the reference to access the visible property of Microsoft Excel.

Example

A new project is opened and the following code is entered in the Form_Load() procedure.

Dim myAppAs Object

Set myApp= CreateObject(“excel.application”)

myApp.filenew

myApp.Visible= True
The following example uses the GetObjectFunction to get a reference to a specific Microsoft
Excel Worksheet. The file, OLE.XLS in the example , must exist in the specified location;
otherwise a Visual Basic error known as the OLE Automation error is generated.

The following code is entered in the Form_Load() procedure of a new Standard EXE project.

Dim MyAppAs Object

Dim ExcelNotRunningAs Boolean

On Error Resume Next

Set MyXL = GetObject(, “Excel.Application”)

If Err.Number<> 0 Then ExcelNotRunning = True

Err.Clear

Set MyXL= GetObject(“I:\OLE.XLS”)

MyXL.Application.Visible = True

MyXL.Parent.Windows(1).Visible = True

If ExcelNotRunning = True Then MyXL.Application.Quit

Set MyXL = Nothing

The above example uses the worksheet’s Application property to make Microsoft Excel visible,
to close it and so on. The first call to GetObject causes an error if Microsoft Excel is not already
running. In this example, the error causes the ExcelWasNotRunning flag to be set to True. The
second call to GetObject specifies the file to opened. If Microsoft Excel is not already running,
this second call starts it and returns a reference to the worksheet represented by the file. Next,
the code in the example makes both Microsoft Excel and the window containing the specified
worksheet visible. Finally, if there was no previous version of Microsoft Excel running, the code
uses the Application object’s Quit method to close Microsoft Excel . If the application was
already running , no attempt is made to close it . The reference itself is released by setting it to
Nothing.

Using an object’s methods and properties

After declaring a variable that refers to the OLE Automation object, the object can be
manipulated in Visual Basic using the object.property syntax. The following example sets the
Name property of the application object.

Dim myAppAs Object

Set myApp = CreateObject(“Excel.Application”)

myApp.Caption= “MyObject”
Some applications might name objects, properties or methods using characters that have special
meaning in Visual Basic. These are called nonstandard names. For example , a Microsoft Word
provides methods that return strings. The name of each of these methods ends in a dollar sign ($)
which has a special meaning in Visual Basic. To use one of the Microsoft Word string functions
in Visual Basic, the name is enclosed in square brackets.

NameofStyle = MyWord.[StyleName] ()

OLE drag and drop

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

OLEDrag Method

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

OLEDragMode Property

This property is used to determine if the object can act as an OLE drag source, and if the
OLEDrag operation is done manually or automatically. The allowable property values are
vbOLEDragManual-0:This is the default value. It is used when the user’s own OLE drag
handlers are used in the application.

vbOLEDrag Automatic-1 :This is used when the application has to handle the drag and drop
operations.

OLEDropModeProperty

This property determines the methodology of processing OLE drop events in the application. It
can take any one of the following values.

vbOLEDropNone-0:This is the default value. It prevents the OLE container from allowing
OLE drop events.

vbOLEDropAutomatic-1:This is set when the user entrusts Visual Basic with handling of the
OLE drag routines.

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

OLEDragDrop() event :This event is fired whenever an OLE drop operation is performed on
an OLE container which allows OLE drop operations.

The syntax of this event is as follows:


Private Sub object_OLEDragDrop(data As DataObject, effect As Long, button As Integer, shift
As Integer, x

As Single, y As Single)

OLE DataObject can be referenced using the GetData method to retrieve the data being dropped
in this event. Effect parameter is used to communicate to the target component the action that is
to be performed on the data. The effect parameter can be any one of the following as shown
inTable:

PARAMETER DESCRIPTION
vbDropEffectNone – 0 Target cannot accept OLE data
vbDropEffectCopy --1 Specifies that data should be copied from
source to destination

vbDropEffectMove –2 Specifies that data must be moved from source


to destination
vbDropEffectScroll – 2147483648 Indicates if the target has scrolled, or would
scroll if the
data were dropped onto it. Used rarely.

The button parameter is used to identify the button on the mouse that was clicked during OLE
drag operations as in the table below:

VALUE DESCRIPTION

1 Left Button

2 Right Button

3 Middle Button

The x and y parameters indicate the current position of the mouse pointer. These values are used
if precision dropping is required within the target control.

Events related to ole drag and drop

OLECompleteDrag() event is fired when data has been dropped from the source control and it
has either successfully performed a Move or Copy operation or the operation was cancelled.

OLEStartDrag() event is fired when the source control’s OLEDragMode property is set to
manual. It is also fired when the source component initiates an OLE Drag operation and the
OLEDragMode property is set to automatic.

OLEDragOver() event is fired when the mouse is moved over an OLE container during an
OLE drag operation.

OLESetData() event is fired when the target component issues a GetData method on the
source’s DataObject. The syntax for this event is as follows:
Private Sub Object_OLESetData(data As DataObject, dataformat As Integer)

Example:

Start a new project by selecting Sandard EXE from the New Project dialog box.

Save the form as olefrm.frm and set the Name property to ole frm and caption property to
OLE Drag and Drop Demonstration Project.

Add two text boxes of equal size as shown in the figure below the project by dragging them
from the toolbox and name them as OLEtext1, OLEtext2. Clear their text property and set their
Multiline property to true.

Set the OLEDragMode to 1 – Automatic for OLEtext1 and OLEtext2.

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

Private Sub OLEtext1_OLEDRagDrop(Data As DataObject, Effect As Long, Button As Integer,


Shift As

Integer, X As Single, Y As Single)

OLEtext1.Text = Data.GetData(vbCFText)

End Sub

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

Private Sub OLEtext1_OLEStartDrag (Data As DataObject, AllowedEffects As Long)

Effect = vbDropEffectCopy

Data.SetData OLEtext1.Text vbCFText

End Sub

Add the code in the OLEDragDrop() event of OLEtext2

Private Sub OLEtext2_OLEDRagDrop(Data As DataObject, Effect As Long, Button As Integer,


Shift As

Integer, X As Single, Y As Single)

Effect = vbDropEffectCopy

OLEtext2.Text = Data.GetData(vbCFText)

End Sub

Add the code in the OLEStartDrag() event of OLEtext2

Private Sub OLEtext2_OLEStartDrag (Data As DataObject, AllowedEffects As Long)

Effect = vbDropEffectCopy
Data.SetData OLEtext2.Text vbCFText

End Sub

Now press F5 to run the project to get the output as in the figure:

File system controls

Three file system controls available in Visual Basic are DriveListBox, DirectoryListBox and
FileListBox. In an application that allows to selecting files from drives, these controls are used
in combinations. When we need to select a file, a dialog box including all these three controls is
displayed on the screen. We can select the desired file by selecting a drive from the
DriveListBox, a directory from the DirectoryListBox and a file from the FileListBox.

Example:

A new standard EXE project is opened and the Form of the project is saved as Select.Frm and
the project is saved as Select.Vbp. The application is designed as per the following specification
in the Table.
The following code is entered in the general declaration section of the Form.
Option Explicit
The following code is entered in the Form_Load () procedure.
Private Sub Form_Load()
Combo1.AddItem “All files(*.*)”
Combo1.AddItem “Text files(*.DOC)”
Combo1.AddItem “All files(*.TXT)”
Combo1.ListIndex = 0
Label4.Caption= Dir1.Path
End Sub
The following code entered in the Drive1_Change() procedure is executed whenever the
DriveListBox is
changed.
Private Sub Drive1_Change()
On Error GoToErrorTrap
Dir1.Path=Drive1.Drive
Exit Sub
ErrorTrap:
MsgBox “Drive Error1”, vbExclamation, “Error”
Drive1.Drive= Dir1.Path
Exit Sub
End Sub
An error trap is set before the procedure. This executes the command that changes the Path
property of the DirListBox. This error trap is required, because changing the path of the
DirListBox may cause an error at run time.
The following code is entered in the Dir1_Change procedure and is executed whenever the
DirListBox is changed.
Private Sub Dir1_Change()
File1.Path = Dir1.Path
Label4.Caption= Dir1.Path
End Sub
Enter the following code in the Combo1_Click() procedure which updates the Pattern property
of the FileListBox according to the selected file type. The Pattern property returns or sets a value
indicating the filenames displayed in a FileListBox control at run time.
Private Sub Combo1_Click()
Select Case Combo1_ListIndex
Case 0
File1.Pattern = “*.*”
Case 1
File1.Pattern = “*.DOC”
Case 2
File1.Pattern = “*.TXT”
End Select
End Sub
The following code entered in the cmdOK_Click() procedure. The If statement checks for the
selected
file and displays a message box.
Private Sub cmdOK_Click()
If Text1.Text = “” Then
MsgBox“ No file was selected”
Else
MsgBox “Selected File is” + Text1.Text
End If
End Sub
Enter the following code in the cmdCancel_Click () procedure which terminates the application.
Private Sub cmdCancel_Click()
End
End Sub

Accessing files
A File Consists of a series of related bytes located on a disk.There are three ways of accessing
files in Visual Basic. They are as follows:
Random Access
Sequential Access
Binary Access
Random access files
A random access file is like a database. It is made up of records of identical size. Each record is
made up of data of identical size. Figure shows a random access file with two fields per record.
DEEPA22VIDYA23
The following program allows us to maintain a database file called Product.Dat that holds the
record of product information.
Example:
A new Standard EXE project is opened and the Form and the project are saved as Product.frm
and Product.vbp. The Form is designed as per the following specification table. The designed
Form appears as shown in the Figure:

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

Enter the following code in the general declaration section of Module1 to declare a user-defined
type that corresponds to the fields of a record in the Product Dat file.

Option Explicit

Type ProductInfo

Name of the product As String * 20

Product code As String * 5

Price As String * 8

Data of manufacture As String * 20

End Type

The following code is entered in the general declaration section of the Form.

Option Explicit

Dim LastRecordAs Long

Dim CurrentRecordAs Long


Dim RecordLenAs Long

Dim Product AsProductInfo

Dim Filenum

Opening the random access file

The file must be opened before the data can be written to or read from the file. The following
code in

theForm_Load() procedure opens the file.

Private Sub Form_Load()

RecordLen = Len(product)

Filenum=FreeFile

Open “C:\InfoProduct.dat” For Random AsFilenum Len = RecordLen

CurrentRecord =1

LastRecord = FileLen(“C:\ProductInfo.dat”) / RecordLen

If LastRecord = 0 Then

LastRecord = 1

End If

ShowCurrentRecord

End Sub

Len() function is used to exatract the length of the variable.

FreeFile() function is used to get a file number that is not already in use.

The RecordLen and Filenum variables are now updated and the procedure opens the file
Product.Dat

for random access in the C:\directory.

Variable CurrentRecord is used to store the record number of the currently displayed record.

Variable LastRecord is used to store the record number of the last record in the file.

A new procedure called SaveCurrentRecord is created which is responsible for saving the
contents of

the TextBox controls in the record specified by the CurrentRecord.

Public Sub SaveCurrentRecord()


Product.Name=Text1.Text

Product.code=Text2.Text

Product.price = Text3.Text

Product.manufacture_date = Text4.Text

Put #Filenum, CurrentRecord, product

End Sub

Put statement stores the contents of the variable in record number CurrentRecord of the file.

A new procedure called ShowCurrentRecord() is created in the declarations section of the Form
that displays

the record specified by the variable CurrentRecord.

Public Sub ShowCurrentRecord()

Get #Filenum, CurrentRecord, product

Text1.Text=Trim(Product.Name)

Text2.Text=Trim(Product.code)

Text3.Text=Trim(Product.price)

Text4.Text=Trim(Product.manufacture_date)

Form1.Caption = “Record” + Str(CurrentRecord) + “/” + Str(LastRecord)

End Sub

Get statement is used to fill the variable Product with the data of the current record. After it is
filled the

contents are displayed by updating the Textbox controls.Trim function is used to remove the
trailing blanks.

The following code is entered in the cmdNew_Click() procedure, adds a new record to the file.

Private Sub cmdNew_Click()

SaveCurentRecord

LastRecord= LastRecord + 1

Product.Product_Name = “”

Product.Product_Code = “”

Product.date_of_manufacture_date = “”
Put #Filenum, LastRecord, Product

CurrentRecord = LastRcord

ShowCurrentRecord

Text1.SetFocus

End Sub

Enter the following code in the cmdPrevious_Click()

If CurrentRecord = 1 Then

MsgBox“ Beginning of File!”, vbExclamation

Else

SaveCurrentRecord

CurrentRecord= CurrentRecord – 1

ShowCurrentRecord

End If

Text1.SetFocus

End Sub

The following code is entered in the cmdExit_Click() procedure, which is executed when the
Exit

button is clicked.

Private Sub cmdExit_Click()

SaveCurrentRecord

Close #Filenum

End

End Sub

Sequential access files

Sequential Access Files are accessed line by line and are ideal for applications that manipulate
text files. When data is written into a sequential file, we write lines of text into a file and when
data from a sequential access file is read, we read lines of text from a file. Sequential access file
is opened in one of the three ways – output, append or input.
In order to create a sequential file, we need to open a file for output. After the file is created, we
can use output command to write lines to the file. The following code example creates the file
OUTPUT.TXT and writes the contents of the TextBox Text1 into the file.

Example:

A new Standard EXE project is opened and a TextBox and CommandButton is added to the
Form. The Form and the project files are saved as SEQ.FRM and SEQ.VBP.

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

Private Sub Command1_Click()

filenum = FreeFile

Open “C:\OUTPUT.TXT” For Output Asfilenum

Print #filenum, Text1.Texto

Close filenum

End Sub

The application is run by clicking F5. Text that is necessary is entered in the TextBox and the

CommandButton is clicked.

The enetered text appears in the file OUTPUT.TXT file. This can be viewed by opening the file
in the

Notepad after terminating the application. The following code appends the existing file:

Two more CommandButton controls namely Command2 and Command3, and a TextBox
control Text2 are

added to the SEQ.FRM.

The following code is entered in the Command1_Click() event.

The application is run and the Command2 button is clicked.

Private Sub Command2_Click()

Filenum = FreeFile

Open “C:\OUTPUT.TXT” For Append Asfilenum

Print #filenum, “Work is Worship”

Close filenum

End Sub
In order to open the sequential file for input, we can use the Input statement. Once the file is
opened

for input, the Input() function can be used to read the entire contents of the file into the TextBox
or a string

variable.

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

Private Sub Command3_Click()

Filenum = FreeFile

Open “C:\OUTPUT.TXT” For Input Asfilenum

Filelength = LOF(1)

Text1.Text = Filelength

Text2.Text = Input(LOF(filenum), filenum)

Close filenum

End Sub.

Binary access file

Binary access files are accessed byte by byte. Once a file is opened for binary access we can
read from and write to any byte location in the file. The ability to access any desired byte in the
file makes it the most flexible one. Before accessing a file in binary mode, the file should be
opened first for binary access.

Example :

A new project is opened and the Form of the project is saved as BIN.FRM and the project file as
BIN.BAT. A CommandButton is added and the following code is entered in the Click event:

Private Sub Command1_Click()

mystring = “This is a Binary Access File”

filenum = FreeFile

Open “C:\Binary.DAT” For Binary Asfilenum

Put #filenum, 100, mystring

Close filenum

End Sub

The applicaton is created and the click event of the CommandButton creates the file
BINARY.DAT.
UNIT 5
CONTROLS IN VB

Additional controls in VB: sstab control, setting properties at runtime, adding controls to tab,
list control, tabstrip control, MS Flexgrid control, Why ADO, Establishing a reference,
Crystal and Data Reports.

Additional controls available in vb6.0:


These controls make job easier in terms of development of the interface. In real applications,
textbox, label boxes or combo boxes alone may not be enough. In database need to display the
data in row and column format, display several pages of information on a topic and show details
from a database in a hierarchical format.

SSTab control:
It provides an easy way of presenting several dialogs or screens of information on a single form.
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. Either open the property pages for a control or open the
printer dialog box properties to see .each tabs displays a separate set of controls. The Tabbed
Dialog control provides a group of tabs, each of which acts as a container for other controls. The
controls are exclusive to the particular tab. Other tabs can’t use the controls of one tab. Not
possible to see one tab’s control in another tab.

The properties are set using the property pages. Some properties are in runtime .

Working with SSTab Control:

Start new project, to add the SSTab control,

Right click on the Toolbox

Select components from the pop-up menu

From the components select MSTabbes Dialog Control 6.0

Properties:

Add controls to each of the tabs

Change the caption for each of the tabs.

Write code for the controls where necessary.

Give the captions for the tabs,

Tab0:General

Tab1:Financial

Tab2:Personal
At the run time, the user can navigate through the tabs by either clicking on them, by pressing
CTRL+TAB. To create a tab called ‘general’ and allows the user to access the tab with keyboard
combination ALT+G.

Setting Properties at Runtime:


Add the code to the Form_load event
SSTab1.Tabs=12
SSTab1.TabsRow=4,
By default no.of tabs is 3. Each tab is indexed and can then be selected individually. Tabs are
indexed beginning at 0.
Adding controls to tab:
Same as add controls to form, make sure that group related controls in one tab and each control
need coding.
Enabling and disabling tabs at run time:
Use tab enabled property to enable and disable individual tabs or group of tabs. This property
specify the tab no, then disable it by setting the value to false.
EX:
If UserName=”bca” then
SSTab1.TabEnabled(2)=False
End if
To disable group of tabs,
For i=1 to 5
SSTab1.TabEnabled(i)=false
Next i
The TabOrientation Property:
Used to locate the tabbed dialog box on either of the four sides.
SSTab1.TabOrientation=ssTabOrientationLeft(OR)
SSTab1.TabOrientation=ssTabOrientationRight(OR)
SSTab1.TabOrientation=ssTabOrientationTop(OR)
SSTab1.TabOrientation=ssTabOrientationBottom(OR)
Better to set the orientation to either top or left. To set the orientation to Left or Right, need to
change the font because only true type fonts will be displayed in vertical tabs.The picture can be
added at design time by setting the properties, at run time set the picture property using the
LoadPicture function,
SSTab1.TabPicture(0)=LoadPicture(“c\azam\car1.bmp”)
The ImageList Control:
The ImageList is a control that enables to store graphic images in an application. Other
controls can then use the ImageList as a central repository for the images that they will use. Both
bitmaps (*.bmp files) and icons (*.ico files) can be stored in the ImageList control. At runtime
the ImageList is invisible, just like a Timer or a CommonDialog control, so you can place it
anywhere on a form without interfering with the user interface. After an ImageList control has
been added to a form, images can be added to the control at design time through the Custom
Properties dialog box. The first tab of the dialog box, as shown in Figure, enables to change
general properties of the ImageList. On this tab, also can select the style and size of a graphic
that will be included in the ImageList. Three of the resolutions, 16´16, 32´32, and 48´48, refer to
the resolution of icon files. The Custom option include bitmap images in the ImageList as well
as icon images. Need not to choose a resolution, height, and width for the ImageList. As soon as
add an image to the control, Visual Basic automatically determines the properties.

The General tab of the Property Pages dialog box for the ImageList control. The list of images
contained in the ImageList control can be managed through the Images tab of the Property Pages
dialog box, as shown in Figure. This tab enables you to add and remove images from the control
as well as set additional information about each image. The Index of each image is assigned by
Visual Basic. The Index starts at 1 for the first image and increments by 1 for each additional
image.
The Key property to refer to an image in the ImageList's collection of images. The Key property
is a string value that can use in place of the Index property to refer to an image in the list. The
easiest way to add images to the ImageList is to use the Images tab at design time. Just click on
the Insert Picture button, and you can browse for the *.ico and *.bmp files that you want to add
to the control.
After added images to the ImageList control, they are available for our application to use in
other controls. Also can load images into PictureBoxes and Image controls from theImageList.
Although you can add all the images you may need in your application to theImageListat design
time, there are times when you will have to manipulate these images at runtime. This can be
done through the ListImages Collection of the ImageList control. e ListImages Collection
contains ListImage objects.
The Add method of the ListImages Collection to add images to the ImageList at runtime. The
syntax for Add is as follows:
ImageList1.ListImages.Add([index], [key], picture)

Here ImageList1 is the name of the ImageList control on your form. Index and Key are
optional parameters. If Index is specified, it will be the location at which the image is loaded into
the ListImages Collection. If Index is omitted, the new image will be inserted at the end of the
collection. Key is a string value that you can use to refer to an image in the list without knowing
its index value.

For example if an image were added as follows:


ImageList1.ListImages.Add(, "folder icon", LoadPicture("folder.ico"))
Need not know the index value of the new image, but you could still refer to it in this way:
Picture1.Picture = ImageList1.ListImages("folder icon").Picture
To remove a ListImage from the ListImages Collection with the Remove method. To use
Remove either by specifying the index of the image:
ImageList1.ListImages.Remove 1
or by providing the image's key value:
ImageList1.ListImages.Remove "key value"
TabStrip Control:
A tab strip control presents the user with a row (or rows) of tabs that acts like the dividers in a
notebook or the labels on a group of file folders. Using tab strips, the user can click a tab and see
a whole new panel of data, like opening a file folder. The most common use of tab strips today is
to organize dialog boxes—often those dialog
boxes that let the user set program options—into many different panels, all hidden from view
except the current one the user has selected. A tab strip control consists of one or more Tab
objects in a Tabs collection. At both design time and runtime, can set the Tab object’s
appearance by setting properties, and at runtime, by invoking methods to add and remove Tab
objects. Adding A Tab Strip To A Form:
To add a tab strip control to a form, follow these steps:
1. Select the Project|Components menu item.
2. Click the Controls tab in the Components dialog box that opens.
3. Select the Windows Common Controls item.
4. Click on OK to close the Components dialog box.
5. The preceding steps add the Tab Strip Control tool to the toolbox. Draw a tab strip in the form
as
you want it.
6. Set the tab strip’s properties, and add the code you want.
To add new tabs at runtime if add them to the tab strip’s Tabs property, using the Add method.
For example, here’s how we add two new tabs to a tab strip control and set their keys:
Private Sub Form_Load()
Dim Tab2, Tab3 As ComctlLib.Tab Set Tab2 = TabStrip1.Tabs.Add() Tab2.Key = "Key2"
Set Tab3 = TabStrip1.Tabs.Add() Tab3.Key = "key3"
End Sub
The Tabs Collection
The control consists of one or more Tab objects in a Tabs collection. At both design time and
run time, can affect the Tab object's appearance by setting properties, and at run time, by
invoking methods to add and remove Tab objects.
Associate the ImageList Control with the TabStrip Control
To identify a tab's function, to assign an image from the ImageList control to the Tab object.
First associate an ImageList control with the TabStrip control. To associate an ImageList control
with a TabStrip control at run time simply set the ImageList property to the name of the
ImageList control, as shown in the example below:
void CForm1::Form_Load()
{
// set the imagelist
// Thetabstrip control is named m_Tabstrip
// and the imahelist control is named m_Imagelist
m_Tabstrip.ImageList = m_Imagelist.GetDispatch();
}
Create Tabs at Design Time or Run Time
To create Tab objects at design time
1. Click on the browse button [with caption "...", next to the control name edit box] on the
property window.
2. Click Tabs to display the Tabs page, as shown in Figure below:

Create Tab Objects at Run Time Using the Add Method

To create Tab objects at run time, use the Add method for Tab objects. Note One Tab object is
created by default. The code below adds 2 tabs to a tab control

void CForm1::Form_Load()

// Add tabs

// "Find_Image" and "Draw_Image" are two images that belong

// to an imagelist control

// You need to set the images before (either at design or run time)

// before you call the following "Add" methods

m_AxTabstrip1.Tabs.Clear();

m_AxTabstrip1.Tabs.Add(NULL, _V("Key1"), _V("Find"), _V("Find_Image"));

m_AxTabstrip1.Tabs.Add(NULL, _V("Key2"), _V("Draw"), _V("Draw_Image"));

}
Difference between SSTab and TabStrip

SSTab:

1) Is a container

2) Can be buggy (always put a frame or picturebox on each tab and site your controls inside
those containers)

3) Probably easier to use & less code

TabStrip:

1) Not a container. You must toggle the visibility/zorder of actual containers, which makes them
appear to be 'contained' by the TabStrip, hence more code

2) Each tab can have an assigned icon/picture from an ImageList

3) If you are already using MS Common Controls in your app, probably the best option.

MSFlexGride Control:

One of the most impressive controls of Visual Basic is the MSFlexGridcontrol.TheMSFlexGrid


control provides all the functionality for building spreadsheet applications, just as the
RichTextBox control provides all the functionality for building word processing applications.
The MSFlexGrid control is an extremely useful tool for displaying information in a tabular form.
Place it on your Forms to present nicely organized data to the user. At first glance, 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).

Basic Properties

The grid’s cells can contain text, numbers, or images. Can also assign a value ‘ to a cell in
several ways, but all methods required to first select the cell by means of its address on the grid
and assign the desired value to its Text property. ‘The address of a cell is given by its Row and
Cot 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, to 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.

Visual Basic has a number of grid controls: the data grid control, the flex grid control, and the
hierarchical flex grid control. Like charts, grids give a way of displaying data. Whereas charts
present data in graphical format, grids appear like spreadsheets.A grid presents the user with a
twodimensional array of individual cells. When you display a grid, it seems that users should be
able to just type the data they want into the grid, but that’s not the way it works. Grid controls
can hold data in each cell when you put it there, but the user can’t simply enter that data—also
add the code to do that. The flex grid control is often used to display database data in read-only
format. It also features the ability to rearrange its columns under user control, as we’ll see, as
well as the ability to display images in each cell instead of just text. Each cell supports word
wrap and formatting. To add a flex grid control to your program, open the Components dialog
box by selecting Project[vbar]Components, click the Controls tab, select the Microsoft FlexGrid
Control entry, then click on OK to close the Components dialog box.
ActiveX Data Objects

Prior to VB6 and the introduction of ADO (ActiveX Data Objects), VB programmers would
generally use DAO (Data Access Objects) to interact with local databases such as MS Access
and use RDO (Remote Data Objects) to interact with client/server databases such as Oracle and
SQL Server. The concept behind Visual Basic ADO was Universal Data Access (UDA), where
one database access method could be used for any data source; it was designed to replace both
DAO and RDO.

The ADO (ActiveX Data Object) data control is the primary interface between a Visual Basic
application and a database. It can be used without writing any code at all! Or, it can be a central
part of a complex database management system. This icon may not appear in our Visual Basic
toolbox. If it doesn’t, select Project from the main menu, then click Components. The
Components window will appear. Select Microsoft ADO Data Control, then click OK. The
control will be added to your toolbox.

ADO collections

Fields: This collection contains a set of Field objects. The Collection can be used in either a
Recordset object or in a Record object. In a Recordset object, each of the Field objects that make
up the Fields collection corresponds to a column in that Record set object. In a Record object, a
Field can be an absolute or relative URL that points into a treestructured namespace (used for
semi-structured dataproviders like the Microsoft OLE DB Provider for Internet Publishing) or as
a reference to the default Stream object associated with that Record object.

Properties: An object can have more than one Property object, which are contained in the
object's Properties collection.

Parameters:A Command object can have several Parameter commands to change its predefined
behavior, and each of the Parameter objects are contained in the Command object's Parameters
collection

Errors: All provider-created errors are passed to a collection of Error objects, while the Errors
collection itself is contained in a Connection object. When an ADO operation creates an error,
the collection is cleared and a new group of Error objects is created in the collection.
ADO objects

Connection:

The connection object is ADO's connection to a data store via OLE DB. The connection object
stores information about the session and provides methods of connecting to the data store. As
some data stores have different methods of establishing a connection, some methods may not be
supported in the connection object for particular OLE DB provider. A connection object
connects to the data store using its 'Open' method with a connection string which specifies the
connection as a list of key value pairs.

Example: "Provider='SQLOLEDB';Data Source='TheSqlServer'; Initial

Catalog='Northwind';Integrated Security='SSPI';".

The start of this connection string must identify the type of data store connection that the
connection object requires:

an OLE DB provider (for example SQLOLEDB), using the syntax "provider=";

a file name, using the syntax "file name=";

a remote provider and server (see RDS), using the syntax "Remote provider=" and

"Remote server="; or

an absolute URL, using the syntax "URL="

Command:

After the connection object establishes a session to the data source, instructions are sent to the
data provider via the command object. The command object can send SQL queries directly to the
provider through the use of the CommandText property, send a parameterised query or stored
procedure through the use of a Parameter object or Parameters collection or run a query and
return the results to a dataset object via the Execute method. There are several other methods
that can be used in the Command object relating to other objects, such as the Stream, RecordSet
or Connection objects.

Recordset:A recordset is a group of records, and can either come from a base table or as the
result of a query to the table. The RecordSet object contains a Fields collection and a Properties
collection. The Fields collection is a set of Field objects, which are the corresponding columns in
the table. The Properties collection is a set of Property objects, which defines a particular
functionality of an OLE DB provider. The RecordSet has numerous methods and properties for
examining the data that exists within it. Records can be updated in the recordset by changing the
values in the record and then calling on the Update or UpdateBatch method.

Immediate:

The recordset is locked using the adLockOptimistic or adLockPessimistic lock. The data are
updated at the data source after the record is changed and the Update method is called.

Batch:

The recordset is locked using adLockBatchOptimistic and each time Update is called the data are
updated in a temporary buffer. Finally, when UpdateBatch is called the data are completely
updated back at the data source. This has the advantage of it all being done in memory, and if a
problem occurs then UpdateCancel is called and the updates are not sent to the data source.

Transaction:

If the OLE DB provider allows it, transactions can be used. To start the transaction, the
programmer invokes the BeginTrans method and does the required updates. When they are all
done, the programmer invokes the CommitTrans method. RollbackTrans can be invoked to
cancel any changes made inside the transaction and roll back the database to the state before the
transaction began.

Record:

This object represents one record in the database and contains a fields collection. ARecordSet
consists of a collection of Record objects.

Stream:

A stream, mainly used in a RecordSet object, is a means of reading and writing a stream of
bytes. It is mostly used to save a recordset in an XML format, to send commands to an OLE DB
provider as an alternative to the CommandText object and to contain the contents of a binary or
text file.

Parameter:A parameter is a means of altering the behaviour of a common piece of functionality,


for instance a stored procedure might have different parameters passed to it depending on what
needs to be done; these are called parameterised commands.
Field:Each Record object contains many fields, and a RecordSet object has a corresponding
Field object also. The RecordSet object's Field object corresponds to a column in the database
table that it references.

Property:

This object is specific to the OLE DB provider and defines an ability that the provider has
implemented. A property object can be either a built-in property — it is a well-defined property
implemented by ADO already and thus cannot be altered — or can be a dynamic property —
defined by the underlying data provider and can be changed

Error:

When an OLE DB provider error occurs during the use of ADO, an Error object will be created
in the Errors collection. Other errors do not go into an Error object, however. For instance, any
errors that occur when manipulating data in a RecordSet or Field object are stored in a Status
property.

Basic usage

Some basic steps are required in order to be able to access and manipulate data using ADO :

1. Create a connection object to connect to the database.

2. Create a recordset object in order to receive data in.

3. Open the connection

4. Populate the recordset by opening it and passing the desired table name or SQL statement as a

parameter to open function.

5. Do all the desired searching/processing on the fetched data.

6. Commit the changes you made to the data (if any) by using Update or UpdateBatch methods.

7. Close the recordset

8. Close the connection


The Data Source

Via Windows Control Panel, double-click on Administrative Tools, then Data Sources (ODBC).
The ODBC Data Source Administrator screen is displayed, as shown below. Click on the System
DSN tab.
Click the Select button. The Select Database dialog box appears. On a default installation of
VB6 or Visual Studio 6, the BIBLIO.MDB sample database should reside in the folder
C:\Program Files\Microsoft Visual Studio\VB98. Navigate to that folder, select
BIBLIO.MDB from the file list, and click OK.

Using the ADO Data Control:

ADO stands for ActiveX data objects. As ADO is ActiveX-based, it can work in different
platforms and different programming languages. Besides, it can access many different kinds of
data such as data displayed in the Internet browsers, email text and even graphics other than the
usual relational and non-relational database information.To be able to use ADO data control, you
need to insert it into the toolbox. To do this, simply press Ctrl+T to open the components dialog
box and select Microsoft ActiveX Data Control 6. After this, you can proceed to build your
ADO-based VB database applications.

OLE DB

Object Linking and Embedding Database (OLE DB) is a group of APIs used to facilitate and
abtract access to application data of different file formats, including spreadsheets, structured
query language (SQL)-based database management systems (DBMS), indexedsequential files,
and personal databases. OLE DB is based on the Component Object Model (COM) and is part of
the Microsoft Data Access Components (MDAC) software package, which is used to read and
write data. The OLE DB object model components are data source objects (DSO), command
objects, rowset objects and session objects. OLE DB uses abstraction sets to segregate stored
application data, because different programs require access to different DSO types.

OLE DB classifications are:Consumers:

Applications requiring data access

Providers: Software components that supply consumer data by using OLE DB APIs When
requesting OLE DB data, an application follows this sequence: Initialize the OLE.

1. Establish a connection to the data's source.

2. Use a command to request access.

3. Process the application query to acquire request results.

4. Provide the requested DSO.


CRYSTAL AND DATA REPORTS

Crystal Reports and Data Reports are report generators. Crystal Reports is a third party product
developed by Seagate of Singapore. It has been bundled with various data access tools. It can
work with Visual Basic on your PC or with the AS/400 as well.

PREREQUISITES FOR WORKING WITH CRYSTAL REPORTS

Hardware : A printer must be installed. It need not be physically connected though. This is
because Crystal Reports builds the reports based on the properties of the printer.

Application : We can access Crystal Reports only through the VB IDE. If Crystal Reports has
not been installed then follow the steps given below. Prepare a pencil copy of the report structure
that we want to create.

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

DATA REPORT

Data Report as it stands today is meant for programmers. To use Data Report, we need to use
ADO or Data Environment.

Steps to generate a report using the Data Report:

Create a data source using ADO Add the Data Report object to our project Place textboxes
representing the various fields that we want on the DataReport object. Link the Textboxes to the
various fields of the data source. Display the report using the Show method.

GETTING ACQUAINTED WITH THE DATA REPORT DESIGNER

To add Data Report designer to the form right click on the toolbox and select Components from
the pop-up menu. Click on the ‘Designers’ tab and select ‘Data Report’. The Data Report
Designer is the form on which we design the layout of the report. The Data Report object is the
programmable object that represents the Data Report Designer
PARTS OF THE DATA REPORT

The Data Report consists of three main components:

Data Report Object

Section Object

Data Report Controls

Data Report Object can be used to programmatically control the form which is its Visual
Component . The Data Report Designer consists of a number of Sections like header, footer and
detail sections. Each of these section objects can be configured at design time or controlled
through code at run time. Each section has a set of properties that can be manipulated. Data
Report Controls are special control that can be created on the Data Report Designer and these
tools are placed under separate tab in the toolbox.

The default Data Report Designer contains these Sections:

Report Header: Title of the report is given in this section. If the first page of the report should
contain only the title, ForcePageBreak property is set to rptPageBreakAfter.

Page Header : To give the page heading.

Group Header/Footer : To give the heading for every group. A group header must also have a
group footer.

Details : This section contains the actual data. The records are displayed in this section.

Page Footer : To give the page footer and it can be page number or any relevant text like the
date of report etc.

Report Footer :To give the summary for the report which can contain address, bibliography etc.
The Report Footer appears between the last Page Header and Page Footer.

DATA REPORT CONTROLS

TextBox Control (RptTextBox) ---> To display text or other formatted data.

Label Control (RptLabel) ---> To display the labels on the report to identify fields or sections.

Image Control (RptImage) ---> To display pictures on the report. This control cannot be tied to a
data field.
Line Control (RptLine) ---> To draw lines on the report.

Shape Control (RptShape) ---> To draw rectangles, circles, etc on the report.

Function Control (RptFunction) --->Special Textbox that calculates values as the report is
generated.

EXTRACTING THE DATA

Create a data source using ADO. Invoice.mdb is used. Create a list that consists of
CustomerName,

Customer_City and Order_Value.

Dim adoconAsADODB.Connection

Dim adorsAsADODB.Recordset

This code has declared an ADO Connection and ADO Recordset.

To create a connection and recordset add the following code in the Form load event :

Set adocon = New ADODB.Connection

adocon.Open “DSN-Invoice”

Add a CommandButton and enter the following code in the click event:

Set adors = adocon.Execute (“Select distinctrowCustomer_data.customer_name,


Customer_data.address2,

orders_data.ordervalue from Customer_data, orders_data where Customer_data.customer_code


=

orders_data.customercode”).

WORKING WITH THE DATA REPORT

Add three RptTextBox controls to the Data Report designer. The textbox caption is Unbound
which means that these controls are not bound to any data source or data field. Binding the
RptTextBox to a data field: In the Properties Window of the RptTextBox enter the name of the
field to be displayed in the Data Field property. The Data Report designer will look as in the
figure:
DISPLAYING THE REPORT

The Recordset is created and the fields are assigned in the Data Report Designer. To link the
recordsource to the Data Report Show method of the Data Report is called. Add the following
codes in the command button click event: Set DataReport1.DataSource = adors

DataReport1.Show

Run the program now.


CREATING MULTIPLE REPORTS

There are two ways of handling the ‘multiple reports’ situation.We can create a Data Report or
we can display different data using only one or a few DataReport forms. Both the approaches
have their merits and demerits.

Let us use the DataReport1 to create another report. In this report we will display the Customer
Name, Customer Address and the Order Value. Add another button to the form. Give the caption
like “Report2”.

Add the following code in the click event of this button:

Set adors = adcon.Execute(“Select distinctrowCustomer_data.customer_name,


Customer_data.address2,

orders_data.ordervalue from Customer_data, orders_data where Customer_data.customer_code


=

orders_data.customerid”)

Set DataReport1.DataSource = adors

DataReport1.Sections(2).Controls(“Label2”).Caption = “Customer Name”

DataReport1.Sections(2).Controls(“Label3”).Caption = “Address”

DataReport1.Sections(2).Controls(“Label4”).Caption = “Order Value”

DataReport1.Sections(3).Controls(“Text3”).DataField = “ordervalue”

DataReport1.Sections(3).Controls(“Text2”).DataField = “address2”

DataReport1.Sections(3).Controls(“Text1”).DataField = “customer_name”

DataReport1.Sections(5).Controls(“Function1”).DataField = “ordervalue”

DataReport1.Show

A fresh recordset is created and the value for the column headers are given during runtime.
Similarly the data that has to be displayed is also specified at runtime. In this way we can create
multiple reports using one DataReport designer.

You might also like