Visual Basic 6.0 Programming Guide
Visual Basic 6.0 Programming Guide
VB is imitated by using the Start → All Programs → MS Visual Studio → MS Visual Basic
6.0. By Clicking the VB 6.0 icon in Desktop it can be opened. Below Figure shows the interface screen of
VB 6.0 with Menu bar, Toolbar and etc.
Toolbox
Toolbox contains a set of controls that are used to place on a form at design time thereby creating
the user interface area. Additional controls can be included in the toolbox by using the Components menu
item on the Project menu. A toolbar is shown in the below.
Pointer PictureBox
Label Textbox
Frame CommandButton
CheckBox Option Button
ComboBox List Box
Hscroll Bar VScrollBar
Timer Drive ListBox
DirListBox FileListBox
Shape Line
Image Data
OLE
• The pointer helps to move and resize the controls and Forms
• Label displays a text that the user cannot modify or interact with.
• Frame control serves as a visual and functional container for controls.
• CheckBox displays a True/False or Yes/No option.
• TextBox is a control used to display message and enter text.
• The ListBox displays a list of items from which a user can select one.
• ComboBox contains a TextBox and a ListBox. This allows the user to select an item from the
dropdown ListBox or to type a selection in the TextBox.
• HScrollBar or VScrollBar controls allow the user to select a value within the specified range of values.
• Timer control executes timer events at specified intervals of time.
• DirListBox allows the user to select directories and paths, which are displayed.
• Shape control adds a shape to a Form.
• Image control is used to display icons, bitmaps, metafiles, etc.
• OLE control is used to link or embed an object, display and manipulate data from other Windows
based applications
• PictureBox displays icons/bitmaps and metafiles. It display text or acts as a visual container for other
controls.
• CommandButton carries out the specified action when the user chooses it.
• The OptionButton control which is a part of an option group allows the user to select one option even
if it displays multiple choices.
• The DriveListBox displays the valid disk drives and allows the user to select one of them.
• The FileListBox displays a set of files from which a user can select the desired one.
• Line controls draws a straight line to the Form.
• Data control enables the user to connect to an existing database and display information from it.
Form serves as a window that can be customized and controls, graphics and pictures can also be
added to it.
Project Explorer
The project explorer serves as a quick reference to the various elements of a project namely form,
classes and modules. All of the objects that make up the application are packed in a project. A typically
project contains one form, which is a window that is designed as part of the program’s interface.
Properties Window
The Properties window exposes the various characteristics of selected objects. Each and every
Form in an application is considered an object. All the characteristics of an object are called its properties.
Object Browser
The object Browser allows browsing through the various properties, events and methods that are
made available to us. It is accessed by selecting Object Browser from the View menu or by pressing F2.
properties such as Enabled, Font, Multi Line, Text, Visible, etc. A method is an action that can be
perfomed on objects. The TextBox has associated with Refresh, SetFocus etc.
VB programs are built around Events. Events are various things that can happen in a program. In
an event driven application, the program statements are executed only when calls a specific part of the
code that is assigned to the events.
Border Style
Forms can have a variety of types of borders. Various borders that are available in VB are Name,
Fixed Single, Sizeable, Fixed Double, Fixed ToolWindow and Sizeable ToolWindow.
Caption
The title for the window is stored in the Caption property, the caption appears below the form’s
icon when the form is minimized.
Control Box
This property determines whether the Control box, available by clicking the upper left corner of a
window, will be shown or not.
Icon
This property specifies the icon for the window in the upper left corner of the window.
MousePointer
This property sets the value that indicates the type of mouse pointer displayed when the mouse
pointer appears over a particular area of the object at runtime.
MaxButton
This property indicates Whether the Maximize button should be shown and the Maximize choice
made available in the Control Box menu.
MDIChild
This property specifies if this window must be shown within a multiple document interface (MDI)
window.
MinButton
This property indicates whether the Minimize button should be shown and the Minimize choice
made available in the Control Box menu.
Moveable
By setting it to False, it is possible to prevent the user from moving the window manually. This is
useful for splash screens and other informational dialog boxes that are shown and dismissed quickly.
StartUpPosition
Instead of writing code to position user window, user can pick a starting position from this drop-
down menu. The available choices are Manual, CenterOwner, CenterScreen and Windows Default.
WindowState
This property indicates whether the window is shown normally, maximized or minimized. It is
possible to pick a starting state for your Form at design time so that when you show the window, it comes
up in that state.
Show Method
The Show method is used to display the Form object. For example, to display the form
frmCalculator, the following code is written.
[Link]
A New Standard EXE Project item is selected from the File menu that displays a New Project
dialog box. The standard EXE is chosen for normal applications. Visual Basic responds by displaying the
Project and Form windows. Though no change have made to the Form, it is better to save the project at
the early stage of the design. When a project is saved, two files are saved, namely Project file and Form
file. The project file has .VBP extension and its contains information that VB uses for building the
project. The Form file contains information about from and has .FRM extension. The Save Project
command is selected from the File Menu. VB responds by displaying a Save File As dialog box. A file
name called [Link] is given and Save button has to be clicked on. VB than display a Save Project As
dialog box. The project file is saved as [Link].
Code editor window includes List Properties/Methods which presents a list of properties available
for controls.
The application is run by clicking Start command form the Run menu or Pressing F5. When the
Display button is clicked the message Visual Basic 6 is displayed in the TextBox. Clicking the Clear
button clears the message, while button terminates the application.
Ending an Application
The End statement is used to terminate the execution of the application. It unloads all the forms
from memory.
Class modules (.CLS filename extension) are the foundation of object oriented programming in VB.
New objects can be created by writing code in class modules. Each module can contain:
➢ Declaration
May include constant, type, variable and DLL procedure declarations.
➢ Procedure
A sub function or property procedure that contains piece of code that can be executed as a unit
Data Types
By default Visual Basic variables are of the variant data type. The variant data type can store
numeric, date/time or string data. When a variable is declared, a data type is supplied for it that
determines the kind of data of data it can store. The fundamentals data types in VB including variant are
integer, long, single, double, string, currency, byte and Boolean. VB supports a vast array of data types.
Each data type has limits to the kind of information and minimum and maximum values it can hold.
Variables
Variables are used for storing values temporarily. A defined naming strategy has to be followed
while naming a variable. A variable name must begin with an alphabet letter and should not exceed 255
characters. It must be unique within the same scope. It should not contain any special characters such as
%, &, #, etc. There are ways of declaring variable in VB. Depending on where variable are declared and
how they are declared, user can determine how they can be used in the application. The different types of
declaring variables in VB are discussed below
Explicit Declaration
Declaring a Variable tells Visual Basic to reserve space in memory. It is not a must that a variable
should be declared before using it. Automatically whenever Visual Basic encounters a new variable, it
assigns the default variable type and value. This is called implicit declaration.
Though this type of declaration is easier for the user, it is advisable to declare them explicitly. The
variables are declared with a Dim statement to name the variable and its type. The As type clause in the
Dim statement allows to define the data type or object type of the variable. This is called explicit
declaration.
Syntax
Dim variable [As type]
Example
Dim strname As String
Dim intCounter As Integer
Scope of Variables
A scope of variable to a procedure-level (local) or module-level variable depending on how it is
declared. The scope of variable, procedure or object determines which parts of the code in the application
are aware of the variable’s existence.
A variable is declared is general declaration section of a Form and hence is available to all the
procedure. Local variables are recognized only in the procedure in which they are declared. They can be
declared with Dim and Static keywords. If we want a variable to be available to all the procedures within
the same module or to all the procedures in an application, a variable is declared with border scope.
Local Variables
A local variable is one that is declared inside a procedure. This variable is only available to the
code inside the procedure and can be declared using the Dim statement
Dim intTemp As Integer
The local variables exist as long as the procedure in which they are declared, is executing. Once a
procedure is executed the value of its local variables are lost and memory used by these variables is freed
and can be reclaimed. Variables that are declared with keyword Dim exist only as long as the procedure is
being executed.
Static Variables
Static variables are not re-initialized each time Visual Basic invoke a procedure and thus retains or
preserves value even when a procedure ends. In case we need to keep track of the number of times a
CommandButton in an application is clicked, a static counter variable has to be declared. These static
variables are also ideal for making controls alternatively visible or invisible. A static variable is declared
as given below.
Static intPermanent As Integer
Variables have a lifetime in addition to scope. The values in module-level and public variables are
preserved for the lifetime of an application whereas local variables declared with Dim exist only while the
procedure in which they are declared is still being executed. The value of a local variable can be
preserved using the Static keyword. The following procedure calculates the running total by adding new
values to the previous variable value.
Function RunningTotal()
Static Accumulate
Accumulate = Accumulate + num
RunningTotal = Accumulate
End Function
If the variable Accumulated was declared with Dim instead of Static, the previously accumulated values
would not be preserved across calls to the procedure and the procedure would return the same value with
which it was called. To make all variables in a procedure static, the Static keyword is placed at the
beginning of the heading in the statement below.
Static Function RunningTotal()
code. For example, if the public integer variable intY is declared in both Forml and Modulel of a project
it can be referred as [Link] and [Link].
Public vs Local Variables. A variable can have the same name and different scope. For example, we can
have a public variable named R and within a procedure we can declare a local variable R. References to
the name R within the procedure would access local variable and references to R outside the procedure
would access the public variable.
Sub Procedures
A sub procedure can be placed in standard, class and form module. Each time the procedure is
called, the statements between Sub and End Sub are executed. The syntax for a sub procedure is as
follows.
[Private | Pub1ic] [Static] Sub procedurename[(arglist)]
[Statements]
End Sub
arglist is a list of argument names separated by commas. Each argument acts like a variable in
the procedure. There are two types of Sub Procedures-general procedures and event procedures.
Event Procedures
An event procedure is a procedure block that contains the control’s name, an under score( _ ), and
the event name. The following syntax represents the event procedure for a Form_Load event.
Private Sub Form_Load( )
… Statement block …
End Sub
Event Procedures acquire the declaration as Private by default.
General Procedures
A general procedure is declared when several event procedures perform the same actions. It is a
good programming practice to write common statement m a separate procedure (general procedure) and
then call them in the event procedure. In order to add a general procedure following steps are followed.
• The Code window is opened for the module to which the procedure is to be added.
• The Add Procedure option is chosen from the Tools menu, which opens as Add Procedure dialog box
• The name of the procedure is typed in the Name textbox.
• Under Type, Sub is selected to create a Sub procedure, Function to create a Function procedure or
Property to create a Property procedure.
• Under Scope, Public is selected to create a procedure that can be invoked the module or Private to
create a procedure that can be invoked only from within the module.
We can also create a new procedure in the current module by typing Sub ProcedureName.
Function ProcedureName or Property ProcedureName in the Code window. A Function procedure returns
a value and a Sub procedure does not return a value.
Function Procedures
Functions are like sub procedures, except that they return a value to the calling procedure. They
are especially useful for taking one or more pieces of data, called arguments and performing some tasks
with them. Then the function returns a value that indicates the results of the tasks which are complete
within the function. The following function procedure calculates the third side or hypotenuse of a right
triangle, where A and B are the other two sides. It takes two arguments A and B (of data type Double) and
finally returns the result.
Function Hypotenuse(A As Double, B As Double) As Double
Hypotenuse = sqr(A^2 + B^2)
End Function
The above function procedure is written in the general declarations section of the Code window. A
function can also be written by selecting the Add Procedure dialog box from the Tools menu and by
choosing the required scope and type.
Property Procedures
A property procedure is used to create and manipulate custom properties. It is used to create read
only properties for Forms, Standard modules and Class modules. Visual Basic provides three kinds of
property procedures - Property Let that sets the value of a property, Property Get procedure that returns
the value of a property and Property Set procedure that sets the reference to an object.
Control Structure
If...Then...Else Statement
The If…Then block is used for conditional execution of one or more statements.
If Condition Then
Statements
End If
The statement is executed only if the condition is true. The condition is usually a comparison, but it can
be any expression that evaluates a numeric value. If…Then-Else block is used to define several blocks of
statements, in order to execute one block. The following block of statement illustrates If...Else...End If
statements.
If A=l Then
Statements
Else
Statements
End if
The following example illustrates the If...Then ...Else statement.
Private Sub Commandl_Click()
If Val([Link]) < 10 Then
MsgBox “It is a Single Digit Number"
Else lf Val([Link]) < 100 Then
Select…Case Statement
Select...Case structure is an alternative to If…Then .... Elself for selectively executing a single
block of statements from among multiple blocks of statement. Select...Case is more convenient to use
than the If..Else..End If. The following program block illustrates the working of Select ... Case.
Select case Index
Case 0
Statements
Case 1
Statements
End select
Select…Case structure evaluates an expression once at the top of the structure, where as If..Then…Else If
structure evaluates different expressions for each Else If statement.
msgbox name$
Loop Until name$ = “NIL”
End Sub
At the runtime it asks for the Name and until it is entered as “NIL” the loop remains infinite.
If we want to specify the lower limit, then the parenthesis should include both the lower and upper
limit along with the To keyword. An example for this is given below.
Dim lengths(1 To 10) As Integer
In the above statement, an array of 10 elements is declared but with indexes running from 1 to 10. A
public array can be created using the keyword Public instead of Dim as shown below:
Public digits(20) As Integer
Multidimensional Arrays
A multidimensional array is used when we need to represent or store information of different
dimension. For example to hold the student registration number and marks of the student, we need to
mention its x and y co-ordinates. The following statement declares a two-dimensional 50 by 50 array
within the procedure.
Dim Marks(50,50)
It is also possible to define explicit lower limits for one or both the dimensions as for fixed size arrays.
An example for this is given here.
Dim StudMarks(101 to 200, 1 to 100)
Any number of dimensions can he declared in a multidimensional array. An example for a three
dimensional array with defined lower limits is given below.
Dim StudDetails(101 To 200,1 To 100,1 To 100)
Dynamic Array
There will be a situation when the user may not know the exact size of the array at design time.
Under such circumstances, a dynamic array can be initially declared and the user can then add elements
when needed instead of declaring the size of the array at design time.
Dim NewArray()
The actual number of elements can be allocated using a ReDim statement. This example allocates the
number of elements in the array based on the value of the variable Y.
ReDim NewArray(Y + 1)
The ReDim statement can appear only in a procedure, which is an executable statement. The same way of
declaration as used for fixed arrays is used for declaring ReDim statement also. ReDim is an executable
statement. The lower and upper limits for each dimension can also be specified explicitly as in a fixed size
array. An example for this is given below
ReDim FirstArray(4 to 12)
Each time on executing the ReDim statement, the current data stored in the array is lost and the default
value is set. But if we want to change the size of the array without losing the previous data, we have use
the preserve keyword with the ReDim statement. This is shown in the example given below.
ReDim Preserve NewArray(Ubound(FirstArray)+1)
When the Preserve keyword is used, only the upper limits of the last dimension in a multi dimensional
array can be changed. No other dimensions or the lower limit of the last dimension can be changed.
The user defined data type can be declared with a variable using the Dim statement as in any other
variable declaration statement. An array on these user-defined data types can also be declared. An
example to consolidate these two features is given below.
Dim Electronicgoods As ProductDetails ‘ One record
Dim Electronicgoods(lO) As ProductDetails ‘ An array of 11 record
A User-defined type can be referenced in an application by using the variable name in the
procedure along with the item name in the Type block. Say, for example if the text property of a textbox
namely text1 is to be assigned the name of an electronic item is written as given below.
[Link] = [Link]
If the same is implemented as an array, then the statement changes to the following.
[Link] = Electronicgoods(i).prodname
Here i is the index of the array. User defined types can also be passed to procedures to allow many related
items as one argument.
Sub ProdData(Electronicgoods As ProductDetails)
[Link] = [Link]
[Link] = [Link]
End sub
Constants
Constants are named storage locations in memory, the value of which does not change during
program execution. They remain the same throughout the program execution. When the user wants to use
a value that never changes, a constant can be declared and created. The Const statement is used to create
a constant. Constants can be declared in local, form, module or global scope and can be public or private
as for variables. Constants can be declared as illustrated below.
Public Const gravityconstant As Single = 9.81
represents the time between 0:00:00 and 29:59:59 hours inclusive. The system's current date and time can
be retrieved using the Now, Date and Time functions in VB, The Now function retrieves the date and
time, While Date function retrieves only date and Time function only retrieves the time. To display both
the date and time together a message box is displayed using the statement given below.
MsgBox "The current date and time of the system is" & Now
Here ‘&’ is used as a concatenation operator to concatenate the string and the Now function. Selective
portions of the date and time value can be extracted using following functions given in the below.
Function Extracted Portion
Year() Year(Now)
Month() Month(Now)
Day() Day(Now)
WeekDay() WeekDay(Now)
Hour() Hour(Now)
Minute() Minute(Now)
Second() Second(Now)
The calculation and conversion functions related to data and time are listed below
Function Description
DateAdd( ) Returns a date to which a specific interval has been added
DateDiff( ) Returns a Long data type value specifying the interval between the two values
DatePart( ) Returns an Integer containing a specified part of a given date.
DateValue( ) Converts a string to a date.
TimeValue( ) Converts a string to a time.
DateSerial( ) Returns a date for a specified year, month and day.
DateDiff Function
The DateDiff function returns the interval between two dates in terms of years, months or days.
The syntax for this given below
DateDiff(interval, date1, date2 [,firstdayofweek[,firstdayofweek]])
Format Function
The format function accepts a numeric value and converts it to a string in the format specified by the format
argument. The syntax is given below
Format(expression[, format [,firstdayofweek[,firstdayofweek]]])
The Format function syntax with various parts are listed below
Part Expression format
Expression Required any valid expression
format Optional. A valid named or user-defined format expression
firstdayofweek Optional. A constant that specifies the first day of the week
firstweekofyear Optional. A constant that specifies the first week of the year
Logical Operators
There are six logical operators. The most common operators are And, Or and Not operators. And
Xor, Equ and Imp operators are advanced operators.
Operator Functions
And Combines two expressions. Both the expression must be True for the entire expression
to be True
Or Combines two expressions. If one of the expression is True for the entire expression is
True
Not The Negative of single expression
Xor Combines two expressions. The entire expression consider to be True if the two
expression are not both True or False
Equ Combines two expressions. Both expression must be True or False for the entire
expression to be True
Imp Combines two expretyg rssions. The entire expression is True except when first
expression is True and the second expression is False
Test Strings
VB string functions can manipulate strings in applications. Below table given brief description
about the string functions in VB.
Function Name Purpose
StrComp( ) Compare two strings
Format, Lcase( ) Converts the string to lowercase
Format, Ucase( ) Converts the string to uppercase
Space, String( ) Creates a string of repeating character
Len( ) Finds the length of a string
Format( ) Format a string
Lset( ), Rset( ) Justify a string
Instr( ) Returns a Variant(Long) specifying the position of the
first occurrence of one string within another
Left( ) Returns a Variant(String) containing a specified number
of characters from the left side of the string
Mid( ) Returns a Variant(String) containing a specified number
of characters from a string
Right( ) Returns a Variant(String) containing a specified number
of characters from the right side of the string
Trim( ) Returns a Variant (String) containing a copy of a
specified string without leading spaces and trailing
spaces.
Ltrim( ) Returns a Variant (String) containing a copy of a
specified string without leading spaces.
Rtrim( ) Returns a Variant (String) containing a copy of a
specified string without trailing spaces.
StrConv( ) Converts the strings
**********
In addition to properties and events, methods can also be used to manipulate controls from code.
For example, the Move method can be used with some controls to change their location and size. Most of
the controls provide choices to users that can be in the form OptionButton or CheckBox controls, ListBox
entries or ScrollBars to select a value.
Classification of Controls
Visual Basic controls are broadly classified as standard controls, ActiveX controls and insertable
objects. Standard controls such as CommandButton, Label and Frame controls are contained inside a
.EXE file and are always included in the 'l'oolbox which cannot removed. ActiveX controls exist as
separate files with .VBX or .OCX extension. They include specialized controls such as
• MSChart Control
• The Communicating Control
• The Animation control
• The List View control
• An ImageList control
• The Multimedia control
• The Internet Transfer control
• A WinSock control
• The Tree View control
• The Syslnfo Control
• The Picture Clip control
These built-in ActiveX controls will be discussed at length in Chapter 14. Some of these objects support
OLE automation, which allow programming another application object from within Visual Basic
application.
By default, Visual Basic assigns a tab order to controls as we draw them on a form, with the
exception of the Menu, Timer. Data, Image, Line and Shape controls which are not included in the tab
order. At run time, invisible or disabled controls and controls that cannot receive the focus (Frame and
Label controls) remain in the tab but are skipped during tabbing. Setting the TabIndex property of
controls is a must in development environment.
Each new control is placed last in the tab order. If we change the value of a control's
Tablndex property to adjust the default tab order, VB automatically re-numbers the TabIndex of other
controls to reflect insertion and deletions. We can make changes at the design time using the Properties
window or at run time in code.
• We can write code that changes the caption property displayed by a Label control in response to
events at run time. We can also use a Label to identify the control, such as TextBox control, that
doesn't have its own Caption property.
• The AutoSize and WordWrap properties should be set if users wants the Label to properly display
variable-length lines or varying numbers of lines.
• A Label control can also act as a destination in a DDEconversation. Set the LinkTopic property to
establish a link, set the LinkItem property to specify an item for the conversation, and set the
LinkMode property to activate the link. When these properties have been set, VB attempts to initiate
the conversation and displays a message if it’s unable to do so.
• Set the UseMnemonic property to True if you want to define a character in the Caption property of
the Label as an access key
Example
• A new Standard EXE project is opened and the Form and the project is saved as Option. frm and
[Link] respectively.
• The Form is designed as per the following specifications table. The design Form appears as shown
below Figure.
The Val function is used to translate string to a number and can recognize Octal and
Hexadecimal strings. The LTrim function trims the leading blanks in the text. The following code is
entered in the click event of the OptionButton controls.
Private Sub optOct_Click()
[Link] = Oct(currentval)
Department of Computer Science, HiSAC, Erode 23
Visual Basic Lesson Notes - Unit I
End Sub
Private Sub optHex_Click()
[Link] = Hex(currentval)
End Sub
The List property sets or returns that text of an item in a list box. The index number is passed to the list
property to specify the item to be accessed. To return the text of the selected item, the ListIndex property
is passed as shown in the following example:
Str = [Link]([Link])
To return the string for a ListBox, the Text property of the control is used as shown in the following
example:
Str = [Link]
The Dropdown combo box first appears as only an edit area with a down arrow button at the right.
The list portion stays hidden until the user clicks the down-arrow button to drop down the list portion. The
user can either select a value from the list or type a value in the edit area.
The Drop-down list combo box turns the combo box into a drop-down list box. At run time, the
control looks like the drop-down combo box. The user could click the down arrow to view the list. The
difference between Dropdown combo and Drop-down list combo is that the edit area in the dropdown list
is disabled. The user can select only one of the list items and cannot type an item in the edit area. This
area, however, does display the item currently selected in the list.
Generally the ComboBox is preferred when there is a list of choices. It saves space on a Form. The
full list is not displayed until the user clicks the down arrow (except for style 1). An illustration of
different types of combo boxes is shown in below figure.
The AddItem method is used to add values to the ComboBox and ListBox. Similarly the
RemoveItem method is used to remove items from the ListBox or ComboBox. Let us now develop a
small application that uses AddItem, RemoveItem and Clear methods. The application contains a
TextBox, ListBox and three Label and CommandButton controls as shown in below figure. It is designed
in name in the TextBox. When the Add button is clicked, the types name is added in the ListBox. A
particular entry in the ListBox can be removed by selecting the item and choosing the Remove button.
Example
For the supermarket SM & Co. develop an application to Add, Remove, Clear the list of items and
then finally close the application.
Following event procedure are added for the TextBox, CommandButton and ListBox controls.
Private Sub Text1_Change()
[Link] = (Len([Link]) > 0)
End Sub
shown below where thumb of the ScrollBar is positioned at the centre. When the thumb’s position is
changed, it should in the TextBox.
choice = “*”
End Sub
Private Sub cmdDiv_Click()
[Link] = “”
preval = curval
curval = 0
choice = “/”
End Sub
To print the result on the TextBox, the following code is entered in the cmdEqual_Click( ) event
procedure.
Private Sub Command2_Click()
Select Case choice
Case "+"
result = preval + curval
[Link] = Str(result)
Case "-"
result = preval - curval
[Link] = Str(result)
Case "*"
result = preval * curval
[Link] = Str(result)
Case "/"
result = preval / curval
[Link] = Str(result)
End Select
curval = result
End Sub
Save and Run the project. On clicking digits of user ‘s choice and an operator button, the output appears
as shown below:
Writing a Program
Develop an application for the supermarket SM & CO, when the label tags for the items have to be
obtained in different colours and size.
A program contains a menu bar with two titles: Colours and Size. The Colours menu allows selection of a
colour from a menu and files the program's Form with the selected colour. The Colours menu has menu items
Fillcolour and Exit. When the FillColour menu is clicked another menu pops up with a list of colours. This is a
submenu of the menu FillColour. A menu item can have a maximum of four levels of submenus. The Form of
the program is filled with the selected colour from the popup menu. The Size menu contains menu items Small
and Large.
Example
• A new Standard EXE project is opened and the Form and the project files are saved as [Link] and
[Link].
• The Form is designed as per the properties table given below
Object Property Settings
Form Caption COLOUR / SIZE
Name frmColour
The menu items are for the Form is designed as per the following specification listed below:
Object Settings
&Colours mnucolour
...&Fill Colour mnuFillColour
. .... &Red mnuRed
. .... &Green mnuGreen
. .... &Blue mnuBlue
&Size mnuSize
... &Small mnuSmall
...&Large mnuLarge
The following steps are performed to create the full menu application.
• After selecting the Menu Editor, &Colours is typed in the Caption TextBox and mnucolour in the Name
TextBox. The '&' character underlines the letter C. This property allows to us to press Alt + C while the
program is running which has the same effect of clicking Colours.
• The Next button is clicked and &FilI Colour is typed in the Caption TextBox and mnuFillColour in the
Name TextBox. The right arrow button is now clicked.
• The Next button is clicked and &Exit is typed in the Caption TextBox and mnuSize the Name TextBox.
The left arrow button is now clicked.
• The Next button is clicked and &Size is typed in the Caption TextBox and mnuSize in the Name TextBox.
The left arrow button is now clicked.
• Now the next button is clicked and S&maIl is typed in the Caption TextBox and mnuSamll in the Name
TextBox. The right arrow is clicked.
• The Next button is clicked and &Large is typed in the Caption TextBox and mnuLarge in the Name
TextBox.
• When FillColour menu item is selected, a submenu with Red, Green and Blue should pop-up. Hence, these
items should be included below the Fill Colour item.
[Link] = False
[Link] = True
End Sub
When the menu item Large is selected, the mnuLarge_Chck.( ) procedure is executed which maximizes the size
of the Form and disables the Large menu item. The size of the Form is changed by setting the WindowState
property of the Form.
Private Sub mnuSmall_Click()
[Link] = 0
[Link] = False
[Link] = True
End Sub
End statement is added in the mnExit_Click( ) To terminate the application. When the menu it Small selected,
mnuSmall_Click() procedure is executed which minimizes the size of the Form and disables the Small menu
item.
Popup Menu
A pop-up menu is a floating menu that is displayed over a Form independent of the menu bar. Pop-up
menus are also called context menu because the items displayed on the pop-up menu depend on where the
pointer is located when the right mouse button is clicked. Any menu can be displayed as a pop-up menu at run
time provided it has one menu item. The following code displays the Colours menu when the user clicks the
right mouse button over the Form at run time.
Private Sub Form_MouseDown(Button As Integer, Shift As
Integer, X As Single, Y s Single)
If Button = 2 Then
PopupMenu mnuCo1ors
End If
End Sub
The first argument is an integer called Button. The value of the argument indicates whether the left, right
or middle mouse button was clicked. The second argument is an integer called shift. The value of this argument
indicates whether the mouse clicked simultaneous with the Shift key, Ctrl key or Alt key. The third and fourth
arguments X and Y are the co-ordinates of the mouse location at the time mouse was clicked. As the Form is
executed automatically whenever the mouse button is clicked inside the Form’s area x, y Co-ordinates are
referenced to the Form.
Positioning a Control
Mouse Down is a commonly used event and it is combined with a Move method to move an
ImageControl to different location in a Form. The following application illustrates the movement of object
responding to events. It makes use of two OptionButton controls, two Image controls and a CommandButton.
The application is designed in such a way that when an OptionButton is selected, the corresponding image
control is placed anywhere in the Form whenever it is clicked.
Example
A new Standard Exe project is opened and the Form and the project files are saved as [Link] and
[Link]. The form is designed as per the properties given below:
Object Property Setting
From Caption Mouse Down Application
Name Form1
OptionButton Caption Credit card is selected
Name Optionl
Value True
OptionButton Caption Cash is selected
Name Option2
Example
A new Standard EXE project is opened and the Form and project files are saved as [Link] and [Link].
The Name and Caption properties of the Form are changed to frmDraw and LINE DRAWING APPLICATION.
The following code is entered in the general declarations of the frmDraw Form,
Option Explicit
The following code is entered in the Form_MouseDown( ) procedure.
Private Sub Form_MouseDown(Button As Integer, Shift As Integer,
X As Single, Y As Single)
[Link] = X
[Link] = Y
End Sub
The following code is entered in the Form_MouseMove( ) procedure.
Private Sub Form_MouseMove(Button As Integer, Shift As Integer,
X As Single, Y As Single)
If Button = 1 Then
This program uses two graphics related Visual Basic concepts: for the Line method and the currentX and
CurrentY properties. Line method is preferred for drawing a line in a Form. The following statement draws a
line from the co-ordinates x=2500, y=2000 to x=5000, y = 5500
Line(2500,2000)-(5000,5500)
The CurrentX and CurrentY properties are not visible in the Properties window of the Form because it
cannot be set at the design time. After using the Line method to draw a line in a Form, Visual Basic
automatically assigns the co-ordinates of the line's end point to the CurrentX and Current Y properties of the
Form on which the line was drawn.
Visual Basic does not generate a MouseMove event for every pixel the mouse moves over and a limited
number of mouse messages are generated per second by the operating environment. The following application
illustrates how often the Form_MouseMove( ) procedure is executed.
Example
A new Standard EXE project is opened and the Form and the Project files are saved as [Link]
and [Link].
Object Property Setting
From Caption Mouse Move Application
Name frmMouseMove
CommandButton Caption &Clear
Name cmdClear
Font System
The following code is entered in the general declaration of the Form.
Option Explicit
The following code is entered in the Form MouseMove event procedures
Private Sub Form_MouseMove()
circle(X, Y), 70
End Sub
The above simply draws small circles at the mouse’s current location using the Circle method. The parameters
x, y represent the centre of the circle and the second parameter represent the radius of the circle.
Private Sub cmdClear_Click()
[Link]
End Sub
The program is executed by pressing F5. When the mouse inside the Form, circles are drawn along the path of
the mouse movement as shown in below figure. When the clear button is clicked it clears off the circles from
the screen. The circles are widely spaced when the mouse is moved quickly and viva versa. Each small circle is
an indication that the MouseMove event occurred and Form_MouseMove( ) procedure was executed.
The MsgBox( ) function takes the same parameters as the MsgBox statement. The only difference between the
MsgBox statement and MsgBox( ) function is that the function returns a value. The returned value indicates the
button that was clicked in the dialog box.
This application is run by pressing F5. A form appears as shown in below figure. By clicking the Display item,
a dialog box with exclamation point icon and OK button appears. By clicking the Exit menu, a dialog box with
a message appears as shown in above figure. If Yes is clicked, the application terminates.
When date is typed in the TextBox, the procedure determines whether it is valid date or not. If variable I is
filled with characters such as ABC or 1234 the condition. Not IsDate() is satisfied and it displayed a message
box with the message “Invalid Date”.
If the value entered is valid one such as 12/04/18, the condition Not IsDate(1) is not satisfied and the
user is prompted with a message box indicating the day of that date as shown in the below figure:
• Two menu items are added to the Form1 of the [Link] project with the following characteristics. These
menu items are inserted above the Exit menu item.
Caption Name
…Get a Da&y mnuDay
- mnuSep3
The following code is entered in the mnuDay_Click( ) procedure of Form1
Private Sub mnuDay_Click()
[Link] 1
If [Link] = “ “ Then
MsgBox “Dialog Box is Cancelled”
Else
MsgBox “The Selected Day is: ” + [Link]
End If
End Sub
When the menu item Get a Day is clicked, it displays the [Link] as a custom dialog box and prompts the
user to select a day. It also displays the day which is selected by using the Tag property of the Form2 dialog
box. The code uses [Link] to store the name of the day which is selected.
The following code is entered in the Command2_Click() procedure of Form2 dialog box.
Private Sub Command2_Click()
[Link] = “ “
[Link]
End
End Sub
Whenever the Exit button is clicked, the Tag property of the Form2 dialog box is set to null and the Hide
method hides the Form. Setting [Link] to null indicates that the user has clicked the Exit menu.
• Components is selected from the Project menu which displays a Components box.
• After ensuring that Common Dialog 6.0 Control CheckBox has a check mark in it, the OK is clicked
Example
• A new Standard EXE is opened and the Form and the project are saved as [Link] and [Link].
• The application is designed and menu items are added to the to the From as per below Tables specifications
• The designed Form is represented in below Figure
Object Property Setting
From Caption The Common Dialog Program
Name Form1
CommonDialog Cancel Error True
Name CommonDialog1
Caption Name
&File mnuFile
…Color mnuColour
…Open mnuOpen
- mnuSep
...E&xit mnuExit
Before displaying the dialog box, the mnuColour_Click( ) procedure sets an errortrap. The purpose of an
errortrap is to detect an error during the display of the dialog box. We have set the CancelError Property of the
Dept. of Computer Science, HiSAC, Erode 47
Visual Basic – Unit II
CommonDialog1 control to true at design time. Therefore, if Cancel button is pressed when the dialog box is
displayed, the errortrap, which has been set displays the “Dialog Box is Cancelled” and dialog box disappears.
However, if specific colour is selected from the dialog box and OK button is clicked the Back Colour of the
Form is changed to that particular colour. The following code is entered in the mnuOpen_Click( ) procedure.
Private Sub mnuOpen_Click()
Dim filter As String
On Error GoTo errortrap
fi1ter = “all files(*.*) | *.*”
[Link] = fi1ter
[Link] = 1
MsgBox "Selected file is: “+[Link]
Exit Sub
errortrap:
MsgBox “Dialog box is cancelled”
Exit Sub
End Sub
The above procedure displays an Open dialog box. Before displaying the dialog box, the first statement of the
mnuOpen_Click() procedure sets an errortrap which detects an error during the display of the dialog box. If
the Cancel button is pressed when the dialog box is displayed, the errortrap, which has been set, displays the
message “Dialog Box is cancelled” and the dialog box disappears. However, If a specific file is selected from
the dialog box the name of the selected file is displayed as a message box. The filter property of the
CommonDialog1 is set to the value of the filter variable Action property to 1, displays the Open dialog box
Private Sub mnuExit_CliCK )
End
End Sub
The above procedure terminates the application. Like Colour and Open dialog boxes, the properties of the
Common Dialog Control may used to determine the user’s response to the dialog box. Action property 4
displays the Font dialog box and 5 displays the Print dialog box.
RichTextBox Control
The RichTextBox control allows the user to enter and edit text while also providing more advanced
formatting feature than the conventional 'I'extBox control. It almost works like an editor. The RichTextBox
control provides a number of properties we can use to format any portion of text within control. Using these
properties, we can make the text bold or italic, change it colour, and create superscripts and subscripts. We can
also a paragraph formatting by setting both left and right indents, as well as hanging indents.
******
Fundamentals of Graphics
Various controls and methods are used in Visual Basic to draw points, lines, boxes, circles and other
shapes and their location and appearance on a Form can be changed. There are some basic idea that is used for
creating graphics using twips, coordinate system and simple colour.
A twip is a unit that specific the dimensions and location of the object. The number of times a twip is
used by all Visual Basic movement. There are 1440 twips in one inch. These measurements designate the
object’s size then printed. The co-ordinate system is a two-dimensional grid that define location either on the
Form or any other container which or an any other container which is represented as (X, Y). A colour is
represented by a long integer and there are four ways of specifying it at run time; RGB function, using
QBColour function using one of the intrinsic constants in the Object Browser or by entering a colour value
directly.
The RGB( ) function enables the user to specify colours. The RGB( ) function has three arguments. The
value of the first argument represent amount of Red in the final colour the second argument represents Green
and the third represents Blue. The maximum value of each argument is 255 and minimum is 0. The following
statement uses the RGB function to give the colour red.
RGB (255, 0, 0)
The following statement returns yellow colour.
RGB (255, 255, 0)
QBColour function takes a single number that specifies a Quick Base colour number from 0 to 15 and returns a
long integer that can be used in the Visual Basic Colour property.
[Link] = QBColor (8)
This changes the background colour of the Form to grey.
Line Control
A Line control is a straight line segment that is drawn at design time. The position, length, color and
style of the Line control can be positioned to customize the look of the application.
Shape Control
A Shape control is a visual element that contains several predefined specified shape. In order to view a
specific shape, control is added to the Form by double clicking it. The default shape is rectangle. The Shape
property is selected from the Properties window, which drops a list of shapes, from which a user can select the
desired one.
The FillColor and FillStyle properties of the Shape control can be changed so that the desired color and
style can be obtained.
Image Control
An Image control is a rectangular portion into which picture files can be loaded. Picture files include
bitmap files, icon files and metafiles. A bitmap also called "paint type" graphics defines an image as a pattern of
dots. It has a filename with extension .bmp. An icon is a special kind of bitmap with extension .ico.
Adding Pictures
Line control and Shape control are used for drawing geometric shapes such as lines, circle, squares,
and so on. For drawing more complex figures user can use a picture file. A picture file can be loaded on a
Form, Image control or Picture control. A picture can be added using the following two ways at design time.
• In the Properties window of the Form, the Picture property is selected. Visual Basic displays a dialog box
from which a picture file can be selected. The selected picture is displayed in the Form as its background.
Similarly a picture can be loaded in PictureBox and Image control.
• A picture can be copied from another application such as Paintbrush to the Clipboard and by selecting Paste
command from the Edit menu, the picture can be pasted onto a Form, Picture Box or Image Control.
Removing Pictures
A picture can be removed at run time using the LoadPicture function without arguments. The following
statement removes a picture from an image control at run time.
Set [Link] = LoadPicture(““)
Stretch Property of an Image control is used to automatically resize a picture and place it inside the
control. When this property is set to True, the image control resizes the picture the desired size to fit into the
control. When this property is set to False, the control automatically adjusts its size to the size of the picture
loaded on to it.
A circle method is used to draw a variety of circular and elliptical shapes. To draw a circle, Visual Basic
requires the location of the circle's centre and the length of its radius. The following statement draws a circle
with a center(1400, 1200) and radius 650.
Circle(l400,1200), 650
The first statement in the above procedure declares a variable called NewForm as a copy of the Child Form
Form1. This implies that, for all purposes, the NewForm can be referred to as an instance of the Form1 with the
same properties that Form1 had at the time of design. The second statement in the procedure causes the newly
created Form to pop up. Every time when the menu item New is clicked in the MDI form, a new Form pops up.
The following code is entered in the mnuTile_Click( ) procedure of the MDI form.
Private Sub mnuTile_Click()
[Link] vbTi1eHorizonta1
End Sub
The code in the mnuTile_Click() procedure uses the Arrange method with vbTileHorizontal as the argument
to Tile the Child Forms. Below Figure represents the Forms in Tile arrangement. This procedure is executed
when the menu item Tile is clicked. The following code is entered in the mnuCascade_Click( ) procedure of the
MDI form.
The code in the mnuCascade_Click( ) procedure uses the Arrange method with vbCascade as the argument to
cascade the Child Forms. Below Figure represents the cascaded forms. The following code is entered in the
mnuExit_Click( ) procedure.
Private Sub mnuTile_Click()
End
End Sub
When the menu Exit is clicked, the application terminates.
The Me reserved word used in the Form_Rcsizc( ) procedure is a variable containing the name of the
Form where the code is currently executed. The Me keyword in Visual Basic behaves like an implicitly declared
variable. For example, in the above program, there may be several instance of the child form in the parent form.
When the size of one of these forms is changed, the Form_Resize( ) procedure is executed and automatically
updates the Me variable with the instance that was resized.
Creating a Toolbar
Most of the Windows programs include a Toolbar, which is an area containing control to provide quick
access to the most commonly used operations. Toolbar is also called a ribbon bar or control bar. In order to add
a Toolbar item, the MDI form is selected and the Picture control in the Toolbox is double clicked. Visual Basic
responds by displaying a PictureBox control in the Form as shown in below Figure.
User can place text, or a picture, or both in any cell of an MSFlexGrid. The Row and Col properties
specify the current cell in an MSFlexGrid. We can specify the current cell in code, or the user can change it at
run time using the mouse or the arrow keys. The Text property references the contents of the current cell. If a
cell's text is too long to be displayed in the cell, and the WordWrap property is set to True, the text wraps to the
next line within the same cell. To display the wrapped text, we need to increase the cell's column width
(ColWidth property) or row height (RowHeight property). The Cols and Rows properties are used to determine
the number of columns and row in an MSFlexGrid control.
Two kinds of rows or columns are created in the MSFlexGrid control. They are fixed and non-fixed. A
non-fixed row or column scrolls when the scroll bars are active in the MSFlexGrid control. A fixed row or
column does not scroll at any time. FixedRows or FixedCols is generally used for displaying headings. Rows
and columns are created by setting the four properties of the MSFlexGrid control such as Rows, Cols,
FixedRows and FixedCols. Since the MSFlexGrid control is an OCX control, user must make sure whether the
control is included in the project. If the control does not appear in the ToolBox, it is added by selecting
Components from Project menu and placing a check mark in the Microsoft MSFlcxGrid Control. This places
the control in the ToolBox.
Example
This example uses a MSFlexGrid to view the sales of a particular item in a particular month.
• Start a new Standard Exe project from the New project dialog box.
• The Form is designed as shown below.
• To add the FlexGrid, choose Components from the Project menu and check on the Microsoft Flexgrid
Control 6.0.
• The two combo boxes are named itemname and mnthname respectively.
• The MSFlexgrid is named as itmdet.
• The command button with caption Add shown in the above Figure is named as Add.
Dept. of Computer Science, HiSAC, Erode 55
Visual Basic – Unit II
• In the general declarations section of the Form, the following code is entered to initialize two arrays.
Dim arrl(12) As String
Dim itm(6) As String
Dim i As Integer
• The following code is entered in the Form Load event:
itm(0) = “Stationeries”
itm(1) = “Groceries”
itm(2) = “Milk Products”
itm(3) = “Confectionaries”
itm(4) = “House hold item”
itm(5) = “Toys”
arrl (0) = "Jan"
arrl (1) = "Feb"
arrl (2) = "Mar"
arrl (3) = "Apr"
arrl (4) = "May"
arrl (5) = "Jun"
arrl (6) = "Jul"
arrl (7) = "Aug"
arrl (8) = "Sep"
arrl(9) = "Oct"
arrl(10) = "Nov"
arrl(l1) = "Dec"
[Link] = 0
For i = 0 To 11
[Link] = i + 1
[Link] = arrl(i)
[Link] arrl(i)
Next
itmdet.Co1 = 0
For i = 0 To 5
[Link] = i + 1
[Link] = itm(i)
[Link] itm(i)
Next
The two arrays are initialized itm, arrl are initialized in the Form Load. The first "For loop" shown above adds
the names of the month in the 0th row. The second "For loop" adds the names of the items in the 0th column.
• The following code is entered in the Add Button’s click event:
[Link] = [Link] + 1
[Link] = [Link] + 1
[Link] = Str(Val([Link]) + Val([Link]))
This event procedure stores the value of the sale of the item for the month specified.
Example
• A new Standard EXE project is opened and the Form of the project is saved as [Link]
and the project file is saved as [Link].
• MSFlexGrid control is placed in the Form by double clicking it. After placing it, the Rows property of the
MSFlexGrid is set to 7 and Cols property to 4.16.
• The Caption property of the Form is changed to MSFLEXGRIDAPPLICATION.
• After setting the properties, the MSFlexGrid control is enlarged vertically and horizontally by dragging its
handles.
• Now, the Form is designed as per the specification given above looks like the one shown in below Figure. A
menu title File is placed with a menu item Clear in the Form.
The following code is entered in the general declarations section of the Form.
Option Explicit
The following code is entered in the Form_Load( ) procedure of the Form1
Private Sub Form_Load()
[Link] = 0
[Link] = 1
[Link] = "OF"
[Link] = 2
[Link] = "IMPACT"
[Link] = 3
[Link] = "IMP_NET"
[Link] = 0
[Link] = 1
[Link] = "Jan-Feb"
[Link] = 2
[Link] = "Mar-Apr"
[Link] = 3
[Link] = "May-Jun"
[Link] = 4
[Link] = "Jul-Aug"
[Link] = 5
[Link] = "Sep-Oct"
[Link] = 6
[Link] = "Nov-Dec"
End Sub
The application is run by pressing F5. The program displays a FlexGrid control with seven rows and four
columns displaying the text in the top heading row and the left heading column. The FlexGrid control displays
information in a tabular format. Each cell can be viewed by using the arrow keys but values cannot be entered
directly into cells. The FlexGrid control has both the properties Row and Rows. Similarly it has properties Col
and Cols. Rows and Col properties can be set both during the design time and run tune whereas, the Row and
Col properties are set into action only during run time.
Another procedure called SetRowHeight( ) is added by selecting from the Project menu and it is added
to the code. The following code is entered in the SetRowHeight( ) procedure.
Public Sub SetRowHeight()
Dim counter
For counter = 0 To 6 Step 1
[Link](counter) = 350
Next
End Sub
The code in this procedure uses a "For loop" to change the height of each of the rows to 350 twips. The
RowHeight property determines the height of the cell. The SetRowHeight statement is added to the end of the
Form_Load( ) procedure as shown below.
Private Sub Form_Load()
..................................
.....Same Code written as before.....
SetRowHeight
SetColWidth
End Sub
[Link] = "120"
[Link] = 2
[Link] = 1
FlexGrid1. Text = "150"
[Link] = 3
[Link] = 2
[Link] = “180"
[Link] = 4
FlexGrid1.Co1 = 2
[Link] = "210"
[Link] = 5
FlexGrid1.Co1 = 3
[Link] = "240"
[Link] = 6
[Link] = 3
[Link] = "270"
End Sub
The code which is added in the FillValues( ) procedure fills six cells in the FlexGrid by selecting the
Row and Col properties with the required row number and column number, and then sets the Text property of
the cell with the desired text. Below Figure represent a FlexGrid control with values filled in the specified cells.
A FlexGrid control includes a property called FlexGridLines, which can be set to either True or False. The
default setting is True, which causes the control to appear with visible grid lines. If this property is set to False,
the control is shown without grid lines.
*******
The DBEngine is the top-level database object and corresponds to the Jet database engine. This object is
used to set database engine system parameters and default workspace. The Workspace object is used to support
simultaneous transaction and it acts and it acts as a container for open databases. A default Workspace objects
Workspace (0) is created when the Data Access Objects are referenced in the language at run time. The default
workspace is always available and can never or removed from the collection.
• The Database object corresponds to a Jet native or external database or a direct ODBC connection. This us
used to define the database’s table, relations and stored queries and to open Recordset objects.
• The TableDef object corresponds to a stored table definition. Each TableDef in a collection represents the
definition of a table in the current database or an attached table in the external database.
• The QueryDef object is a stored query definition, which is precompiled SQL statement.
• The Recordset object corresponds to a cursored view into a database table or the results of a query. A
cursored view is one that stores rows of data in buffer and points to one row of data at a time called
current record. The cursor may be positioned to any row of data using Move, Seek or Find methods.
• The Field object corresponds to a column of data type and set of properties. TableDef, QueryDef and
Recordset objects have a collection of Field objects. The collection of Field objects associated with a
Recordset cursor describes a single row of data.
• The Index object is a stored index associated with TableDef objects or table type Recordset object. Setting
the index allows the user to quickly re-order the record in a table.
• The Parameter object represents a parameter associated with a QueryDef object created from a parameter
query. A Parameter's collection contains all the Parameter object of a QueryDef object.
• The User object used to define and enforce database security. The DBEngineobject supports a set of user’s
collection. The Users collection contains all stored User object of a Workspace or group account.
• A Group is a collection of users with similar access rights. The DBEngine Object supports a collection of
system groups. Each user in the group inherits the permission to access the objects that the group can
access.
• A Relation object represents a relationship between field in a table or queries. A Relation collection contains
stored Relation objects of a database object. The DBEngine enforces certain update and delete conditions on
the data associated with the fields of the Relation object, to maintain referential integrity.
• A Property object represents a built-in characteristics or used defined characteristics of a data access object.
Properties collection contains all the Property objects for a specific instance of an object.
• A Document object includes information about one instance of a type of object. The object can be a
database, saved table, query or relationship. A Documents collection contains all of the Document objects
for a specific type of object.
• A Container objects holds information describing the objects that are grouped container. A containers
collection contains all Container objects that are defined in a database.
Opening a Database
To open an existing database, the OpenDatabase method of the Workspace object is used.
Syntax
OpenDatabase(dbname,[options],[readonly],[connect])
To open the employee_details database in the read only mode, the following statement is used.
Set db = OpenDatabase("emp1oyee_detail",Fa1se,True)
In the above statement, the True value specified as the third argument will provide only read access on the
database.
Recordset
A Reeordset is an object that contains a set of records from the database. There are five major types of
Recordset objects.
Dynaset-Type Recordset
The dynaset type Recordset object is a set of records that represents a table, or attached tables, or the
results of queries containing fields from one or more tables. A dynaset enables us to update data from more than
one table.
Creating a Recordset
The OpenRecordset method is used to open a Recordset and create a Recordset variable.
Example
To create a read only Recordset for the table employee, the following code is used.
Dim rs as Recordset
Set rs = [Link]("employee",dbOpentable, dbReadOnly)
In the above statement, db is the variable that represents the Database object. Here db Open Table specifies the
type of Recordset to be created.
Navigating a Recordset
After creating a Recordset object, various Move methods can be used to navigate through the records in a
Recordset.
• The MoveFirst method moves to the first row in the Recordset
• The MoveNext method moves to the next row in the Recordset.
• The MovePrevious method moves to the previous row in the Recordset.
• The MoveLast method moves to the last row in the Recordset.
Finding RecordSet
The Find methods can be used to locate a record in a dynaset or snapshot type Recordset. Visual Basic
supports four Find methods.
• FindFirst method finds the first record satisfying the specified criteria.
• FindLast method finds the last record satisfying the specified criteria.
• FindNext method finds the next record satisfying the specified criteria, searching forward from the current
record.
• FindPrevious method finds the previous record satisfying the specified criteria, searching backward from
the current record.
When the database engine finds a match for the criteria that is specified, it moves to that record. If no match is
found, the current record is unchanged and the Recordset object's No Match property is set to true.
********
2. Enter the Data Source Name as XYZ Company in the Data Source Name box. Enter the description as XYZ
company database in the Description box. Provide the user name as user1 and the server name as server1.
3. Click the Next button to continue and display the screen that allows us to choose more options.
4. Click the select button that allows us to choose appropriate translators.
5. To see the list of ODBC drivers installed in the system, the drivers tab must be clicked. This is illustrated in
the below figure
Example The senior manager of an XYZ company wants to view the details of all the employees in the
company. In order to Navigate through a Recordset the following steps have to be used.
• Add a new Form to the project and set its caption as Emp Details.
• Add controls - six label controls, six textboxes and nine command buttons to the Form as shown below.
In the General declaration section of the form, a Database object db and RecordSet object rs are declared.
Dim db As Database
Dim rs As Recordset
The emp_details database in Oracle using the data source name XYZ Company can be accessed using the
OpenDatabase method on loading the form. The code for this is included in the Form_Load event. Further, in
order to retrieve the data from table emp, the OpenRecordset method in association with the database object db
is called and the resulting data is set into the Recordset rs. The textboxes are then assigned with the field values
of a particular record using the Recordset variable. The txt_empno.text = [Link] ("Emp_no") assigns the value
of the Emp_no in the bracket to the text property of a textbox txt_empno. The other field values are assigned in
a similar way. The following code has to be attached in the Form_Load event procedure.
Private Sub Form_Load()
Set db = OpenDatabase("XYZCompany",Fa1se,Fa1se,_
"ODBC;UID=USERl;PWD=SSI;DSN:"XYZCompany)
Set rs = [Link]("select * from emp")
Txt_empno.Text= [Link](“Emp_no")
Txt_name.Text= [Link]("Emp_name")
Txt_sal.Text= [Link](“Sal")
Txt_date.Text= [Link]("Joindate")
Txt_dept.Text= rs.Fie1ds("Dept_no")
Txt_desig.Text= [Link]("Desig")
End Sub
To move to the First, Last, Previous and Next records, the following code has to be attached to the Click event of
the Command buttons cmdFirst, cmdLast, cmdPrev and cmdNext. The MoveFirst method is used to point a recordset to
the first record of the recordset. Similarly MoveLast points in the last record of the recordset. MoveNext method is used
in the recordset to the next record from the currently accessing one and MovePrevious in point to the previous record
from the current one. The MoveFirst, MoveNext, MovePrevious and MoveLast methods are activated in the click events
of the respective command buttons cmdFirst, cmdNext, cmdPrevious and cmdLast.
Private Sub cmdFirst_Click()
[Link]
MoveFields
End sub
When a new employee is appointed in the company, his details have to be added to the database table.
The AddNew method of the Recordset object is applied to add a new record. The coding to add a new record is
added in the click event of the cmdAdd command button.
Private Sub cmdAdd_Click()
Txt_empno.Text = ""
Txt_name.Text = ""
Txt_sal.Text = ""
Txt_date.Text = ""
Txt_dept.Text = ""
Txt_desig.Text = ""
[Link]
End Sub
The AddNew method of the Recordset object is used to add a new row (an empty record) to the
recordset. Once the AddNew method is applied to the recordset, the edit buffer is created with the empty record
in it. The user is then entitled to enter the required data into the field objects associated with that Recordset.
Finally calling the Update method saves the changes. The user has to save the changes after entering the details.
When the user clicks the command button cmdSave, all the changes that are made to the database are saved.
Private Sub cmdSave_Click()
If [Link] = dbEditAdd then
rs("Emp_no") = Txt_empno.Text
rs("Emp name") = Txt [Link]
rs("sal") = Txt_sal.Text
rs("Joinmdate") = Txt [Link]
rs("Dept_no") = Txt_dept.Text
rs(“Desig") = Txt_desig.Text
End If
[Link]
End Sub
The Update method of the Recordset object saves the contents of the edit buffer to the Recordset object.
Whenever an employee is promoted, or any changes have to be made to his salary field or designation field, his
relevant record has to be modified accordingly. In order to implement this, the record must be in the Edit mode.
On clicking the modify button, [Link] method sets the record to the edit mode and the changes are made. The
changes are assigned to respective fields and are saved by clicking the Save button. The [Link] method saves
the changes made to the record.
Private Sub cmdModify_Click()
If [Link] = dbEditNone Then
[Link]
End If
End Sub
When a particular employee retires from the company, his relevant record has to be deleted from the database.
The Delete method of the Recordset object is used to implement this and the Recordset pointer is moved to the
next record. If the record to be deleted is the last record, then the Recordset is set to the last record using the
statement [Link].
Private Sub cmdDelete_Click()
[Link]
[Link]
If [Link] Then
[Link]
End If
MoveFields
End Sub
Create a Sub procedure called Movefields and attach the following code. In this procedure, the values of the
fields of the Recordset are assigned to the text property of the textboxes.
Public Sub MoveFields()
Txt_empno=rs("Emp_no")
Txt_name=rs(" Emp_name")
Txt_sal=rs("sal")
Txt_date=rs("Hiredate")
Txt_dept=rs("Dept_no")
Txt_Desig = rs("Des;g")
End Sub
Example The following example fetches a record from the Employee table, using the Find method, where
empname = "Allen".
The manager finds that in many cases it will be much more efficient to search for a particular record
by specifying a criterion instead of scrolling through the records. In order to implement this, the Find
methods of the Recordset object are used.
Steps
Place a command button namely cmdFindFirst to activate the Find method and to detect the first record
to match the given criteria. The following code is used to declare a database object mydb, a Recordset
object MySet and a Workspace object namely MyWs and a variable Total of long datatype in the General
declaration section of the form.
Dim mydb As Database, MySet As Recordset, MyWs As Workspace
Dim Total As Long
The following code in the Form load event procedure is included to open the emp_details database and the
emp table in it and assigning the records of empl table to the Recordset variable MySet.
Private Sub Form_Load)
Set mydb = OpenDatabase("XYZCompany”,False,False, _
"ODBC;UID=USERl;PWD=SSI”;DSN=XYZCompany)
Set MySet = [Link](“Emp",dbOpenDynaset)
End Sub
In the click event of the cmdFindFirst command button the emp_no entered in the text1 textbox is searched
using the MySet recordset using the FindFirst function and if no match is found, then a message is displayed
saying "record not found". If a match is found, then other details of that employee identified by the particular
emp_no like emp_name, salary, designation and other related details are assigned and displayed in the
textboxes.
Private Sub CmdFindFirst_Click()
Dim a As String
a = [Link]
[Link] “[emp_no]=" & CInt([Link])
If [Link] Then
MsgBox "The Given Record is not found"
Else
[Link]
[Link] = MySet(0)
[Link] = MySet(1)
[Link] = MySet(2)
[Link] = MySet(3)
[Link] = MySet(4)
End If
End Sub
The following example changes the deptno field of the Emp table in the emp_details database from 9 to 10.
After the BeginTrans method starts a transaction that isolates all changes made to the Emp table, the
CommitTrans method, saves the changes. The Rollback method is used to undo the changes that are saved using
the Update method.
Example
A new Standard EXE project is opened and saved. A function called changeDeptno is entered and is called in
the Form_Load( ) procedure.
Function changeDeptno ()
Dim db As Database, myWs As Workspace, rs As Recordset
Set myWs = [Link](O)
Set db = [Link](“XYZCompany", False, False, _
"ODBC;UID=USERl;PWD=SSI”;DSN=XYZCompany)
Set rs = [Link](“Emp",dbOpenDynaset)
[Link]
Do Unti1 [Link]
If rs("dept_no")=9 Then
[Link]
rs("dept_no") = 10
[Link]
End If
[Link]
Loop
If MsgBox("Save all chances?",vbQuestion+vbYesNo,"Save changes")=vbYes Then
[Link] Else [Link]
End If
[Link]
End Function
When the function changeDeptno is called at run time, it display a message box. By choosing Yes,
changes are made in the database and the transaction is committed, Otherwise, changes made to the database
table before the Commit'I'rans method are not saved.
a Data control so that the control is automatically filled and its column headers are set automatically from a
Data control's Recordset object.
Each cell of a DBGrid control can hold either text or picture values, but is not linked or embedded
objects. The user can specify the current cell in the code, or change it at run time using the mouse or the arrow
keys. Cells can be edited interactively, either by typing into the cell, by programming. If a cell's text is too long
to be displayed, the text wraps to the next line within the same cell. To display the wrapped text, the DBGrid
control's RowHelght property has to be increased.
A DBGrid control can have as many rows as the system resources can support and 1700 columns. When
a cell is selected, the ColIndex property is set, thus selecting one of the Column objects in the DBGrid object's
Columns collection. The Text and Value properties the Column object reference the contents of the current
cell. The data in the current row can be accessed using the Bookmark property, which provides access to the
underlying Recordset object's record. Each column of the DBGrid control has its own font border, word wrap,
colour and other attributes that can be set without regard to other columns.
The AddNew method clears the bound control and sets the EditMode property of the data control to
dbEditAdd. The record is only added when an UpdateRecord is executed. In order to delete the records of these
employees who are no longer employed with the company, the following coding has to be included
Private Sub Delete_Click()
[Link]
[Link]
If [Link] Then
[Link]
End If
End Sub
The Delete method deletes the current record from the database. The EOF property becomes True if the current
record position is after the last record. In order to save the new record added and the changes made to a record,
the Update method is used.
Private Sub Update_Click()
[Link]
End Sub
The manager while inserting a new record, finds that he had entered the department number as 3 instead of 1.
Hence he decides not to add the record into the table by cancelling the insertion To accomplish this, the
following code is added in the click event of the Cancel command.
Private Sub Cancel_Click()
[Link]
End Sub
The UpdateControls method cancels any changes made to the data and retains the original values. If the
user selects the Add button and then decides not to add the record, then the Updatecontrols method cancels
the Add.
The top level object is the rdoEngine object, which is used to access all remote data. All requests using RDO
objects are handled by the rdoEngine.
The rdoEngine creates one or more rdoEnvironment objects. This object contains information about
current environment for data connections. All rdoEnvironment objects are contained in the rdoEnvironments
collection object.
The rdoEnvironment objects can create rdoConnection objects. This object contains the details needed to
establish a connection between an application and the remote data source. All rdoConnection objects are
stored in the rdoConnections collection.
Each rdoConnection can create one or more rdoResultset objects. This object contains a direct reference to
all the rows and columns in the dataset. It can be used to create a collection of records after a connection is
made to the remote data source. All rdoResultset objects are stored in the Resultsets collection of the
rdoConnection object.
The rdoTable object contains information about each column in the base table that exists on the remote
data source. The rdoTable object can be opened from the rdoConnection object.
The rdo Column object contains detailed information about the contents and properties of each data column in
the rdoTable or rdoResultset object. All rdoColumn objects are stored in the rdoColumns collection.
The rdoQuery object provides a method for creating and executing defined queries or views on the remote
data source. rdoQuery objects are accessed through the rdoQueries collection object.
The rdoParameter object manages the parameters that are passed during the processing of queries. More than
one rdoParameter object can be defined for each rdoQuery object. All the parameter objects are accessed via the
rdoParameter collection.
The following steps have to be followed for accessing a database through RDO
• First, the user must create an rdoConnection object to the database.
• After the connection is established and the database is opened, the user can execute SQL statements and
store procedures against the database.
• The results are returned in a rdoResultset object. With the rdoResultset object's methods and properties, the
user can access the records, edit them and save them.
Establishing a Connection
To establish a connection to a database in Oracle, the following syntax is used
Syntax
Set connection = [Link](dsName[,prompt[,readonly[,connect[,
options]]]])
In the above syntax, OpenConnection method opens a connection to an ODBC data source and returns a
reference to the rdoConnection object that represents a specific database. Only the first argument is mandatory.
The syntax in the Open Connection method has the following parts.
connection An object expression that evaluates to a rdoConnection object that the user is opening.
environment This is an object expression that evaluates to an existing rdoEnvironment object. The user provide
an rdoEnvironment object.
dsName This is string expression, which is the name of a registered ODBC data source or name.
prompt This is variant that determine the way in which the operation in carried out, as specified in the settings.
readonly This is a Boolean value. It is True if the connection is to be opened for read only access, and False if
the connection is to be opened for read/write access. If the user omits this argument, the connection is opened
for read/write access.
connect This is a string expression used to pass arguments to the ODBC driver manager for opening the
database.
Options This is a variant or constant that determines how the operation is carried out, as specified in Settings.
The connect arguments constitutes the ODBC connect arguments, and is dependent on the ODBC driver.
If the connect argument is an empty string(“”), the user name and password are procured from the
rdoEnvironment object’s UserName and Password properties and a dsName argument must be provided. If the
Data Source Name (DSN) parameter does not appear in the connect argument, the user has to select from a list
of registered data source names.
The name argument is a string, which specifies the source for the new rdoResultSet [Link] argument
can specify the name of a rdoTable object the name of a rdoquery object, or an SQL statement that will
be executed on the server.
The Type argument is a constant that specifies the type of cursor that will be created by the data source to
manage the qualified records. This argument can have one of the following values.
rdOpenForwardOnly (default) opens a forward-only type resultset. Only the MoveNext method can be used to
scan the resultset forwaed but it cannot be updated.
rdoopenKeyset opens a static type resultset. It can be scanned forward and backward with the Move methods
and can be updated. But it does not reflect any changes made to the rcords by the other users.
rdoOpenStatic opens a static type resultset. It can be scanned forward and backward but cannot be updated and
does not reflect any changes made by other users.
The locktype argument determines the way in which other users can access the data in the resultset. It can take
the following values.
• rdConncurReadOnly This is used when the user is opening the resultsets that will not be updated.
• rdConcurLock This locks the page that contains the current record and frees it only after the application
moves to a record in another page.
• rdConcurRowVer This locks the entire page containing the record being edited, but only while the record
is being updated.
• rdConcurValues Optimistic concurrency based on row values.
• rdConcurBatch Optimistic concurrency using batch mode updates.
[Link]
Else
Call Displayrecord
End If
End If
End Sub
When the user clicks the Add command button, it clears the Form and allows the entry of new information by
the user. Then on clicking the Save command button the new information is stored in the database.
Private Sub Add_Click()
Ca11 ClearRecord
[Link]
End Sub
The Update routine is used to save the changes that are made to the current record.
Private Sub Update_Click()
[Link]
rs("emp_no") = [Link]
rs(“emp_name") = [Link]
rs(“sal") = [Link]
rs("Joindate") = [Link]
rs(“dept_no") = [Link]
[Link]
End Sub
When the user clicks the Delete command button, the current record must be deleted from the table. Add the
following code in the click event of the Delete command button.
Private Sub Del_Click()
[Link]
Ca11 Disp1ayrecord
End Sub
Add the following routines to the form. These routines methods for displaying and retrieving from the
textboxes on the form.
Private Sub Displayrecord()
[Link] = rs("emp_no")
[Link] = rs(“emp_name")
[Link] = rs(“sal")
[Link] = rs("Joindate")
[Link] = rs(“dept_no")
End Sub
The above routine will display the current view row of the resultset on the form
Private Sub Clearrecord()
[Link] = “”
[Link] = “”
[Link] = “”
[Link] = “”
[Link] = “”
End Sub
The Clearrecord() clears the form and allows the user to enter the new values.
******
A class module, which we have already studied, is a server that is an application that provides its
services to the client application. When an object variable is created to access the properties and methods of a
class, we are actually invoking an executable file (DLL or EXE) that runs in the background and waits to be
contacted. This is activated every time a property value is set or read or a method is called.
An ActiveX EXE otherwise called as an out-of-process server, as the name indicates runs as a separate
process. When a client application creates an object provided by an EXE server for the first time, the server
starts running as a separate process. If another client application creates the same object, the running EXE
server provides this object. In other words, a single EXE server can service multiple clients. Out-of-process
servers seem to be more efficient to terms of resource allocation, but exchanging information between servers is
a slow process.
We will be working with a client server model. Here the application is the client, which sends request
and the ActiveX Component is the server, which services the request. Though ActiveX DLLs run within the
same application as the client, they are considered as to be servers.
An ActiveX project is compiled in the same way as a Standard EXE project. But ActiveX EXEs and
DLLs are used differently. Thus ActiveX components are Object Servers that can be used with other
applications.
While both ActiveX DLLs and EXEs can provide objects to other applications, ActiveX EXEs have the
capability to execute independently, which is not so in ActiveX DLLs. Compilation of an ActiveX component
can be done by selecting the File → Make menu command as with a Standard EXE project. The project is then
compiled into an ActiveX DLL or an ActiveX EXE, as appropriate. After it is compiled, the component is
registered on the computer, so that the user has the ability to use objects created from its classes in other
applications.
Example Let us develop a Calculator to perform the simple arithmetic calculations such as to be used in any
suitable client applications where required. This component developed can be used in dealing with simple day
to day operations of the DBF Ltd Bank, which forms our client here.
• Addition
• Subtraction
• Multiplication
• Division
• Modulus
The following three steps are involved
• To create the Calculator which is the ActiveX EXE component
• To compile this component and register.
• To test the component with our client test application.
Step1
To Create the Calculator (ActiveX EXE Component)
• To start with, go to Program→Visual Basic 6.0 → and the New Project dialog box opens. Select ActiveX
EXE.
• This opens into a class module namely Class1 by default similar to a Form in a Standard EXE project.
• Press F4 to edit the properties and set the properties of the class module as given below.
Properties Settings
Name Calculator
Instancing 5-MultiUse
• The following set of coding is included in the general declaration section of the class module Calculator to
perform addition between any two digits of data type-Single. The function is named as Addn and two
parameters A and B are of data type Single to represent that operation is performed on only two input
variables and the return datatype is declared as double here. The resulting addition is stored in Addn
variable.
Public Function Addn(A As Single, B As Single) As Double
Addn = A + B
End sub
• Similar to the addition operation, the difference between any two numbers is determined using the Diff
function defined below in the general declaration section. The resultant of the operation is obtained in the
Diff variable.
Public Function Diff (A As Single, B As Single) As Double
Diff = A - B
End Function
• The same logic holds good for the code given below to perform the multiplication process for any two
numbers passed as input. The product of two numbers A and B can be retrieved from the Prod variable of
the Prod function that is defined as follows. This coding sequence is also included in the general declaration
section of the class module Calculator.
Public Function Prod (A As Single, B As Single) As Double
Prod = A * B
End Function
• The division between two numbers is performed using the function Div as defined in the following code,
included in the general declaration section of the class module. The quotient obtained after performing the
division is retrieved in the Div variable.
Public Function Div (A As Single, B As Single) As Double
Div = A / B
End Function
• The modulus obtained by performing division on one number by the other can be determined using the Mod
operator in VB. When this basic knowledge, a function called modulus has been included in the general
declaration section to determine the modulus of a division operation.
Public Function Modulus (A As Single, B As Single) As Double
Modulus = A Mod B
End Function
• This completes the development of the ActiveX EXE component Calculator. This has to be run and
compiled.
• Before running select File→Save Project As and save it as [Link] and class module as
[Link].
Step 2
Compilation and Registering the Calculator Component
• The Calculator control can be run by pressing F5.
• Then select File→ Make EXE to make component an executable.
• The Make Project dialog appears as shown below. Choose a folder to save the EXE and click OK.
• The ActiveX EXE control namely ActiveX Calculator is now compiled and registered on our computer.
This server can be used from any of our projects.
Step 3
Testing the Calculator Project with a Standard EXE Application
• Goto VB and start another instance of Visual Basic and open a New standard EXE project and save it as
[Link].
• Place the following controls on the Calculator Form as given below
Object Properties Settings
Form Name CalculatorForm
Caption ActiveXCalculator
Components provide reusable code in the form of objects. An application that uses a component's code, by
creating objects and calling their properties and methods, is referred to as a client. Components can run either
in-process or out-of-process with respect to the clients who use their object. An in-process component, or
ActiveX DLL, runs in another application’s process. The client may be the application itself, or another in-
process component that the application is using.
The series of step by step procedures in this chapter build an in-process component called Interest
Calculator with class modules that demonstrate object lifetime. We will also see how to debug an ActiveX
DLL in process, by running the DLL and a test project together in the Visual Basic development environment.
Example DBF Limited finance company is in need of finding out the interest of the depositors for the time
period of investment and the type of deposit scheme chosen. This is generally done by writing a simple function
in the client's program. But the rate of interest offered may change from time to time during which time the
changes reflecting this can be done in the server program alone thereby making the work simpler and easier.
Keeping this in mind, let us more on to developing an ActiveX DLL component namely Interest Calculator as
elucidated below.
• Start an instance of Visual Basic and select an ActiveX DLL project and it opens into a class module by
default as in an ActiveX EXE.
• The properties of the class module can be set as given in below
Properties Setting
Name Interest Calculator
Instancing 5-MultiUse
• In the project menu, click Add Module and double click the module icon and name it as [Link].
• The following code is to be executed when the component starts, in response to the first object request.
Option Explicit
Public gdatServerStarted As Date
Sub Main()
gdatServerStarted = Now
[Link] “Executing Sub Main”
End sub
• Properties for a class can be created by adding public variables and property procedures to the class module.
We can also create methods for a class by adding Public Sub and Public Function procedures to the class
module. The following step by step procedure creates two properties and one method for the Interest class.
• The Name property is a string that can be retrieved and set by client applications. The methods included are
RecInterest, CumInterest and FixInterest to evaluate the interests based on the type of recurring,
cumulative and fixed deposit scheme chosen.
• Add the following code the declaration section of the Interest class module.
Option Explicit
Public Name As String
• The variable name becomes a property of the Interest class between it is declared Public.
• In the general declaration section of the class module, the function FixInterest is declared and defined which
will evaluate the interest for a fixed deposit scheme, with the rate of interest predefined to be 10 per cent
and time and principal amount as the two input parameters.
Option Explicit
Public Function FixInterest(P As Single, T As Single) As Single
Dim R As Integer
R = 10
FixInterest = (P * R * T) / 100
End Function
• If the type of deposit scheme is Recurring Deposit Scheme, then the function RecInterest is declared as
given in the following code in the general declaration section. The rate of interest is defined to be 8 percent.
Public Function RecInterest(P As Single, T As Single) As Single
Dim R As Single
R = 8.0
RecInterest = (P * R * T) / 100
End Function
• If the type of deposit scheme is Cumulative Deposit Scheme, then the function CumInterest is declared as
given in the following code in the general declaration section. The rate of interest is defined to be 7.5
percent.
Public Function CumInterest(P As Single, T As Single) As Single
Dim R As Single
R = 7.5
CumInterest = (P * R * T) / 100
End Function
• Select File→Save As and save the files.
• In order to test InterestCalculator component, a test project is required. The test project creates instances of
the classes a component provides, and exercises their properties, methods, and events. To enable debugging
of in-process components, Visual Basic allows us to load two or more projects into a project group. In
addition to enabling in-process debugging, the project group makes it easier to load our component project
and test project.
• In order to test the ActiveX DLL project, select Add Project from File menu and select a Standard EXE
project, which by default opens into a Form. The controls are placed on the form with properties set as given
below
Object Properties Settings
Label1 Caption Principal Amount
Label2 Caption Time Period
Label3 Caption Choice of Deposit
Label4 Caption Interest Amount
Label5 Caption Total Amount
TextBox1 Name txtPamt
TextBox2 Name txttime
TextBox3 Name txtIamt
TextBox4 Name txtTamt
ComboBox1 Name Combochoice
CommandButton1 Name cmdResult
Caption Caption
• Goto References from the project menu and then select the InterestCalculator component and click OK.
• Next we have to declare instances of the class Interest Calculator that is to be accessed. In the general
declaration section, the following code is included thereby declaring Intobject as object of class Interest.
Dim Intobject As New Interest
• The tab properties are to be set in the desired level in the design mode itself. On running the Form, the tab
control should be positioned first to the txtPamt field to get the principal amount. Then the time period is
given as the input, the user then makes a choice of deposit scheme from the combo box and the result
command button is clicked.
• The Click event of the cmdResult button is handled as given by the code below. On clicking the result
button, it accepts the principal amount and time period and checks for the deposit scheme that is selected.
Private Sub emdResult_Cliek()
Dim I As Single, v As Single, b As Single
Dim a As String
I = [Link]
v = txtTime. Text
a = Comboehoiee(l).Text
• Based on the deposit scheme selected, the functions are called. If the Combo box text field is selected to be
'Fixed Deposit', then the Interest is calculated by calling the FixInterest function referenced by the instance
of the class Intobject,
If Combochoice(l).Text = "Fixed deposit" Then
[Link] = "The Simple Interest amount for the given princip1e is ” &
[Link](I,V)
c = Intobjeet. FixInterest (I,V) + I
• If the Combo box text field is selected to be 'Recurring Deposit’, then the interest is calculated by calling the
RecInterest function referenced by the instance of the class Intobject.
Elself Combochoice(l).Text = "Recurring Deposit" Then
[Link] = "The Recurring Interest amount for the given princip1e is“&
[Link](I,V)
c = [Link](I,V) + I
• If the Combo box text field is selected to be 'Cumulative Deposit', then the interest is calculated by calling
the CumInterest function referenced by the instance of the class Intobject.
ElseIf Combochoice(1).Text = "Cumulative Deposit" Then
[Link] = “The Cumulative Interest amount for the given principle is” &
[Link](I,V)
c = [Link](I,V) + I
End If -
• Lastly the total amount, ie., the sum of the principal amount and the interest is calculated and obtained in the
variable c, which is displayed in the textbox.
[Link] = “The total Amount is” & C
End Sub
• All the coding functionality is complete. Press F5 to run the Form. The Interest Calculator Form appears
as shown below
• Say if we enter the principal amount to be Rs.5500 for a time period of 2½ years and the deposit scheme
chosen to be Commutative deposit, then on clicking the result button, the Interest amount and total amount
is displayed.
*******
OLE Fundamentals
DDE is an acronym for Dynamic Data Exchange. It is the basic foundation for inter process
communication between applications. In DDE, the application creating a link is known as the destination
application, and the application that responds is the source application. Although there are functional
similarities between OLE and DDE, there are a few differences. While using DDE unformatted data is
exchanged. The Visual Basic application has to format it appropriately. For e.g., in case of an Excel
Spreadsheet, the formula used for calculating the result is not fetched, only the resultant number is fetched.
OLE actually transfers control to the original application. OLE is a technology that enables the
programmer of a Windows-based application to create an application that can display data from many different
applications. This enables the user to edit that data from within the application in which it was created. When a
spreadsheet is edited in a Visual Basic program, the original application is called OLE contains the correct
underlying objects so the information is fully editable. The following terms and concepts are the fundamentals
for understanding the methodology to use OLE in Visual Basic.
The application that provides the object's data and the type of data the object contains determines the object's
class. A class defines each object in Visual Basic. The following statements differentiate between an object and
its class.
• The controls in the toolbox in Visual Basic represent a class. This object known as a control does not exist
until it is placed on a Form. When a control is created a copy or Instance of the control class is created. This
instance of the class is the object that is referenced to an application.
• The Form we work with during design time is a class. During run time Visual Basic creates an Instance of a
class.
OLE Automation
Some applications provide objects that support OLE automation. User can use Visual Basic to
manipulate the data in these objects by programming. Some of that support OLE automation also support
linking and embedding. If an object in an OLE container control supports OLE automation, we can access its
properties and methods using the Object property.
Container Application
An application that receives and displays an object’s data is a container application. For example, a
Visual Basic application that uses an OLE container control to embed or link data from another application is a
container application.
Linked Objects
Data associated with a linked object is stored by the application that supplied the object. This
application stores only link reference that displays a snapshot of the source data. When we link an object an
application containing a link to that object can access the object's data and change it. For example, if we
link a text file to a Visual Basic application the text file can be modified by any application linked to it.
The modified version appears in all documents linked to this text file. We can use the OLE container
control to create a linked object in our Visual Basic application.
Embedded Objects
When an embedded object is created, all the data associated with that object is contained in the
object, For example, if a spreadsheet is an embedded object, all the data associated with the cells would be
contained in the OLE container control or insertable object, including any necessary formulae. The name of
the application that created the object is saved along with the data. If we select an embedded object while
working with the Visual Basic application, the spreadsheet application can be started automatically so that
we can edit those cells. When an object is embedded in an application, no other application has access to
the data in the embedded object. We can use embedded objects when we want the application to only
maintain data that is produced and edited in another application.
Example
This example creates a link from an existing application.
• An OLE control is drawn on the Form. This displays an Insert Object dialog box.
• The Create from File option is clicked and the Browse button is chosen. A Browse dialog box appears.
• The desired file is selected from the directory and the OK button is clicked. The Insert Object dialog box is
displayed again. The Link CheckBox is selected and the OK button is clicked.
When a linked object is created, the data displayed in the OLE control exists in one place which is the
source file. The file can be edited in its original application and saved. The object's data can be accessed from
any of the other applications that contain links to that data and the data in the source file can be changed from
within any application.
Example
• An Excel worksheet containing data that is to be linked or embedded is opened. The desired data is selected
from the sheet.
• From the Edit menu, the Copy command is chosen.
• An OLE control is drawn in a VB Form is clicked with right mouse button and the Paste Special command
is chosen from the pop-up menu. It displays a Paste Special dialog box.
• The Paste option is chosen for creating an embedded object and Paste Link option for creating a linked
object.
The above example creates an object from an Excel Worksheet and pastes data from row 45 and row 54 and
from column 1 to 7
Consider an OLE control and a CommandButton are added to the Form. The following code is entered
in the Command1_Click() procedure
Private Sub Commandl_Click()
[Link]
If [Link] = vbOLENoneThen
MsgBox "Object not created”
End If
End Sub
Once the dialog box is displayed, the user can make a choice from the options that are displayed. If the user
cancels the dialog, an object is not created. If the user selects a choice, the selected object is displayed. Any
changes made to the object can be updated in the OLE control by choosing Update from the File menu in that
object. Once the application is chosen to be linked, it is necessary to check if the application is running, To
check if the application is running, the following code ([Link]) is used.
Example
All OLE control is added to a Form. The following code is entered in the OLE1_ObjectMove() procedure.
Private Sub OLEl_ObjectMove(Left As Single, Top As Single, Width As Single,
Height As Single)
[Link] [Link], [Link], Width, Height
[Link] Top,Left, [Link], [Link]
End Sub
When an application supports OLE Automation, the objects it exposes can be accessed by Visual Basic.
Visual Basic could be used to manipulate these objects by invoking methods on the object or by getting and
setting the object's properties. For example, if we create an OLE Automation object named MyObj, the
following code could be written for manipulating the object
[Link] “Hello World”
[Link] = True
[Link] “C:\WORDPROC\[Link]”
The following functions are used to access an OLE Automation object.
• CreateObject creates a new object of a specified type.
• GetObject retrieves an object from a file.
Example
A new project is opened and the following code is entered in the Form_Load() procedure.
Dim myApp As Object
Set myApp = CreateObject(“[Link]")
[Link]
[Link] = True
The following example uses the GetObject function to get a reference to a specific Microsoft Excel Worksheet.
The file, [Link] in the example, must exist in the specified location; otherwise a Visual Basic error known as
the OLE Automation error is generated.
Example
The following code is entered in the Form_Load() procedure of a new Standard EXE project.
Dim MyApp As Object
Dim ExcelNotRunning As Boolean
On Error Resume Next
Set MyXL = GetObject(,"[Link]")
If [Link] <> 0 Then ExcelNotRunning = True
[Link]
Set MyXL = GetObject("I:\[Link]")
[Link] = True
[Link](1).Visible = True
If ExcelNotRunning = True Then [Link]
Set MyXL = Nothing
The above example uses the worksheet's Application property to make Microsoft Excel visible, to close it and
so on. The first call to GetObject causes an error if Microsoft Excel is not already running. In this example, the
error causes the ExcelWasNotRunning flag to be set to True. The second call to GetObject specifies the file to
be opened. If Microsoft Excel is not already running, this second call starts it and returns a reference to the
worksheet represented by the specified file. Next, the code in the example makes both Microsoft Excel and the
window containing the specified worksheet visible. Finally, if there was no previous version of Microsoft Excel
running, the code uses the Application object's Quit method to close Microsoft Excel If the application was
already running, no attempt is made to close it. The reference itself is released by setting it to Nothing.
OLEDrag Method
This method is used to initiate an OLE drag operation. The OLEDrag Method is called when data is
copied between two OLE containers. The following syntax is used [Link] where object is the OLE
container object that acts as the source for the drag operation.
OLEDragMode Property
This property is used to determine if the object can act as an OLE drag source, and if the OLEDrag
operation is done manually or automatically. The allowable property values are
• vbOLEDragManual-0 This is the default value. It is used when the user's own OLE drag handlers are used
in the application.
• vbOLEDragAutomatic-1 This is used when the application has to handle the drag and drop operations.
OLEDropMode Property
This property determines the methodology of processing OLE drop events in the application. It can take
any one of the following values
vbOLEDropNone-0 This is the default value. It prevents the OLE container from allowing OLE drop events.
vbOLEDropAutomatic-1 This is set when the user entrusts Visual Basic with handling of the OLE drag routines.
OLEDropAllowed Property
This property determines whether the OLE drop operations are allowed or not. If this is True it allows
OLE drop operations on the container, otherwise drop operations are prohibited.
OLEDragDrop( ) event
This event is fired whenever an OLE drop operation is performed on an OLE container which allows
OLE drop operations. The syntax of this event is as follows
Private Sub object_OLEDragDrop(data as DataObject, effect As Long, button a
Integer, shift as Integer, x As Single, y As Single)
OLE DataObject can be referenced using the GetData method to retrieve the data be dropped in this event.
Effect parameter is used to communicate to the target component the action that is to be performed on the data.
The effect parameter can be anyone of the following as shown in below Table.
Description
Parameter
vbDropEffeetNone - 0 Target cannot accept OLE data
vbDropEffectCopy - 1 Specifies that data should be copied from source to destination
vbDropEffectMove -2 Specifies that data must be moved from source to destination
vbDropEfIectScroll Indicates if the target has scrolled, or would scroll if the data were
- 2147483648 dropped onto it. Used rarely
The button parameter is used to identify the button on the mouse that was clicked during OLE drag operations.
Value Description
1 Left Button
2 Right Button
3 Middle Button
The x and y parameter indicates the current position of the mouse pointer. These values are used if
dropping is required within the target control.
We can also drag and drop between applications, which support OLE drag and drop operations.
********
The following code is entered in the general declaration section of the Form.
Option Explicit
The following code is entered in the Form_Load( ) procedure.
Private Sub Form_Load()
[Link] “All files(*.*)”
[Link] “Doc fi1es(*.DOC)”
[Link] "text files(*.TXT)”
[Link] = 0
[Link] = [Link]
End Sub
The above procedure initializes the ComboBox and the AddItem method fills it with three items which
includes All files (*.*), Doc files(*.DOC) and Text files(*.TXT). Then the Listlndex property of the ComboBox
is set to 0. This sets the currently selected item of the ComboBox to item 0, or All files (*.*). Finally, the
Caption of Label4 is set to the Path property of the DirListBox. The initial value of the Path property is the
current directory, and hence when we start the program, Label4 displays the name of the current directory. The
following code entered in the Drivel_Change() procedure is executed whenever the DriveListBox is changed.
Private Sub Drivel_Change0
On Error GoTo ErrorTrap
[Link] = [Link]
Exit Sub
ErrorTrap:
MsgBox "Drive Error!",vbExclamation,”Error"
[Link] = [Link]
Exit Sub
End Sub
An error trap is set before the procedure. This executes the command that changes the Path property of
the DirListBox. This error trap is required, because changing the path of the DirListBox may cause an error at
run time. For example, if the DriveListBox is to drive B, and the drive B is not ready, changing the path of the
DriveListBox may cause an error. Visual Basic gives control to the code below the ErrorTrap label. This code
displays an error message and restores the original value of the drive.
The following code is entered in the Dirl_Change() procedure and is executed whenever the DirListBox is
changed.
Private Sub Dirl_Change()
[Link] = [Link]
[Link] = [Link]
End Sub
The code in the above procedure updates the Path property of the FileListBox and the Caption property
of Labe14 with a new directory. As a result of updating the FileListBox with the selected directory, it displays
the files of that directory.
The following code is entered in the Combol_Click( ) procedure which updates the Pattern property of
the FileListBox according to the selected file type. The Pattern property returns or sets a value indicating the
filenames displayed in a FileListBox control at run time. A Select Case is used to determine which item in the
ComboBox is selected. Depending on which item is selected from the ComboBox, a different Case statement is
executed.
Private Sub Combol C1ick()
Select Case [Link]
Accessing Files
A file consists of a series of related bytes located on a disk. When an application accesses a file, it must
assume what the bytes are supposed to represent. Depending on the kind the data the file contains, we can use
the appropriate file access type. There are three ways of accessing files in VB. They are
• Random Access
• Sequential Access
• Binary
Let us design and develop an application that illustrates the creation and manipulation of a random
access file. The program allows us to maintain a database file called [Link] that holds the record of
product information. The program opens the file in a random access mode with the following fields:
Product_Name, Product_Code, Price, Date_Of_Manufacture. If the file does not exist it creates one.
Example
• A new Standard EXE project is opened and the Form and the project are saved as [Link] and
[Link]. The Form is designed as per the following specification table.
• Besides the Form file the application also requires a program module. Hence, a module is added to the
project, by selecting Add module from the Project menu.
The following code is entered in the general declaration section of Modulel. This declares a user-defined type
that corresponds to the fields of a record in the Product Dat file. The declared type is a ProductInfo, and is made
up of variables that include Name of the product, product code, price, date of manufacture. Each of these strings
corresponds to a field in the [Link] file. Later, the program uses a variable of the type ProductInfo to read
and write data into the [Link] file.
Option Exp1icit
Type Productlnfo
Name of the product As String * 20
Product code as string* 5
Price as string* 8
date of manufacture As String * 20
End Type
The following code is entered in the general declaration section of the Form.
Option Explicit
Dim LastRecord As long
Dim CurrentRecord As Long
Dim RecordLen As Long
Dim Product As Productlnfo
The RecordLen and Filenum variables are now updated and the procedure opens the file [Link] for
random access in the C:\ directory. If the file does not exist, the Open statement creates it. After the file is
opened, the procedure updates the variables, LastRecord and CurrentRecord. The variable CurrentRecord is
used to store the record number of the currently displayed record. Since the record number 1 should be
displayed initially, CurrentRecord is initialized to 1.
The variable LastRecord is used to store the record number of the last record in the file, which is
calculated by dividing the total file length by the length of a record. However, if the file was just created, the
FileLen( ) returns 0 and the above calculation yields a value of 0 for LastRecord. An If statement is used to
check whether LastRecord is 0 and if it is so, the statement changes it to 1. The last statement of the procedure
displays the data of the record specified by the variable CurrentRecord.
A new procedure called SaveCurrentRecord is created which is responsible for saving the contents of the
TextBox controls in the record specified by the CurrentRecord.
Private Sub SaveCurrentRecord()
[Link] = [Link]
[Link] = [Link]
[Link] = [Link]
Person.manufature_date = [Link]
Put #Filenm, CurrentRecord, product
End Sub
The first six statements of the procedure fill the variable product with the contents of the Textbox controls.
After the variable is filled, the procedure is executes the Put statement store the contents of the variable in
record number CurrentRecord of the file. The Put statement takes three parameters. The first parameter
specifies the file number of the file, the second parameter specifies the record number that is being saved and
the third parameter specifies the name of the variable whose content is saved in the record. A new procedure
called ShowCurrentRecord is created in the declarations section of the Form that displays the record specified
by the variable CurrentRecord.
Public Sub ShowCurrentRecord()
Get #Fi1enum, CurrentRecord, product
[Link] = Trim(Product. Name)
[Link] = Trim([Link])
[Link] = Trim([Link])
[Link] = Trim(Person.manufacture_date)
[Link] = "Record" + Str(CurrentRecord) + "/" + Str(LastRecord)
End Sub
The first statement of the procedure uses the Get statement to fill the variable Person with the data of the current
record. The Get statement takes three parameters. The first parameter specifies the file number of the file (the
number specified when the file was opened), the second parameter specifies the record number of the record
to be read, and the third parameter specifies the name of the variable that is filled with the data read from the
record.
After the variable Product is filled with the data of the current record, its contents are displayed by
updating the Textbox controls. The TextBoxes are assigned with the trimmed values of the Product variable
because it should not contain any trailing blanks. For example, if the current record in the database contains the
product name as Visual Basic Book in the Name field, after the Get statement is executed, the variable
[Link] contains the following characters.
"VANISHREEVisualBasicBook .....”
Since the Product_Name field was defined as 3020 characters and VisualBasicBook contains only 159
characters, Visual Basic adds 11 15 trailing blanks to the field when the record was stored. The trailing blanks
should not appear on the text boxes and hence the Trim() function is used. The last statement of the procedure
displays the current record number in the Form’s caption. The following code entered in the cmdNew_Click( )
procedure, adds a new record to the file.
Private Sub cmdNew_Click()
SaveCurrentRecord
LastRecord = LastRecord + 1
Product.Product_Name = “ “
Product.Product_Code = “ “
Product.date_of_manufacture_date = “ “
Put #Fi1enum, LastRecord, Product
CurrentRecord = LastRecord
ShowCurrentRecord
[Link]
End Sub
The first statement of the procedure executes the SaveCurrentRecord() procedure so that the current record is
saved in the [Link] file. After saving the current record, the procedure specifies a new blank record to the
file as per the statements from 2 to 9. The second statement increments LastRecord, so that it points to the new
record number, then the Person variable is set to null, and finally the Put statement is used to create the new
record.
After creating the new blank record, the CurrentRecord variable is updated and it points to the new
record. Then the ShowCurrentRecord( ) procedure is executed so that the record that was just created is
displayed. The last statement of the procedure uses the SetFocus method to set the keyboard focus to the
TextBox namely Textl. The following code is entered in the cmdPrevious_Click( ) procedure which displays the
contents of the previous record.
Private Sub cmdPrevious_Click()
If CurrentRecord = 1 Then
MsgBox "Beginning of File!", vbExclamation
Else
SaveCurrentRecord
CurrentRecord = CurrentRecord - 1
ShowCurrentRecord
End If
[Link]
End Sub
The first statement of the procedure is an If statement that checks if the CurrentRecord is equal to 1 and if so, a
message box is displayed. If the CurrentRecord is not equal to 1 the procedure SaveCurrentRecord( ) saves the
contents of the TextBox controls to the [Link] file and the CurrentRecord variable is decremented by 1
and points to the previous record. The procedure ShowCurrentRecord( ) is then executed and the TextBoxes
display the new value of the CurrentRecord. The following code is entered in the cmdExit_Click( ) procedure,
which is executed when the Exit button is clicked.
Private Sub cmdExit Click()
SaveCurrentRecord
Close #Filenum
End
End Sub
The code in the above procedure saves the current record and closes the [Link] and [Link] file.
The Close statement takes one parameter that specifies the file number of the file to be closed. The End
statement terminates the application.
In order to create a sequential file, we need to open a file for output. After the file is created, we can use
the output command to write lines to the file. The following code example creates the [Link] and
writes the contents of the TextBox Text1 into the file.
Example
• A new Standard EXE project is opened and a TextBox and CommandButton is added to the Form. The
Form and the project files are saved as [Link] and [Link].
• The following code is entered in the Commandl_Chck( ) procedure.
Private Sub Commandl_Click()
filenum = FreeFile
Open "C:\[Link]" For Output As filenum
Print #filenum, [Link]
Close filenum
End Sub
• The application is run by clicking F5. Text that is necessary is entered in the TextBox and the
CommandButton is clicked.
• The entered text appears in the file [Link] file. This can be viewed by opening the file in the
Notepad after terminating the application.
If the file [Link] does not exist, the code creates it. If the file exists already, the code erases it. Since
opening a file for output creates the file, it will be empty. The Print statement is used to write text into the file.
Two parameters are passed to this statement. The first parameter is the file number and the second is the string
to be written into the file. Opening a sequential access file for append is similar to opening it for output. When a
file is opened for append, it is not erased if the file already exists. Rather, subsequent output commands append
new lines to the opened file. Let us assume that the file [Link] already exists and it contains the
following two lines.
God is Great
God is Grace
The following code appends the existing file.
• Two more CommandButton controls namely Command2 and Command3, and a TextBox control Text2 are
added to the [Link]
• The following code is entered in the Command2_Click( ) event.
• The application is run and the Command2 button is clicked.
Private Sub Command2_Click()
filenum = FreeFile
Open "c:\[Link]" For Append As filenum
Print #fi1enum, "Work is Worship"
Close fi1enum
End Sub
After executing this code, the file [Link] contains three lines. If the same code is executed again, the
file contains four lines.
God is Great
God is Grace
Work is Worship
Work is Worship
In order to open the sequential file for input, we can use the Input statement. Once the file is opened for input,
the Input( ) function can be used to read the entire contents of the file into the TextBox or a string variable. The
following code is entered in the Command3_Click( ) procedure.
Private Sub Command3_Click( )
fi1enum = FreeFi1e
Open "C:\[Link]" For Input As filenum
File1ength = LOF(1)
[Link] = File1ength
[Link] = Input(LOF(filenum),filenum)
C1ose fi1enum
End Sub
Once the code is executed and the CommandButton is clicked, Text1 control displays the file length and
Text2 displays the contents of the file. The Input() function takes two parameters. The first parameter
specifies the number of bytes to be read from the file and the second parameter specifies the file number. The
LOF( ) function returns the length of the file in bytes.
filenum = FreeFile
Open "c:\[Link]" For Binary As fi1enum
Put #fi1enum, 100, mystring
Close fi1enum
End Sub
The application is executed and the click event of the CommandButton creates the file [Link]. The Put
statement takes three parameters. The first parameter is the file number, the second is the byte location where
the writing starts and the third is the name of the variable whose contents will be written into the file.
The Tabbed Dialog control provides a group of tabs, each of which acts as a container for other controls. The
controls are exclusive to the particular tab. Other tabs cannot use the controls of one tab. We cannot see one
tab's control in another tab control.
For each of the ‘tabs’ you can set properties, add other controls and write the code necessary. The properties are
set using the property pages. Some of the properties can set during the runtime as well. However, it is better to
set the properties during the design time.
Now we need to set the Properties for each of the Tab. We need to,
➢ Add controls to each of the tabs.
➢ Change the caption for each of the tabs.
➢ Write code for the control is where necessary.
The control uses bitmap(.bmp), cursor(.cur), icon(.ico), JPEG(.jpg), or GIF(.gil) files in a collection of
Listlmage objects. You can add and remove images at design time or run time. The ListImage object has the
standard collection object properties: Key and Index. It also has standard methods, such as Add, Remove, and
Clear. However, once the ImageList has been associated with another control you cannot delete or insert images
in the ListImages collection. You can only append images.
Click the Images tab to display the ImageList control’s Property pages, as shown below
Click Insert Picture to display the Select Picture dialog box. Use the dialog box to find either bitmap or icon file
files, and click Open. Click on the key box and enter a string that will uniquely identify that image. This string
can be used to refer to the image that has been added to the ImageList collection. Optional. Assign a Tab
property setting by clicking in the Tag box and typing a string. The Tag property doesn’t have to be unique.
TabStrip Control
The function of a TabStrip control is very similar to that of the SSTab. It is used to create a tabbed
dialog box to allow users to set various attributes. It can also be used to create a tabbed dialog that preference
for an application.
The TabStrip control looks like control consists of one or more Tab objects in a Tab collection. You can affect
the Tab object’s appearance by setting properties both at design time and run time, an at run time, by invoking
methods to added and remove Tab objects.
You can add a tab at run time with code like this.
[Link] ‘find’,‘Find’,‘Fbooks’
This line of code will add a tab with Caption ‘Find’, and load the picture ‘Fbooks’. However, before using the
above code line we must associate the TabStrip control with the ImageList control.
One should take precautions to ensure that the hidden controls do not respond to the ALT + Key combinations.
The ZOrder will not inactivate the other controls, and they may respond to the ALT + Key combinations.
MSFlexGrid Control
The MSFlex control displays and operates on data in a table form. The Flex Grid is designed to only
display the data and not allow the user to enter data in it. However, the user can sort, merge, format tables
containing string and pictures. When bound to a Data control, MSFlexGrid displays read-only data. However,
with a little programming we can do what the guys at Microsoft did not build into the FlexGnd control. We
allow the user to enter data in the FlexGrid using a textbox.
You can add text, a picture, or both, in any cell of a MSFlexGrid. The Rowand Col properties specify
the current cell in an MSFlexGrid. You can specify the current cell in code, or the user can change it at run
time using the mouse or the arrow keys. The Text property references the contents of the current cell.
The user can resize the cell's width or height in design time or run time. If a cell's text is too long to be
displayed in the cell, and the WordWrap property is set to True, the text wraps to the next line within the same
cell. To display the wrapped text, you may need to increase the cell's column width (CoIWidth property) or row
height (RowHeight property). Let us take up the simple task of connecting the FlexGrid to a database. We will
display the data from one of the tables in the [Link].
Draw a FlexGrid control to your form. If it is not there on your ToolBox then first add it to your TholBox as
you added other controls. Choose the Microsoft Flex Grid control from the components list. Add a Data control.
Set the properties of the Data control as follows
✓ DatabaseName: [Link]
✓ RecordSource: Customer
✓ Bring up the properties window of the FlexGrid control and set its properties as DataSource: Datal,
Number of rows: 5, Number of columns: 4
Now run the program. The customer details will be displayed in the Grid.
*******
However, today's data access requirements are not limited to handling only relational data. We need to
access data from other sources as well, such as mail, Internet content, directory data from other machines and
others. The technology required to access information from these different data source is different. Therefore,
the data access modal will have to change to accommodate the new requirements.
We can access any type of data and store it locally in a new type of database and tackle the various types
of data using its native method, or we can implement the various technologies in our data access table. Both
these alternatives have their own problems.
Moreover, our requirements do not end with merely getting the data from the source and downloading it
on our machine. We would also like to make changes to the data and update the data source with these changes.
What we need is a simple, consistent application programming interface (API) that enables applications to gain
access to and modify a wide variety of data sources. A data source may be a database, a text file, a spreadsheet,
a graphics application, a cluster of heterogeneous databases, or something yet to be invented.
OLEDB
The general solution Microsoft offers to this problem is OLE DB, a set of Component-Object Model
(COM) interfaces that provide uniform access to data stored in diverse information sources. OLE DB is defined
as a new low-level interface that is part of the Universal Data Access platform. It is defined as a general-
purpose set of interfaces designed to let developers build data access tool as component using the Component
Object Model (COM). OLE DB enables applications to have uniform access to data stored in DBMS and non-
DBMS information containers, while continuing to take advantage of the benefit of database technology
without having to transfer data from its place of original to a DBMS.
This means that OLE DB is not restricted to ISAM, Jet, or even relational data sources, but capable of dealing,
with any type of data, regardless of its format or storage method, In practices, this versatility means you can
can access the data that resides in an Excel spreadsheet, text files, or even on a mail server such as Microsoft
Exchange. OLE DB has what it calls ‘provider' which let you access the different data source.
For different data sources you have different data providers. OLE DB provides four services that you will be
using in application
1. A Cursor Service. A cursor is defined as temporary, read-only table that saves the result of a query with
assigned name. The cursor is available for browsing, reporting, or other uses until it is closed.
2. A service to perform batch updates.
3. A shape service to build the data in the form of a hierarchy.
4. A remote data service provider for managing data in multi-tier environment over connected or disconnected
networks.
Unfortunately Visual Basic cannot access the OLE DB directly because of its sophistication. This is where
ADO comes into the picture. The ADO acts like the intermediary between the application and the OLE DB.
Now that you understand why we need ADO, let us see what ADO is all about.
ADO
ADO enables your client applications to access and manipulate data in a database server through any of
the OLE DB providers. According to Microsoft, ADO’s primary benefits are ease of use, high speed, low
memory overhead, and a small disk footprint. ADO supports key feature for building client/server and Web-
based application.
In the case of the DAO you have seventeen objects. In the case of the ADO you have only seven objects.
Besides, you do not have to follow a strict hierarchy when working with the objects. The goal of ADO is to gain
access, to edit, and update data sources. It provides classes and objects to perform each of the following
activities:
• Connection You can access a data source using the Connection object. A connection represents an open
session or connection to a data source. Unless a connection is made, data cannot be exchanged between the
data source and the application. The connection object specifies the name of the data source, the provider
that will be used to access the data, and other parameters.
• Command Once a connection has been established with the data source, the data has to be extracted. This is
done using the Command Object. The Command adds, deletes and updates data in the data source, or
retrieves data in the form of rows in a table.
• Parameter The command to retrieve data can be qualified using parameters. Parameters are arguments to a
command that alter the result of the execution of the command.
• Recordset The command object when executed will return a set of rows from one or more tables. This set of
rows is called a Recordset. The Recordset is the primary means of examining and modifying data in the
rows. The Recordset object allows you to:
✓ Specify which rows are available for examination
✓ Traverse the rows
✓ Specify the order in which the rows may be traversed
✓ Add, change, or delete rows
✓ Update the data source with changed rows
✓ Manage the overall state of the Recordset.
• Field A row of a Recordset consists of one or more fields. If you visualize the Recordset as a two
dimensional grid, the fields line up to form columns. Each field (column) has among its attributes a name, a
data type and a value. It is this value that contains the actual data from the source.
• Errors Error can occur at any time in your application, due to the data source being corrupted or renamed by
somebody, or the password being changed or many other reasons that programmer can understand.
• Property Each ADO object has a set of unique properties that either describe or control the behavior of that
object. There are two types of properties: built-in and dynamic. Built-in properties are part of the ADO
object, and are always available. Dynamic properties are added to the ADO object’s Properties collection by
underlying data provider, and exist only when that provider is being used.
• Collection Just as in DAO, ADO provides collections, a type of object that contains other objects of a
particular type. The objects in the collection can be retrieved with a collection method, either by name, as a
text string, or by ordinal as an integer number. ADO provides four types of collections:
✓ The Connection object has the errors collection, which contains all Error objects created in response
to a single failure involving the data source.
✓ The Command object has the Parameters collection, which contains all Parameter objects that apply
to that Command object.
✓ The Recordset object has the Fields collection, which contains all Field objects that define the
columns of that Recordset object.
✓ In addition, the Connection, Command, Recordset, and Field objects all have a Properties
collection, which contains all the Property objects that apply to their respective containing
objects.
• Events This is new in ADO. ADO 2.0 introduces the concept of events to the programming model. Events
are notifications that certain operations are about to occur, or have already occurred.
Establishing a Reference
Open a new project. To use ADO in your project, you have to make a reference to it. Click on Projects,
and from the menu Select References. From the list displayed in the references dialog box, select Microsoft
ActiveX Data Objects 2.0 Library and the Microsoft ActiveX Data Objects Recordset 2.0 Library.
In order to achieve our objective of accessing a data source, extracting a set of records from it and
manipulating or editing the Recordset and finally updating the DataSource we have to follow the below steps.
✓ Make a connection to a data source.
✓ Create a command to specify the records to be extracted.
✓ Execute the command.
✓ Navigate and edit the data in the Recordset.
✓ Update the data source with changes made to the data in the Recordset.
ADO does not follow strict hierarchy. You can create a Recordset without explicitly making a connection.
Click on Select to choose the name of the .mdb file. After selecting the .mdb file, enter the name of the
data source. You will be using this name as the DSN (Data Source Name). Click Ok and exit from the ODBC
administrator.
Add the line "MsgBox [Link]" to see if the database has been opened. Run the program
and checkout if you have managed to set up a connection with the data source using ADO.
Creating the command We have established a connection with the data source. Now we need to construct our
command using SQL such that it will return the records as recordsets. Our Command can be a literal string or a
variable that represents the string. We can select all the records from the Customer table of the [Link].
The command object must be linked to the connection object using the following line.
[Link] = adocon
Executing the command Now that we have built the command, the command must be executed. The command
can be executed by either using the command object, or by using the Recordset object. Add the following lines
to your code
Set rs = [Link]
MsgBox [Link](l)
In this case you are using the command object to execute. The Connection object is not visible here. The
Connection object is set in the ActiveConnection property of the Command object. Block the above lines and
add the following lines
Set rs = [Link]("seleet * from Customer")
MsgBox [Link](l)
In this case the Connection object is used without bringing in the Command object. These methods have their
own advantages and disadvantages. The two methods that return a Recordset are [Link],
Command Execute. The syntax is as follows
[Link](CommandText, RecordAffected, Options)
[Link](RecordAffected, Parameters, Options)
Both methods return fast, static-cursor, forward-only Recordset objects. The CommandExecute method allows
you to use parameterized commands that can be reused efficiently.
Manipulating the records in the Recrodset The properties and methods for a Recordset in DAO are valid here
as well. Most of the properties of the Recordset deal with navigating and manipulating the Recordset. The row
that has your focus is the ‘current row’. If you move to the next row then that row becomes your ‘current row’.
There are methods to locate a particular record, to delete records, to update records and so forth. There are also
properties that will view selective records, sort them in an order of your choice, etc. Add a command button to
your form. Add the following lines of code to its cIick_event.
Private Sub Command1_Click()
[Link]
Do While Not [Link]
[Link] [Link](O) & " "; [Link](l)
[Link]
Loop
End Sub
This segment of code will display the first two fields of the Recordset. Remember that this Recordset returns all
the fields from the Customer Table of the [Link]. We are viewing only the first two fields of the
Recordset. The MoveFirst method moves the record pointer to the first record. The MoveNext method moves
the record pointer to the next record.
If you want to view only a certain set of records you can set the filter property of the Recordset, In order
to view only those customers who are from Bangalore you can add the following line to your code.
[Link] = "Customer_City LIKE 'Ban*'"
Your code will look like this
Dept. of Computer Science, HiSAC, Erode 118
Visual Basic – Unit V
The Property Pages of the ADODC allow you to specify a lot more information than the Data control. In
the case of the Data control, you only need to give the following four details.
The type of database (Access, dBase, FoxPro ...)
The Name of the database
The type of Recordset (Table, Dynaset, Snapshot)
The RecordSource (A Table name, an SQL Query…..)
However, you may need to do a little more in case of the ADODC, the Property pages of ADODC contain four
tabs. They allow you to set the various properties of the ADODC. They are
General In this tab you specify how the ADODC should connect to a data source. There are three options.
Use data links file You will need this option if you are going to link a textbox or a grid or some such control to
an application like Excel or Word via DDE.
Use ODBC date source name You can mention the name of the DSN that we created using the ODSC Data
Source Administrator, The DSNs already created will be displayed in a drop-down ListBox. You can select the
one you need to work with, or you can build a new DSN.
Use connection string You can build the connection string here by clicking on the 'Build' button. This will
bring up a Wizard and guide you along.
Authentication This lets you enter Authentication information like the User Name and Password.
RecordSource Here you can specify the method of creating the Recordset. That is, you can indicate the
Command Type (adCmdUnknown or adCmdText or adCmdTable, or adCmdStoredProc)
Font and color The other two tabs Font and Color allow you to customize the appearance of the ADO Data
Control.
There are two approaches that ADO uses to add or modify the data in the database
1. Changes made to the data or the row are made in the 'copy buffer' and not directly to the Recordset. If
the changes are acceptable then they are applied to the Recordset.
2. Changes are made directly to the data source either immediately or in a batch mode. These modes are
governed by the CursorLocation and LockType properties. Changes will make to the data source in the
immediate mode as soon as you confirm an update.
In the Batch node, every time you confirm an update, the Recordset gets update and not the data source. In
order to update the data source you have to invoke the UpdateBatch method. In order to use this method you
must open the Recordset in the batch mode. You can also make a change to the data in a field or fields and
invoke the update in one step.
If your application has transactions that update more than one table it is a good idea to use the
‘transaction’ method. This is to ensure that related operations that depend on each other either all occurred
successfully, or else were all canceled. There are three transaction methods involved. They are
BeginTrans To be invoked when you start working on the Recordset. This method begins a new transaction.
Once the BeginTrans method has been invoked, the OLEDB provider will not continuously commit the
changes made to the data source unless you call CommitTrans to commit the changes or RollbackTrans to
reverse the changes and end the transaction.
CommitTrans To be invoked when you want to commit the changes to the data source. CommitTrans saves
any changes made to the Recordset and ends the current transaction.
RollbackTrans This method is to be invoked to cancel any changes made within the current transaction. This
method also ends the current transaction.
The CommitTrans and the RollbackTrans may also start a new transaction. The following code will show you
how to use the Transaction methods. Add a Module to your project.
In the code Module, create a function to display the current row of the Recordset
Sub Showfields()
[Link] = rs!Customer_Name
[Link] = rs!Customer_City
End Sub
This code will display the next record record everytime that you click on the Next button. Now let us assume
that the user wants to edit the data that is displayed. To the Edit button add the following code
rs!Customer_Name = [Link]
rs!Customer_City = [Link]
[Link]
This segment of code is enough to update the Recordset. In case you want the System to prompt you about the
changes made. You can write another procedure called UpdateRecord. This procedure will have the following
code.
If MsgBox(“Save all changes?”, vbYesNo) = vbYes Then
[Link]
Else
[Link]
End If
The above code segment will ask for your confirmation before committing the changes made by you. If you
answer yes to the above question, the changes are committed to the data Source. If you answer No then the
changes are rolled back.
*****
We can build this functionality into our application with the help of VBA code or through report
generators like Crystal Reports or Data Report. Crystal Reports is a third party product developed, by Seagate
of Singapore. It has been bundled with various data access tools.
Application You can access Crystal Report only through the VB IDE. If the Crystal reports have not been
installed then follow the step given below. Prepare a pencil copy of the report structure that you want to create.
Installation So, Crystal Reports has been installed and you have a rough ‘copy’ of the report that you want. Let
us get started. Click on Add_Ins, Select Report Designer. Click on Field and Select New. Or click on the icon
that represents a new report.
preview the report that you are creating. Once you do that you cannot come back to the wizard. Should you
wish to return to the wizard, you will have to start all over again. We will see the various steps required to
create a Standard Report and then call the 'Expert' for a particular step.
The wizard in the dialog box will ask you to select the database(s) that you will be using to generate the
report. Let us select [Link] for a change. Upon selecting the [Link], all the tables and stored queries /
view will get added to the ListBox. After you have added all the databases that you want to work on click on
'Done'.
This figure will display the various tables and the relationship between each of them. If you think there
are too many tables and views and you do not need all of them, then you can delete some of them. Click on the
button ‘Back’. Click on the ‘Back’
You can select the items that you do not need and click on remove to remove them one by one. When
you are sure you have only those tables that you need click Next to continue. It will show the selected tables
and their relationship. Click Next to continue.
In next dialog box you can add the fields that you wish to include in your expert. The fields that you
select here will appear on the report. However the selection criteria for the selected records need not depend on
the fields alone. When you have selected the fields and added them one by one in the ‘Report fields’ ListBox.
Click on the Next to continue.
In next dialog box you can choose the fields on which the report is to be sorted out. For example, you
can sort all the details based on the City, or the Product that a customer uses, or the Turnover of the company,
etc. Select the fields on which the criteria are to be built and then select the sort order. For example, you can
sort the details in the ascending order or descending order. When you are through with this click Next to
continue.
In next dialog box you must select the fields on which you have to perform calculation like group total,
sun-total, etc. For example if you want to know the number of customers in a particular city, the select
Customer_City and add it to the ‘Total Fields’ ListBox. Here you can also choose if you want to total the
number of customers for a city or if you want to the add the figures for a particular column. For our example
choose Count. Then Click Next to continue.
In next dialog box you must choose the fields based on which the records must be selected from the
database. In the Report Fields ListBox you are presented with the fields that you have selected for the report. If
none of these fields meet your requirements to determine the selection criteria, you can scroll down further and
select from the fields that have not been included in the report. Build your selection criteria and click Next to
continue.
In next dialog box you can select the layout of the report. Select the report layout style that you think
suits you best. The selection of the style will depend upon the type of data that you are likely to have on the
report. For example, if you are going to have the total amount outstanding from a customer, and your report will
hold the status of customer for customer for a city, or area then you can choose. Trailing Break Style or the
Drop Table style. Next you can preview the report. The preview of the report will look like this. So we have
created a report from scratch with the help of a wizard or an Expert.
From the extended set of buttons displayed select Custom and then click on the Data File button. You
will be asked to select the database file. Select [Link] in order to complete this example.
This is called the Design/Preview window where you can design and view the report as you go on
adding fields to it.
of these titles is separated by a line that extends into the large white area. This is to help you correctly insert and
correct the data that should appear on the report. If you click on the Preview tab, a preview of the report will be
displayed. You can zoom to get a better view of the report.
In the Insert Data Field dialog box displayed over the design window consists of the list of fields that
you can display on the report. Apart from the list box there are three buttons "Insert", "Done" and "Browse
Field Data". To insert a field select it and push the Insert button. Your mouse pointer will suddenly acquire a
square tail. This is tells you that you have selected a field and you can insert it at a location on the report. Move
the pointer to the location where you wish to display the selected field and click on the mouse. The field will get
inserted at that location.
Let us get back to the Insert Data Field Dialog box. Select Customer_Name from the list of fields
displayed in the ListBox. Click on the 'Insert' button. Notice that your mouse pointer has acquired a 'tail'. Move
the mouse pointer to the section ‘Detail' on the 'White Area' and click the left mouse button. The Customer
Name field gets placed there along with the heading. You can change the column heading later if you do not
like the current heading. Similarly add two more columns namely Order_Date and Order_Value to the report.
Click on the Preview tab to view the report. You will see a list of the customers with the Order Date and Order
Value. Some of the problems with this report are:
1. The customer names are repeated.
2. There are no sub-totals for individual customers.
3. There is no grand total of the Order Value.
Let us see how we can correct them. We are at liberty to call on the 'experts' for help. We will first sort the
listing on Customer_Name. Click on the 'Reports' Menu Option. From the menu items select Sort ‘Records'.
You will see the following dialog box. From the list of items in Report Fields ListBox on the left add the
Customer_Name to the Sort Fields ListBox on the right. Select the Ascending order for sorting the records.
Now click the Preview tab to see the result.
To avoid repeating the Customer_Name for every occurrence, click on Format. From the menu click on
‘Fields’. Click on the 'Suppress if Repeated' option button. To include Sub-Totals for the Order_Value for each
customer for each customer, right click the mouse button Order_value in the Detail section. From the pop-up
menu select ‘Insert Sub-Total'.
The message displayed will be "When the report is printed the records will be sorted and grouped by".
Next to this message is a drop-down combo box. Click on the down arrow to View the list of fields that you can
group by. Select Customer_Data Customer Name. A message will appear at the bottom of the dialog box. "The
subtotals will be printed on any change of Customer_Data.Customer_Name". Click OK to accept the changes.
To add the Grand Total to represent the total of all Order_ Values, once again right click the mouse on the
Order_Value in the Details section. From the pop-up menu select 'Insert Grand Total'.
Select 'Sum' from the drop-down ComboBox. You have a wide choice of options to choose from for the
Grand Totals column. Now preview your report. Save the report in your directory. It will have an extension
name “.rpt".
The most important property to set here is the ReportFileName. This is set in the General Tab. Set it to
the filename under which you saved your report. Under this tab you can also specify if your report should goto
the printer or to the window or to a file. Add a CommandButton to your form. In the click event of the
CommandButton add the following line of code
[Link] = 1
If you are going to use more than one report file in your program then you need to set the ReportFileName
before you run the report. You see the ReportFileName as follows
[Link] = "C:\vb-exersices\[Link]"
[Link] = 1
Most of the properties that you see in the property pages are available at runtime and can be modified when
needed. You can for example use a selection formula to select the records that appear on the report. If you want
the report to display selected records, for example you want to see details of the customer whose
Customer_Code is C455 then add the following line in the SelectionFormula ListBox under the Selection Tab.
{Customer_Data.Customer_Code } = "C455"
Run the program and you will see the details of customer C455 only.
Data Report
Data Report is the new offering from Microsoft perhaps with a view to replacing Crystal Reports in the
long run. Data Report as it stands today is meant for programmers. A general user of computers will not be able
to get around it. Let us take a look at what Data report has to offer and how we about using this tool.
In order to use Data Report you need to use ADO or Data Environment. Since we have covered ADO in
the previous chapter we will work using ADO with Data Report. You need to follow the following steps to
generate a report using the Data Report.
1. Create a data source using ADO.
2. Add the Data Report object to your project.
3. Place Textboxes representing the various fields that you want on the DataReport object.
4. Link the Textboxes to the various fields of the data source.
Dept. of Computer Science, HiSAC, Erode 126
Visual Basic – Unit V
Let us take a look at the DataReport object. This will give us an idea about the approach to be taken for
generating a report. The Data Report Designer is the form on which you design the layout of the report. The
DataReport object is the programmable object that represents the Data Report Designer.
Click on ‘Projects’ in this menu you will see new item ‘Add Data Report’. Select this item to add a Data
Report Designer to your IDE. Please remember that this designer will not be placed on the form. The Data
Report Designer is a separate from by itself. Open the Project Explorer and you will see another item called
DataRepprt1 along the Form1. Also notice that toolbox has acquired a tab called Data Report with its own set of
tools.
The Data Report Designer consists of a number of Sections like the header, footer, and details sections.
Each of these Section objects can be configured at design time or controlled through code at run time. Each
section has a set of properties that can be manipulated. Finally you have the Data Report controls, which are
special control that you can create on the Data Report designer. These tools are placed under a separate tab on
your toolbox.
In the form load event itself you can populate the recordset. But this is not such a good idea. If you are not
going to view / display the report then the recordset is unnecessarily taking up memory. In order to avoid this
add a button to your form. Let the caption be “Display”. In the code window of this CommandButton, enter the
following code.
set adors = [Link](“Select distinctrow Customer_data.customer_name,
Customer_data.address2, orders_data.ordervalue from Customer_data, orders_data where
Customer_data.customer_code = orders_data.customercode”)
The above code segment will populate the Recordset. We now have readily available. The Recordset will have
all the fields from both the tables. Next we have to display the fields that the user is supposed to view.
Working with the Data Report In the details section of the Data Report designer, add three of the RptTextBox
controls. Notice that it is just like adding ordinary textbox controls. Also observe that these textboxes contain a
caption called 'Unbound'. This means that these Rpt'IextBox controls are not bound to any data source or data
field.
Binding the RptTextBox to a data field: Bring up the Properties window of the RptTextBox by pressing F4.
Enter the name of the field that you want to display against the Data Field property.
For our Example, the three RptTextBox controls will display the “Customer Name”, “Customer City” and
“Order Value”. Enter the field’s names as they are in the database. If they are wrongly spelt you will get an
error message. Your Data Report designer will look like the figure in the next page.
Displaying the report We are now ready to display data. We have created the recordset. We have assigned the
fields in the Data Report Designer. We need to link the record source to the Data Report. Then we must call the
Show method of the Data Report. The following lines have to be added to the “Display” command button.
Set [Link] = adors
[Link]
Run the program now. Add headers to report using the RptLabelBox controls so that the report looks
meaningful.
Details like Caption, Page Headers, Footers, etc for each of the reports must be determined. The heading
for the data must also be determined. The data and the source of the data must also be worked out. Depending
upon the number of reports that you may need to display on a form, you have to work out if it is feasible to
create a recordset or a number of recordsets for all the reports. Creating a recordset every time the user asks for
a report may not be a good idea especially in a multi-user environment. At the same time creating a large
number of recordsets and locking up resources will not be the right thing to do.