Visual Basic
Visual Basic
UNIT 1
INTRODUCTION TO VB
Getting Started with VB6, Programming Environment, working with Forms, Developing an
application, Variables, Data types and Modules, procedures and control structures, arrays.
Working with Controls: Creating and using controls, working with control arrays.
After installing the vb6 compiler, the icon will appear on your desktop or in your programs menu.
Click on the icon to launch the VB6 compiler. Visual Basic 6.0 will display the following.
The Integrated Development Environment:
One of the most significant changes in Visual Basic 6.0 is the Integrated Development Environment
(IDE). IDE is a term commonly used in the programming world to describe the
Interface and environment that we use to create our applications.
It is called integrated because we can access virtually all of the development tools that we
need from one screen called an interface. The IDE is also commonly referred to as the design
environment, or the program.
First finalize the project commercial, educational or recreational value. Next, click on the Standard
EXE icon to go into the actual Visual Basic 6 programming environment. The Visual
Basic 6 Integrated Programming Environment. It consists of the toolbox, the form, the project explorer
and the properties window.
The earlier visual basic version IDE was designed as a Single Document Interface (SDI). In a
Single Document Interface, each window is a free-floating window that is contained within a main
window and can move anywhere on the screen as long as Visual Basic is the current application.
But, in Visual Basic 6.0, the IDE is in a Multiple Document Interface (MDI) format. In this
format, the windows associated with the project will stay within a single container known as the
parent. Code and form-based windows will stay within the main container form.
Menu Bar
This Menu Bar displays the commands that are required to build an application.
The main menu items have sub menu items that can be chosen when needed.
The toolbars in the menu bar provide quick access to the commonly used commands and a
button in the toolbar is clicked once to carry out the action represented by it.
Toolbox
The Toolbox contains a set of controls that are used to place on a Form at design time thereby
creating the user interface area.
Additional controls can be included in the toolbox by using the Components menu item on the
Project menu.
Control Description
Pointer Provides a way to move and resize the controls
form
Picture Box Displays icons/bitmaps and metafiles. It
displays text or acts as a visual
container for other controls.
Textbox Used to display message and enter text.
Frame Serves as a visual and functional container for
controls
Command Button Used to carry out the specified action when the
user chooses it.
Checkbox Displays a True/False or Yes/No option.
Option Button Option Button control which is a part of an
option group allows the user to
select only one option even it displays mulitiple
choices.
ListBox Displays a list of items from which a user can
select one.
ComboBox Contains a Textbox and a List Box. This allows
the user to select an ietm from
the dropdown ListBox, or to type in a selection
in the TextBox.
HScrollBar and These controls allow the user to select a value
VScrollBar within the specified range of
Values
Timer Executes the timer events at specified intervals
of time
DriveListBox Displays the valid disk drives and allows the
user to select one of them.
DirListBox Allows the user to select the directories and
paths, which are displayed.
FileListBox Displays a set of files from which a user can
select the desired one.
Shape Used to add shape (rectangle, square or circle)
to a Form
Line Used to draw straight line to the Form
Image Used to display images such as icons, bitmaps and
metafiles. But less
capability than the PictureBox
Data Enables the use to connect to an existing database
and display information
from it.
OLE Used to link or embed an object, display and
manipulate data from other
windows based applications.
Label Displays a text that the user cannot modify or
interact with.
Project Explorer
Docked on the right side of the screen, just under the toolbar, is the Project Explorer window. It
provide a quick reference to the various elements of a project namely form, classes and modules. A
simple project will typically contain one form. It is possible to develop any number of forms for use
in a program, although a program may consist of a single form. In addition to forms, the Project
Explorer window also lists code modules and classes.
Properties Window
A form has properties and any controls placed on it will have properties too.
Object Browser
The Object Browser allows us to browse through the various properties, events and methods
It is accessed by selecting Object Browser from the View menu or pressing the key F2. The
left column of the Object Browser lists the objects and classes that are available in the
projects that are opened and the controls that have been referenced in them.
After an object is picked up from the Classes list, we can see its members (properties,
A property is represented by a small icon that has a hand holding a piece of paper. Methods
are denoted by little green blocks, while events are denoted by yellow lightning bolt icon.
For example, a TextBox accepts properties such as Enabled, Font, MultiLine, Text, Visible,
Width, etc.
Enables property allows the TextBox to be enabled or disabled at run time depending on the
condition set to True or False.
MultiLine property allows the TextBox to accept and display multiple lines at run time.
Text property of the TextBox control sets a particular text in the control.
Width property sets the TextBox to the desired width at design time.
These properties are design-time properties that can be set at the design time by selecting the
Example: The CurrentX and CurrentY properties of a Form cannot be set at the design time.
A method is an action that can be performed on objects. For example, a cat is an object. Its
properties might include long white hair, blue eyes, 3 pounds weight etc. In object-oriented
programming, a method is a connected or built-in procedure, a block of code that can be invoked to
impart some action on a particular object. A method requires an object to provide them with a
context. For example, the word Move has no meaning in Visual Basic, but the statement,
Text1.Move 700, 400 performs a very precise action. The TextBox control has other associated
The Refresh method enforces a complete repaint of the control or a Form. For example,
program.
While in an event driven application, the program statements are executed only when a
particular event calls a specific part of the code that is assigned to the event.
Example: The TextBox control supports various events such as Change, Click, MouseMove and
many more that will be listed in the Properties dropdown list in the code window for the TextBox
control.
The code entered in the Change event fires when there is a change in the contents of the
TextBox
The MouseMove event fires when the mouse is moved over the TextBox
Move : Lets the user moves the Form around with the mouse
Size : Lets the user resizes the control with the mouse
By default, Visual Basic suggests the name of the first Form created when the project started.
The FormName variable is the name of the Form to be loaded or unloaded. Unlike the Show
method which cares of both loading and displaying the Form, the load statement doesn't show the
Form, just call the Form's Show method to display it on the desktop.
The FormName variable is the Form's name, and the optional argument mode determines whether the
Form will be Modal or not. It can have one of the following syntax:
* 0-Modeless (default Normal forms, forms interact with the user and the user allowed to switch to
any other Form of the application. Default the mode is set to modeless.
* 1-Modal Modal Forms takes the total control of the application where user cannot switch to any
other Forms in the application unless the Form is closed.
To hide a Form from within its own code, the following code can be used.
Me.Hide
Forms that are hidden are not unloaded; they remains in the memory and can be displayed instantly
with the Show Method. When a Form is hidden, possible to access its properties and code. Also can
change the settings of its Control Properties or call any Public functions in the Form.
The following is an example illustrates the Show method and Mode statement
Example: Open a new project and save the project. Draw two buttons on the form and name those as
shown above.
Me.Hide
Unload Me
Save the project and run the application. To click on Hide button that the Form is invisible but
the application is still running. But when click on Unload button that the application is terminated.
Developing an application:
Two steps are there,
1.Visual programming step-involves designing an application with various tools that come along
Explicit Declaration
Declaring a variable tells Visual Basic to reserve space in memory. It is not must that a
variable should be declared before using it. Automatically whenever Visual Basic encounters a new
variable, it assigns the default variable type and value. This is called implicit declaration.
Though this type of declaration is easier for the user, to have more control over the variables,
it is advisable to declare them explicitly. The variables are declared with a Dim statement to name
the variable and its type. The As type clause in the Dim statement allows to define the data type or
object type of the variable. This is called explicit declaration.
Syntax: Dim variable [As Type]
For example,Dim strName As String
Dim int Counter As Integer
Using Option Explicit statement
It may be convenient to declare variables implicitly, but it can lead to errors that may not be
recognized at run time. Example a variable by name int count is used implicitly and is assigned to a
value. In the next step, this field is incremented by 1 by the following statement.
Intcount = Intcount + 1
This calculation will result in intcount yielding a value of 1 as intcount would have been
initialized to zero. This is because the intcount variable has been mityped as incont in the right hand
side of the second variable. But Visual Basic does not see this as a mistake and considers it to be new
variable and therefore gives a wrong result. In Visual Basic, to prevent errors of this nature, declare a
variable by adding the following statement to the general declaration section of the Form.
Option Explicit
This forces the user to declare all the variables. The Option Explicit statement checks in the
module for usage of any undeclared variables and reports an error to the user. The user can thus
rectify the error on seeing this error message. The Option Explicit statement can be explicitly placed
in the general declaration section of each module using the following steps.
1. Click Options item in the Tools menu
2. Click the Editor tab in the Options dialog box
3. Check Require Variable Declaration option and then click the OK button
Scope of variables:
A variable is scoped to a procedure-level (local) or module-level variable depending on how it is
declared. The scope of a variable, procedure or object determines which part of the code in our
application are aware of the variable's existence. A variable is declared in general declaration section
of the Form, and hence is available to all the procedures. Local variables are recognized only in the
procedure in which they are declared. They can be declared with Dim and Static keywords. If we
want a variable to be available to all of the procedures within the same module, or to all the
procedures in an application, a variable is declared with broader scope.
Local Variables:
A local variable is one that is declared inside a procedure. This variable is only available to the code
inside the procedure and can be declared using the Dim statements as given below.
Dim sum As Integer
The local variables exist as long as the procedure in which they are declared, is executing.
Once a procedure is executed, the values of its local variables are lost and the memory used by these
variables is freed and can be reclaimed. Variables that are declared with keyword Dim exist only as
long as the procedure is being executed.
Static Variables: Static variables are not reinitialized each time Visual Invokes a procedure and
therefore retains or preserves value even when a procedure ends. To keep track of the number of
times a command button in an application is clicked, a static counter variable has to be declared.
These static variables are also ideal for making controls alternately visible or invisible.
Function RunningTotal ( )
Static Accumulate
Accumulate = Accumulate + num
RunningTotal = Accumulate
End Function
If the variable Accumulate was declared with Dim instead of static, the previously accumulated
values would not be preserved accross calls to the procedure, and the procedure would return the
same value with which it was called. To make all variables in a procedure static, the Static keyword
is placed at the beginning of the procedure heading as given in the below statement.
The first time we click the CommandButton, the Counter starts with its default value of zero.
Visual Basic then adds 1 to it and prints the result.
Module Level Variables: A module level variable is available to all the procedures in the module.
They are declared using the Public or the Private keyword.
Puplic intPermanent As Integer
Private intTemp As Integer
Declaring a variable using the public keyword makes it available throughout the application
even for the other modules. At the module-level there is no difference between Dim and Private, but
is preferred because it makes the code easier to read. Public variables should not be declared within a
procedure. It is in different modules can share the same name and they can be differentiated in code.
Example: If the public integer variable intY is declared in both Form1 and Module1of a project
it can be referred as Form1.intY and Module1.intY.
Public vs Local Variables :
A variable can have the same name and different scope. Example, a public variable named R and
within a procedure we can declare a local variable R. References to the name R within the procedure
would access the local variable and references to R outside the
procedure would access the public variable.
Modules:
Code in Visual Basic is stored in the form of modules. The three kind of modules are Form
Modules, Standard Modules and Class Modules. A simple application may contain a single Form,
and the code resides in that Form module itself. As the application grows, additional Forms are added
and there may be a common code to be executed in several Forms. To avoid the duplication of code,
a separate module containing a procedure is created that implements the common code. This is a
standard Module. Class module (.CLS filename extension) are the foundation of the object oriented
programming in Visual Basic. New objects can be created by writing code in class modules. Each
module can contain:
Declarations : May include constant, type, variable and DLL procedure declarations.
Procedures : A sub function, or property procedure that contain pieces of code that can be executed
as a unit.
Data types in Visual Basic 6
By default Visual Basic variables are of variant data types. The variant data type can store
numeric, date/time or string data. When a variable is declared, a data type is supplied for it that
determines the kind of data they can store. The fundamental data types in Visual Basic including
variant are integer, long, single, double, string, currency, byte and boolean. Visual Basic supports a
vast array of data types. Each data type has limits to the kind of information and the minimum and
maximum values it can hold.
1. Numeric:
2. String : Use to store alphanumeric values. A variable length string can store approximately 4
billion characters
3. Date: Use to store date and time values. A variable declared as date type can store both date and
time values and it can store date values 01/01/0100 up to 12/31/9999
4. Boolean: Boolean data types hold either a true or false value. These are not stored as numeric
values and cannot be used as such. Values are internally stored as -1 (True) and 0 (False) and any
non-zero value is considered as true.
5. Variant: Stores any type of data and is the default Visual Basic data type. In Visual Basic if we
declare a variable without any data type by default the data type is assigned as default.
Logical Operators
applications. Visual Basic programs can be broken into smaller logical components called
Procedures. Procedures are useful for condensing repeated operations such as the frequently used
calculations, text and control manipulation etc. The benefits of using procedures in programming
are:
It is easier to debug a program a program with procedures, which breaks a program into
Procedures used in one program can act as building blocks for other programs with
slight modifications.
Sub Procedures : A sub procedure can be placed in standard, class and form modules. Each time the
procedure is called, the statements between Sub and End Sub are executed. The syntax for a sub
procedure is as follows:
[ statements]
End Sub
arglist is a list of argument names separated by commas. Each argument acts like a variable in the
procedure. There are two types of Sub Procedures namely general procedures and event procedures.
Event Procedures:
An event procedure is a procedure block that contains the control's actual name, an underscore(_),
and the event name. The following syntax represents the event procedure for a
Form_Load event.
....statement block..
End Sub
General Procedures: A general procedure is declared when several event procedures perform the
same actions. It is a good programming practice to write common statements in a separate procedure
The Code window is opened for the module to which the procedure is to be added.
The Add Procedure option is chosen from the Tools menu, which opens an Add Procedure
dialog box as shown in the figure given below.
Under Type, Sub is selected to create a Sub procedure, Function to create a Function
Under Scope, Public is selected to create a procedure that can be invoked outside the module,
or Private to create a procedure that can be invoked only from within the module.
We can also create a new procedure in the current module by typing Sub Procedure Name,
Function Procedure Name, or Property Procedure Name in the Code window. A Function procedure
returns a value and a Sub Procedure does not return a value.
Function Procedures
Functions are like sub procedures, except they return a value to the calling procedure. They
are especially useful for taking one or more pieces of data, called arguments and performing some
tasks with them. Then the functions returns a value that indicates the results of the tasks complete
within the function. The following function procedure calculates the third side or hypotenuse of a
right triangle, where A and B are the other two sides. It takes two arguments A and B (of data type
Double) and finally returns the results.
Declaring arrays
Arrays occupy space in memory. The programmer specifies the array type and the number of
elements required by the array so that the compiler may reserve the appropriate amount of memory.
Arrays may be declared as Public (in a code module), module or local. Module arrays are declared in
the general declarations using keyword Dim or Private. Local arrays are declared in a procedure
using Dim or Static. Array must be declared explicitly with keyword "As".
There are two types of arrays in Visual Basic namely:
Fixed-size array : The size of array always remains the same-size doesn't change during the
program execution.
Dynamic array : The size of the array can be changed at the run time- size changes during the
program execution.
Fixed-sized Arrays: When an upper bound is specified in the declaration, a Fixed-array is created.
The upper limit should always be within the range of long data type.
Declaring a fixed-array : Dim numbers(5) As Integer
In the above illustration, numbers is the name of the array, and the number 6 included in the
parentheses is the upper limit of the array. The above declaration creates an array with 6
elements,with index numbers running from 0 to 5.
If we want to specify the lower limit, then the parentheses should include both the lower and upper
limit along with the To keyword. An example for this is given below.
Dim numbers (1 To 6 ) As Integer
In the above statement, an array of 10 elements is declared but with indexes running from 1 to 6. A
public array can be declared using the keyword Public instead of Dim as shown below.
Public numbers(5) As Integer
Multidimensional Arrays
Arrays can have multiple dimensions. A common use of multidimensional arrays is to represent
tables of values consisting of information arranged in rows and columns.
To identify a particular table element, we must specify two indexes: The first (by convention)
identifies the element's row and the second (by convention) identifies the element's column.
Tables or arrays that require two indexes to identify a particular element are called two
dimensional arrays.
Multidimensional arrays can have more than two dimensions. Visual Basic supports at least 60
array dimensions, but most people will need to use more than two or three dimensional-arrays.
The following statement declares a two-dimensional array 50 by 50 array within a procedure.
Dim AvgMarks ( 50, 50)
It is also possible to define the lower limits for one or both the dimensions as for fixed size arrays.
An
example for this is given here.
Dim Marks ( 101 To 200, 1 To 100)
An example for three dimensional-array with defined lower limits is given below.
Dim Details( 101 To 200, 1 To 100, 1 To 100)
Static and dynamic arrays
Static arrays must include a fixed number of items, and this number must be known at compile time
so that the compiler can set aside the necessary amount of memory. You create a static array using a
Dim statement with a constant argument:
' This is a static array.
Dim Names(100) As String
Visual Basic starts indexing the array with 0. Therefore, the preceding array actually holds 101 items.
Most programs don't use static arrays because programmers rarely know at compile time how many
items you need and also because static arrays can't be resized during execution. Both these issues are
solved by dynamic arrays. Declaring and creating dynamic arrays in two distinct steps.
In general, declaring the array to account for its visibility (for example, at the beginning of a
module if you want to make it visible by all the procedures of the module) using a Dim command
with an empty pair of brackets.
Then you create the array when you actually need it, using a ReDim statement:
Dynamic arrays can be re-created at will, each time with a different number of items. When re-create
a dynamic array, its contents are reset to 0 (or to an empty string) and lose the data it contains. To
resize an array without losing its contents, use the ReDim Preserve command:
When resizing an array, need not change the number of its dimensions nor the type of the
values it contains. Moreover, using ReDim Preserve on a multidimensional array, can resize only its
last dimension:
ReDim Cells(1 To 100, 10) As Integer
...
ReDim Preserve Cells(1 To 100, 20) As Integer ' This works.
ReDim Preserve Cells(1 To 200, 20) As Integer ' This doesn't.
Finally, you can destroy an array using the Erase statement. If the array is dynamic, Visual
Basic releases the memory allocated for its elements (and you can't read or write them any longer); if
the array is static, its elements are set to 0 or to empty strings.
Use the LBound and UBound functions to retrieve the lower and upper indices. If the array
has two or more dimensions, need to pass a second argument to these functions to specify the
dimension you need:
Print LBound(Cells, 1) ' Displays 1, lower index of 1st dimension
Print LBound(Cells) ' Same as above
Print UBound(Cells, 2) ' Displays 20, upper index of 2nd dimension
' Evaluate total number of elements.
NumEls = (UBound(Cells) _ LBound(Cells) + 1) * _
(UBound(Cells, 2) _ LBound(Cells, 2) + 1)
Working with controls in Visual Basic 6
Controls are used to receive user input and display output and has its own set of properties,
methods and events.
Creating and Using Controls
A control is an object that can be drawn on a Form object to enable or enhance user
interaction with an application.
Controls have properties that define aspects their appearance, such as position, size and
colour, and aspects of their behavior, such as their response to the user input.
They can respond to events initiated by the user or set off by the system. For instance, a code
could be written in a CommandButton control's click event procedure that would load a file
or display a result.
In addition to properties and events, methods can also be used to manipulate controls from
code. For instance, the move method can be used with some controls to change their location
and size.
Most of the controls provide choices to users that can be in the form of OptionButton or
CheckBox controls, ListBox entries or ScrollBars to select a value.
Classification of Controls
Visual Basic cojntrols are broadly classified as standard controls, ActiveX controls and
insertable objects. Standard controls such as CommandButton, Label and Frame controls are
contained inside .EXE file and are always included in the ToolBox which cannot be removed.
ActiveX controls exist as separate files with either .VBX or .OCX extension. They include
specialized controls such as;
MSChart control
The Communications control
The Animation control
The ListView control
An ImageList control
The Multimedia control
The Internet Transfer control
The WinSock control
The TreeView control
The SysInfo control
The Picture Clip control
TabIndex property of Controls
Visual Basic uses the TabIndex property to determine the control that would receive the focus
next when a tab key is pressed. Every time a tab key is pressed, Visual Basic looks at the value of the
TabIndex for the control that has focus and then it scans through the controls searching for the next
highest TabIndex number. When there are no more controls with higher TabIndex value, Visual
Basic starts all over again with 0 and looks for the first control with TabIndex of 0 or higher that can
accept keyboard input.
By default, Visual Basic assigns a tab order to control as we draw the controls on the Form, except
for Menu, Timer, Data, Image, Line and Shape controls, which are not included in tab order.At run
time, invisible or disabled controls also cannot receive the focus although a TabIndex value is given.
Setting the TabIndex property of controls is compulsory in development environment.
Using TextBox Control In Visual Basic 6
TextBox controls offer a natural way for users to enter a value in your program. For this
reason, they tend to be the most frequently used controls in the majority of Windows applications.
TextBox controls, which have a great many properties and events, are also among the most complex
intrinsic controls.
Setting properties to a TextBox
Text can be entered into the text box by assigning the necessary string to the text property of
the control.
If the user needs to display multiple lines of text in a TextBox, set the MultiLine property to
True
To customize the scroll bar combination on a TextBox, set the ScrollBars property.
Scroll bars will always appear on the TextBox when it's MultiLine property is set to True and
its ScrollBars property is set to anything except None(0)
If you set the MultilIne property to True, you can set the alignment using the Alignment
property.
The test is left-justified by default. If the MultiLine property is et to False, then setting the Alignment
property has no effect.
Run-Time Properties of a TextBox control
The SelStart property sets or returns the position of the blinking caret (the insertion point
where the text you type appears).
The SelLength property returns the number of characters in the portion of text that has been
highlighted by the user, or it returns 0 if there's no highlighted text.
The SelText property sets or returns the portion of the text that's currently selected, or it
returns an empty string if no text is highlighted.
When you want to append text to a TextBox control, you should use the following code (instead of
using the concatenation operator) to reduce flickering and improve performance:
Text1.SelStart = Len(Text1.Text)
Text1.SelText = StringToBeAdded
One of the typical operations you could find yourself performing with these properties is selecting
the entire contents of a TextBox control. You often do it when the caret enters the field so that the
user can quickly override the existing value with a new one, or start editing it by pressing any arrow
key:
Always set the SelStart property first and then the SelLength or SelText properties. When you assign
a new value to the SelStart property, the other two are automatically reset to 0 and an empty string
respectively, thus overriding your previous settings.
The selected text can be copied to the Clipboard by using SelText:
Clipboard.SelText text, [format]
In the above syntax, text is the text that has to be placed into the Clipboard, and format has three
possible values.
The following Figure summarizes the common TextBox control's properties and methods.
Using a Label Control
Most people use Label controls to provide a descriptive caption and possibly an associated hot
key for other controls, such as TextBox, ListBox, and ComboBox, that don't expose the Caption
property Caption is the default property for Label controls. Be careful to set the Label's TabIndex
property so that it's 1 minus the TabIndex property of the companion control. Other useful properties
are BorderStyle(if you want the Label control to appear inside a 3D border) and Alignment (if you
want to align the caption to the right or center it on the control). In most cases, the alignment depends
on how the Label control relates to its companion control: for example, if the Label control is placed
to the left of its companion field, you might want to set its Alignment property to 1-Right Justify.
The value 2-Center is especially useful for standalone Label controls.
If the caption string is a long one, you might want to set the Label's WordWrap property to true so
that it will extend for multiple lines instead of being truncated by the right border of the control.
Alternatively, you might decide to set the AutoSize property to True and let the control
automatically resize itself to accommodate longer caption strings.
If you want to show a character string somewhere on the form but at the same time you don't want
to obscure underlying objects, set the Back Style property to 0-Transparent.
If you're using the Label control to display data read from elsewhere—for example, a database
field or a text file—you should set its Use Mnemonics property to False.
Frame Controls
Frame controls are similar to Label controls in that they can serve as captions for those controls
that don't have their own.
Moreover, Frame controls can also (and often do) behave as containers and host other controls.
In most cases, you only need to drop a Frame control on a form and set its Caption property. If you
want to create a borderless frame, you can set its BorderStyle property to 0-None.
Controls that are contained in the Frame control are said to be child controls. Moving a control at
design time over a Frame control—or over any other container, for that matter—doesn't
automatically make that control a child of the Frame control.
After you create a Frame control, you can create a child control by selecting the child control's
icon in the Toolbox and drawing a new instance inside the Frame's border.
Alternatively, to make an existing control a child of a Frame control, you must select the control,
press Ctrl+X to cut it to the Clipboard, select the Frame control, and press Ctrl+V to paste the control
inside the Frame
Frame controls, like all container controls, have two interesting features. If you move a Frame
control, all the child controls go with it.
If you make a container control disabled or invisible, all its child controls also become disabled or
invisible. You can exploit these features to quickly change the state of a group of related controls.
]CommandButton Controls in VB6
Using CommandButton controls is trivial. Just draw the control on the form's surface, set its Caption
property to a suitable string (adding an & character to associate a hot key with the control if you so
choose), and finished, at least with user-interface issues. To make the button functional, need to write
code in its Click event procedure, as in this fragment:
Call SaveDataToDisk
Unload Me
End Sub
Two other properties at design time to modify the behavior of a CommandButton control. Set the
Default property to True if it's the default push button for the form (the button that receives a click
when the user presses the Enter key—usually the OK or Save button).
Similarly, set the Cancel property to True if you want to associate the button with the Escape key.
The only relevant CommandButton's run-time property is Value, which sets or returns the state of the
control (True if pressed, False otherwise). Value is also the default property for this type of control.
Command1.Value = True
The CommandButton control supports the usual set of keyboard and mouse events (KeyDown,
KeyPress, KeyUp, MouseDown, MouseMove, MouseUp, but not the DblClick event) and also the
GotFocus and LostFocus events, but you'll rarely have to write code in the corresponding event
procedures.
To set the background colour of the CommandButton, select a colour in the BackColor property.
Font for the CommandButton control can be selected using the Font property.
To enable or disable the buttons set the Enabled property to True or False
To make visible or invisible the buttons at run time, set the Visible property to True or False.
Tooltips can be added to a button by setting a text to the Tooltip property of the CommandButton.
A button click event is handled whenever a command button is clicked. To add a click event
handler, double click the button at design time, which adds a subroutine like the one given below.
..................
End Sub
OptionButton controls are also known as radio buttons because of their shape. It used a group of two
or more because their purpose is to offer a number of mutually exclusive choices. Anytime you click
on a button in the group, it switches to a selected state and all the other controls in the group become
unselected.
Set an OptionButton control's Caption property to a meaningful string, and change its Alignment
property to make the control right aligned. If the control is the one in its group that's in the selected
state, also set its Valueproperty to True. (The OptionButton's Value property is a Boolean value
because only two states are possible.) Value is the default property for this control.
At run time, typically query the control's Value property to learn which button in its group has been
selected. Let's say you have three OptionButton controls, named optWeekly, optMonthly, and
optYearly. You can test which one has been selected by the user as follows:
If optWeekly.Value Then
End If
Strictly, avoid the test for the last OptionButton control in its group because all choices are
supposed to be mutually exclusive. But the approach I just showed you increases the code's
readability. A group of OptionButton controls is often hosted in a Frame control. This is necessary
when there are other groups of OptionButton controls on the form.
Example
Open a new Standard EXE project and the save the Form as Option.frm and save the project as
Option.vbp. Design the Form as per the following specifications table.
The application responds to the following events
The change event of the TextBox reads the value and stores it in a form-level numeric
variable.
The click event of the optDec button returns the decimal equivalent of the value held
currentval.
The following code is entered in the general declarations section of the Form.
The variable is initialized to 0 by default. The change event procedure checks to ascertain the
number system (Octal, Hexadecimal) that is in effect and then reads in the number.
The following Fig lists some of the common ComboBox properties and methods.
Adding items to a List
It is possible to populate the list at design time or run time
Design Time : To add items to a list at design time, click on List property in the property box
and then add the items. Press CTRL+ENTER after adding each item as shown below.
Run Time : The AddItem method is used to add items to a list at run time. The AddItem method
uses the following syntax.
Object.AddItemitem, Index
Theitem argument is a string that represents the text to add to the list
Theindexargument is an integer that indicates where in the list to add the new item. Not giving
the index is not a problem, because by default the index is assigned.
Following is an example to add item to a combo box. The code is typed in the Form_Load event
Combo1.AddItem 1
Combo1.AddItem 2
Combo1.AddItem 3
Combo1.AddItem 4
Combo1.AddItem 5
Combo1.AddItem 6
End Sub
The RemoveItem method is used to remove an item from a list. The syntax for this is given
below.
Object.RemoveItem index
The following code verifies that an item is selected in the list and then removes the selected item
from the list.
Selecting an item from a list box
Use listIndex and List properties. It sets the index number of the currently selected item. The first
item in the list is index number 0. If it is 1 no item is selected.Listcount always one more than the
index number of the last item in the list.NewIndex property returns the index of the last item added
to the list.
List1.addItem “Television”
List1.ListIndex=List1.NewIndex
The Sorted property is set to True to enable a list to appear in alphanumeric order and False to
display the list items in the order which they are added to the list.
A ComboBox combines the features of a TextBox and a ListBox. This enables the user to select
either by typing text into the ComboBox or by selecting an item from the list. There are three types
of ComboBox styles that are represented as shown below.
The Simple Combo box displays an edit area with an attached list box always visible
immediately below the edit area. A simple combo box displays the contents of its list all the
time. The user can select an item from the list or type an item in the edit box portion of the
combo box. A scroll bar is displayed beside the list if there are too many items to be displayed in
the list box area.
The Dropdown Combo box first appears as only an edit area with a down arrow button at the
right. The list portion stays hidden until the user clicks the down-arrow button to drop down the
list portion. The user can either select a value from the list or type a value in the edit area. The
Dropdown list combo box turns the combo box into a Dropdown list box. At run time ,the
control looks like the Dropdown combo box. The user could click the down arrow to view the
list. The difference between Dropdown combo & Dropdown list combo is that the edit area in
the Dropdown list combo is disabled. The user can only select an item and cannot type anything
in the edit area. Anyway this area displays the selected item.
Example
This example is to Add , Remove, Clear the list of items and finally close the application.
Open a new Standard EXE project is opened an named the Form as Listbox.frm and save the
project as Listbox.vbp
'is entered
cmdAdd.Enabled = True
End If
End Sub
lstName.AddItem txtName.Text 'Add the entered the characters to the list box
'text box
End Sub
The click event of the Add button adds the text to the list box that was typed in the Text box.
Then the text box is cleared and the focus is got to the text box. The number of entered values
will is increased according to the number of items added to the listbox.
lstName.Clear
lblDisplay.Caption = lstName.ListCount
End Sub
Unload Me
End Sub
Private Sub cmdRemove_Click()
End If
End Sub
Remove button removes the selected item from the list as soon as you pressed the Remove
button. The number of items is decreased in the listbox and the value is displayed in the label.
The code for the clear button clears the listbox when you press it. And the number of items
shown in the label becomes 0.
The ScrollBar is a commonly used control, which enables the user to select a value by
positioning it at the desired location. It represents a set of values. The Min and Max property
represents the minimum and maximum value. The value property of the ScrollBar represents its
current value, that may be any integer between minimum and maximum values assigned. The
default initial value for those two properties is 1, but you'll probably have to change
LargeChange to a higher value. For example, if you have a scroll bar that lets you browse a
portion of text, SmallChange should be 1 (you scroll one line at a time) and LargeChange should
be set to match the number of visible text lines in the window.
The most important run-time property is Value, which always returns the relative position of the
indicator on the scroll bar. By default, the Min value corresponds to the leftmost or upper end of
the control: There are two key events for scrollbar controls: the Change event fires when you
click on the scroll bar arrows or when you drag the indicator; the Scroll event fires while you
drag the indicator.
Working with control arrays:
Control Arrays in Visual Basic 6
A control array is a group of controls that share the same name type and the same event
procedures. Adding controls with control arrays uses fewer resources than adding multiple
control of same type at design time. A control array can be created only at design time, and at
the very minimum at least one control must belong to it. You create a control array following
one of these three methods:
You create a control and then assign a numeric, non-negative value to its Index property; you
have thus created a control array with just one element.
You create two controls of the same class and assign them an identical Name property. Visual
Basic shows a dialog box warning you that there's already a control with that name and asks
whether you want to create a control array. Click on the Yes button.
You select a control on the form, press Ctrl+C to copy it to the clipboard, and then press
Ctrl+V to paste a new instance of the control, which has the same Name property as the original
one. Visual Basic shows the warning mentioned in the previous bullet.
Control arrays are one of the most interesting features of the Visual Basic environment, and
they add a lot of flexibility to your programs:
Controls that belong to the same control array share the same set of event procedures; this
often
dramatically reduces the amount of code you have to write to respond to a user's actions.
You can dynamically add new elements to a control array at run time; in other words, you can
effectively create new controls that didn't exist at design time.
Elements of control arrays consume fewer resources than regular controls and tend to produce
smaller executables. Besides, Visual Basic forms can host up to 256 different control names, but
a control array counts as one against this number. In other words, control arrays let you
effectively overcome this limit.
Creating Controls at Run Time
Control arrays can be created at run time using the statements
Load object (Index %)
Unload object (Index %)
Where object is the name of the control to add or delete from the control array. Index % is the
value of the index in the array. The control array to be added must be an element of the existing
array. created at design time with an index value of 0. When a new element of a control array is
loaded, most of the property settings are copied from the lowest existing element in the array.
Following example illustrates the use of the control array.
* Open a Standard EXE project and save the Form as Calculator.frm and save the Project as
Calculater.vbp.
* Design the form as shown below.
The following variables are declared inside the general declaration
Dim Current As Double
Dim Previous As Double
Dim Choice As String
Dim Result As Double
The following code is entered in the cmd_Click( ) (Control Array) event procedure
Private Sub cmd_Click(Index As Integer)
txtDisplay.Text = txtDisplay.Text & cmd(Index).Caption
'&is the concatenation operator
Current = Val(txtDisplay.Text)
End Sub
The following code is entered in the cmdAC_Click ( ) event procedure
Private Sub cmdAC_Click()
Current = Previous = 0
txtDisplay.Text = ""
End Sub
The below code is entered in the cmdNeg_Click( ) procedure
Private Sub cmdNeg_Click()
Current = -Current
txtDisplay.Text = Current
End Sub
The following code is entered in the click events of the cmdPlus, cmdMinus, cmdMultiply,
cmdDevide controls respectively.
Private Sub cmdDevide_Click()
txtDisplay.Text = ""
Previous = Current
Current = 0
Choice = "/"
End Sub
Private Sub cmdMinus_Click()
txtDisplay.Text = ""
Previous = Current
Current = 0
Choice = "-"
End Sub
Private Sub cmdMultiply_Click()
txtDisplay.Text = ""
Previous = Current
Current = 0
Choice = "*"
End Sub
Private Sub cmdPlus_Click()
txtDisplay.Text = ""
Previous = Current
Current = 0
Choice = "+"
End Sub
To print the result on the text box, the following code is entered in the cmdEqual_Click ( ) event
procedure.
Private Sub cmdEqual_Click()
Select Case Choice
Case "+"
Result = Previous + Current
txtDisplay.Text = Result
Case "-"
Result = Previous - Current
txtDisplay.Text = Result
Case "*"
Result = Previous * Current
txtDisplay.Text = Result
Case "/"
Result = Previous / Current
txtDisplay.Text = Result
End Select
Current = Result
End Sub
UNIT 2
MENUS IN VB
Menus, Mouse events and Dialog boxes: Mouse events, Dialog boxes, MDI and
Flex grid: MDI, Using the Flex grid control.
Introduction:
Menu Interface:
It offers a convenient and consistent way to group commands and an easy for users to access
them. Visual Basic provides an easy way to create menus with the modal Menu Editor dialog.
Basically, each menu item has a Caption property (possibly with an embedded & character to
create an access key) and a Name. Each item also exposes three Boolean properties, Enabled,
Visible, and Checked, which can be set both at design time and at run time. At design time, you
can assign the menu item a shortcut key so that your end users don't have to go through the menu
system each time they want to execute a frequent command.
An expanded Menu Editor window.
One of the most annoying defects of the Menu Editor tool is that it doesn't permit you to reuse
the menus you have already written in other applications. The programmer can create menu
control arrays. The Index TextBox specifies the menu's index in the control array.The Menu
Editor dialog also provides several CheckBoxes to control the appearance of the Menu.
Checked: This is unchecked by default and allows the programmer the option of creating a
checked menu item( a menu item that act as a toggle and displays a check mark when selected.
The following is a Check Menu items.
Enabled : specifies whether a menu is disabled or not. If you see a disabled command in a menu
that means that feature is not available. The Visible checkbox specifies whether the menu is
visible or not. To add commands to the Form's menu bar, enter a caption and a name for each
command. As soon as you start typing the command's caption, it also appears in a new line in the
list at the bottom of the Menu Editor window. To add more commands click Enter and type the
Caption and the Name.
Creating Menus
Open a new Project and save the form as menu.frm and save the project as menu.vbp.
Choose Tools ››› Menu Editor and type the menu items as shown below.
Run the application by pressing F5. You can see that you can select a menu.
Application Standardization includes the structure of your toolbars, menus, and overall look and
feel of your applications. All Windows applications look similar, and yours should be designed
to enable the users to learn the application quickly. For example: Most Windows applications
have a File menu dealing with file-oriented tasks. Imagine how difficult it would be for a new
user to figure out that you have put your printing functionality under a menu called, for example,
Technical Tasks -
Creating a Menu
1. Click the MenuEditor component at the bottom of the screen. This will allow you to start
2. Click File, then underneath File where it displays text, as shown in Figure 1, type Open.
3. Repeat the steps to enter the Save, Recent, and Exit items to the File menu.
4. Add a menu item 'Edit' next to File and Add Cut, Copy, and Paste underneath it.
Now that you have the main menu sorted, let's take it a step further and add a submenu to the
Open
2. To the right of the Open menu item, you should see the 'Type Here' section.
3. Enter Text.
Alt key shortcut enables you to press the Alt key and then the underlined letter to display the
menu. For example: If you press Alt + F, it should open the File menu. To make a letter in the
menu display underlined and act as an Alt key shortcut, follow these steps:
3. Add an ampersand in front of the desired letter to be used as a shortcut, added an ampersand
in front of the O in Open.
Shortcut keys are usually a combination of Ctrl and a letter. For example, Ctrl + C is the
keyboard shortcut for Copy and Ctrl + V is the Keyboard shortcut for Paste. To add a keyboard
shortcut key to a menu item, follow these steps:
To add a small icon next to the Menu Item, follow these easy steps:
Once you click on the button, the Select Resource box will appear. Here, you can select from
already added icons inside your project, or add new items to your project's resources.
1. Click the Menu Item that you want to separate from other menu items.
2. When the 'Type Here' text appears, look closely. There is a small drop-down arrow next to it,
as shown in Figure 2.
Opening Files
Add the following Namespace and code to make use of the OpenFileDialog to open a file. The
code is slightly different for the Text and Other file types (according to the menus):
Imports System.IO
Private Sub TextToolStripMenuItem_Click(sender As Object, _
e As EventArgs) Handles TextToolStripMenuItem.Click
OpenFileDialog1.Filter = "*.txt|*.txt"
If OpenFileDialog1.ShowDialog = DialogResult.OK Then
OpenFile(OpenFileDialog1.FileName
Saving a File
SaveFileDialog1.Filter = "TXT Files (*.txt*)|*.txt"
. If SaveFileDialog1.ShowDialog = _
Windows.Forms.DialogResult.OK Then
My.Computer.FileSystem.WriteAllText _
(SaveFileDialog1.FileName, TextBox1.Text, True)
End Sub
frmDraw.CurrentX = X
frmDraw.CurrentY = Y
End Sub
If Button = 1 Then
End If
End Sub
Button value 1 indicates that the left mouse button is clicked. The code written in the
MouseDown event changes the CurrentX and CurrentY to the coordinates where the mouse
button was just clicked.
Run the application. You can notice that when the mouse is clicked and moved in the Form a
line is drawn corresponding to the mouse movement. Following figure illustrates the combined
action of
The program uses two graphics related Visual Basic concepts, the Line method and the CurrentX
and CurrentY properties. Line method is preferred to draw a line in a Form. The following
statement draws a line from the coordinates X = 2500, Y = 2000, X = 5000, Y = 5500 Line
(2500, 2000) - (5000, 5500) The CurrentX and CurrentY properties are not visible in the
properties window of the Form because it cannot be set at the design time. After using the Line
method to draw a line in a Form, Visual Basic automatically assigns the coordinate of the line's
end point to the CurrentX and CurrentY properties of the Form on which the line is drawn.
MouseMove application
Visual Basic does not generate a MouseMove event for every pixel the mouse moves over and a
limited number of mouse messages are generated per second by the operating environment. The
following application illustrates how often the Form_MouseMove ( ) event is executed. Open a
new standard EXE project and save the form as MouseMove.frm and save the Project as
MouseMOve.vbp. Place a CommandButton control and name the caption as Clear and set the
name as cmdClear.
frmMouseMove.Cls
End Sub
End Sub
The above procedure simply draws small circles at the mouse's current location using the
Circle method. The parameter x, y represent the centre of the circle, and the second parameter
A dialog box is simply a form in a program that contains input controls designed to receive
information. To make your programming faster, Visual Basic includes an ActiveX control,
named CommonDialog.
4. Place a check mark next to Microsoft Common Dialog Control, and then click OK.
2. When the common dialog object appears on your form, drag it to an out -of-the-way location.
This table lists the name and purpose of the six standard dialog boxes that the common dialog
object provides and the methods you use to display them:
Common Dialog Object event Procedures
The following code window shows an event procedure named mnuOpenItem_Click. You can
use this event procedure to display an Open dialog box when the user clicks the Open command
on the File menu. The event procedure assumes that you have already created a File menu
containing Open and Close commands and that you want to open Windows metafiles (.wmf).
CommonDialog1.ShowOpen
Image1.Picture = LoadPicture(CommonDialog1.FileName)
mnuCloseItem.Enabled = True
End Sub
If you need to update the color of a user interface element while your program runs, you can
prompt the user to pick a new color with the Color dialog box displayed by using the Common
Dialog object. The color selections provided by the Color dialog box are controlled by the Flags
property, and the Color dialog box is displayed with the ShowColor method. The event
procedure assumes that you have already created a menu command named TextColor with the
Menu Editor. See the code given below
CommonDialog1.Flags = &H1&
CommonDialog1.ShowColor
Label1.ForeColor = CommonDialog1.Color
End Sub
EXERCISE: Creating a File Menu and Common Dialog Object Step by Step
In this exercise, you use the Menu Editor to create a File menu with Open, Close , and Exit
commands for your program. You also assign access keys and shortcut keys to the commands,
so you can run them from the keyboard.
2. On the toolbar, click Menu Editor to open the Menu Editor dialog box.
4. In the Name text box, type mnuFile, and then click Next. By placing the & character before
the letter F, you specify F as the menu access key.
3. To indent the selected (highlighted) command, click the right arrow button.
4. In the Shortcut drop-down list, click CTRL+O for a shortcut key, and then click Next.
7. In the Shortcut drop-down list, click CTRL+C for a shortcut key, and then click Next.
10. In the Shortcut drop-down list, click CTRL+X for a shortcut key, and then click OK.
2. Save your form and project to disk under the name “Picture”. Visual Basic will prompt you
for two
file names — one for your form file (Picture.frm), and one for your project file (Picture.vbp).
1. Verify that the CommonDialog control is in your project toolbox. If it isn't, add it now by
using the
2. To add a common dialog object to your form, double-click the CommonDialog control in the
toolbox, and then drag the object to the lower right-hand side of the form.
1. Click the Image control and create a large image object in the middle of your form. When you
run
your program, the image object displays picture files with *.jpg extension on a form.
2. On the form, click Image1. To restore the Properties window to full size, double-click the
If you cannot see the Properties window, click Properties on the toolbar to display it.
When you run your program, Stretch makes the metafile fill the entire image object.
4. On the toolbar, click Save Project to save these changes to your program.
1. In the Project window, click View Code , click the Code window Object drop-down list box,
and
CommonDialog1.ShowOpen
Image1.Picture = LoadPicture(CommonDialog1.Filename)
mnuCloseItem.Enabled = True
3. In the Object drop-down list box, click mnuCloseItem, and then type the following code:
Image1.Picture = LoadPicture("")
mnuCloseItem.Enabled = False
4. In the Object drop-down list box, click mnuExitItem, and then type End in the event
procedure.
Visual Basic loads the program and the form with its File menu.
3. When the Open dialog box appears, load a picture file from your computer.
The picture selected should appear correctly sized in your image object.
4. From the File menu, click Close.
Your program should clear the picture file and turn off the Close command.
5. Try using the access keys and the shortcut keys to run the File menu commands. When you’re
The Multiple Document Interface (MDI) was designed to simplify the exchange of information
among documents, all under the same roof. With the main application, you can maintain
multiple open windows, but not multiple copies of the application. Data exchange is easier when
you can view and compare many documents simultaneously.
An MDI application must have at least two Form, the parent Form and one or more child Forms.
Each of these Forms has certain properties. There can be many child forms contained within the
parent Form, but there can be only one parent Form. The parent Form may not contain any
controls. While the parent Form is open in design mode, the icons on the ToolBox are not
displayed, but you can't place any controls on the Form. The parent Form can, and usually has its
own menu.
1. Start a new project and then choose Project >>> Add MDI Form to add the parent Form.
4. Make this Form as child of MDI Form by setting the MDI Child property of the SDI Form to
Visual Basic automatically associates this new Form with the parent Form. This child Form can't
exist outside the parent Form; in the words, it can only be opened within the parent Form.
The MDI Form usually has a menu with two commands to load a new child Form and to quit
the application. The child Form can have any number of commands in its menu, according to the
application. When the child Form is loaded, the child Form's menu replaces the original menu on
the
MDI Form
* Open a new Project and name the Form as Menu.frm and save the Project as Menu.vbp
At design time double click on MDI Open and add the following code in the click event of the
open
menu.
Form1.Show
And so double click on MDI Exit and add the following code in the click event
End
Double click on Child Close and enter the following code in the click event
Unload Me
Before run the application in the project properties set MDI Form as the start-up Form. Save
And as soon as you click MDI Open you can notice that the main menu of the MDI Form is
replaced with the Menu of the Child Form. The reason for this behavior should be obvious. The
operation available through the MDI Form are quite different from the operations of the child
window. Moreover, each child Form shouldn't have it's own menu.
Using the FlexGrid control
display, filter, edit, validate and update your data. For example, such utilities could include:
Most of the other grid objects are specifically designed for data binding, whereas the
FlexGrid has many collections of properties, methods and events that lend themselves to
One of the most powerful applications of the FlexGrid is in managing data from
database tables in an unbound state. That is, to populate & edit the FlexGrid and write the
contents back to the database in code. This may seem a pointless exercise as objects such
Microsoft's Data Bound Grid Control are written specifically for this purpose, except these
grids simply display the contents of a recordset, record by record, field by field. Whereas the
FlexGid can populate the grid in any manner, examples of which are:
3. changing the colour of the cell background or text in individual or multiple cells,
5. validating entered data e.g., numeric values, positive values, permitted date ranges etc.
That said, most of the functionality found in these third party grids can be accessed
with FlexGrids .
To use the FlexGrid in your application, right click the Toolbox or select the Project menu and
choose 'Components'.
Select Microsoft FlexGrid Control and copy the control onto your form from the Toolbox. The
default FlexGrid will appear on the form.
There are a few simple formatting tips to improve to appearance of the FlexGrid:
First of all, it's good practice to determine the initial number of grid rows and columns using
the Row and Col properties respectively. Then set the number of fixed rows and columns with
the FixedRow and FixedCol properties respectively.
To ensure the columns are the correct width to fit inside to FlexGrid, first set a variable to the
width of the FlexGrid, allowing for a vertical Scrollbar width. Then use this variable to resize to
individual column widths, by dividing it by the number of columns.
The height of individual rows can be changed to accommodate multi-line headings. This is
done by simply multiplying the appropriate row height by a scaling factor, in this case two, to
double the height.
When increasing the size of a row height, to make sure text uses the extra available space, use
the WordWrap property the ensure text continues on the the next cell line.
Regarding writing text to the grid there are two main methods. The first one is using the
Additem method, this writes text to an entire row in one action and is therefore useful for adding
headings. The vbTab constant is used to distinguish adjacent cells.
The second method to populate grid cells with text is to directly address individual cells and
using the TextMatrix or Text property and set the cell's text.
With MSFlexGrid
.Cols = 4
.FixedCols = 1
.Rows = 0
"Heading Text Two" & vbTab & "Heading Text Three" & _
.Rows = 12
.FixedRows = 1
.WordWrap = True
.RowHeight(0) = .RowHeight(0) * 2
.ColWidth(0) = lngWidth / 4
.ColWidth(1) = lngWidth / 4
.ColWidth(2) = lngWidth / 4
.ColWidth(3) = lngWidth / 4
Next intLoopCount
End With
The ability to change the individual cell background colour and cell font colour is useful for
highlighting particular data states, e.g. values exceeding a specified ceiling, negative values,
cells where data cannot be entered etc. To set the background colour of a cell, first reference the
cell by setting the Row and Col properties to the appropriate cell, then use the CellBackColor
property to set its colour. Similarly use the CellForeColor property to change the colour of the
text displayed in a cell. Examples of available colours are found in the FlexGrid's Properties
Window under any of the colour properties, especially the palette tab as this displays a wider
range of colours. To set a range of cells to a selected colour each cell must be referenced in turn,
unless all the cells in the grid are to have their colour set to the same colour in which case the
BackColor and ForeColor property can be used which sets the entire grid's colour.
UNIT 3
ODBC AND DATA ACCESS OBJECTS
ODBC and Data Access Objects: Data Access Options, ODBC, Remote data objects, ActiveX
EXE and ActiveX DLL: Introduction, Creating an ActiveX EXE Component, Creating
ActiveX DLL Component.
Introduction
Data Access Options
Visual Basic provides variety of options when it comes to accessing the data stored in the
database.
Find all options below:
(i) Data Access Objects (DAO):It communicates with the Microsoft access and other ODBC
compliant data sources through the JET engine.
(ii) ODBC Direct :It allows accessing ODBC data sources through the RDO (Remote Data
Objects) and DAO objects bypassing the JET database engine.
(iii) Data Control:It binds data-aware controls to Microsoft access or other ODBC data sources.
(iv) Remote Data Objects (RDO):It provides a frame work for using code to create and
manipulate components of a remote ODBC database system.
(v) Remote Database Control:It binds to controls to an ODBC remote database.
(vi) Open Database Connectivity(ODBC):This is an API call interface to the ODBC libraries
and drivers to provide data access to Oracle and other databases that provide an ODBC driver.
(vii)Visual Basic Library for SQL Server(VBSQL): It is an implementation of the DB library
API and it provides access to SQL Server through a VB application.
(viii) Active Data Objects(ADO):It is a programming model designed to provide a common
bridge between different databases, file systems and e-mail servers.
Data access objects
A Data Access Object is a collection of object classes that model the structure of a Relational
Database System. They provide properties and methods that allow the user to accomplish all the
operations like creating a database, defining tables, navigating and querying a database. Visual
Basic supports data access objects such as DB Engine, Workspace, Database, TableDef, Field,
Index and Record set objects.
The following figure represents the Data Access Objects Hierarchy:
DB Engine: Top level database object and corresponds to the Jet database engine used to set
database engine system parameters and default workspace.
Table Def: It corresponds to a stored table definition. It represents the definition of a table in the
current database or an attached table in the external database.
Recordset: This object corresponds to a cursored view into a database table. It stores rows of
data in buffer and points to one row of data at a time called current record.
Index Object: It is a stored index associated with Table def or table type Recordset object.
Parameter Object : It represents a parameter associated with a Query Def object created from a
parameter query.
Relation : This object represents a relationship between files in tables or queries. The DBEngine
enforces certain update and delete conditions to maintain referential integrity.
Property Object: It represents a built-in or user defined characteristic of a data access object.
Document Object : It includes information about one instance of a type of object.
Container Object : It holds information describing the objects that are grouped into that
container.
To work with data access objects, reference has to be set to the appropriate DAO library. The
two
Click on OK.
Opening a Database
To open an existing database, the openDatabase method of the Workspace Object is used.
Set db=OpenDatabase(“employee_details”)
Variable db represents the Database object employee_details database. Code to use the database
is
Set db = OpenDatabase(“employee_details”,True)
Set db=OpenDatabase(“employee_details”,False,True)
RecordSet: A recordset is an object that contains a set of records from the database. There are
five major types of Recordset objects.
TableTypeRecordset: Fastest type of Recordsets representing a single table used to add, change
or delete records.
Snapshot Type Recordset:Snapshot can refer to any table, attached table or query. It cannot be
updated and does not reflect any changes made by users.
Dynamic Type Recordset:It represents a query result set from one or more table. We can add,
change or delete records from row-returning query. It is only available in ODBC Direct
Workspaces.
Forward Only Type Recordset: This is identical to snapshot recordset except that we can only
scroll forward through its records.
Example: The following code creates a read only Recordset for the table employee
Dim rs as Recordset
Navigating a Recordset:
The EOF(End of File) property is True when the user moves beyond the last record in the
recordset.
The BOF(Beginning of File) property is True when the user has moved to a position before the
first record in the recordset.
Update Method ---> Used to save the necessary changes made to the record.
Delete Method ---> used to delete an existing record in the dynaset or table type recordset.
Finding Methods:
Find Next ---> Finds next record satisfying the specified criteria.
Query Def object contains information about a stored SQL Query Def Objects runs faster than
SQL
Open Recordset Method ---> Used to retrieve data from the tables.
Parameter Query ---> Created using the parameters collection of a QueryDef object.
TableDef Data Object :It contains detailed definition about each data table in the database.The
following five methods are available to use with this object:
OpenRecordset ---> Used to open a table – Dynaset or Snapshot Recordset from the
TableDef object.
Refresh Link ---> To update and refresh any attached table links for the TableDef object.
Modifying and Deleting Existing Tables:New fields can be added or existing fields can be
deleted using the Append or Delete methods respectively on the TableDef object.
Open database connectivity (odbc) is a Windows technology that lets a database client
application connect to an external database. To use ODBC client machine should be configured
with ODBC driver. The destination of the database, login id and password should also be
configured. This is called a Data Source. It is possible to access heterogeneous data from client.
A Driver manager
Create a new data source using the ODBC driver for Oracle
Select the Add button to add a new ODBC data source. Select the ODBC driver for Oracle
from the
Double click on the Oracle ODBC driver. The Oracle DSN configuration dialog box is
displayed. This screen gathers login and connection information.
Enter the Data Source Name as XYZ company in the Data Source Name box. Enter the
description as xyz company database in the Description box. Provide the user name as user1 and
the server name as server1.
Click the Next button to continue and display the screen that allows us to choose more options
The properties and methods of DAO can be used in conjunction with the ODBC type database.
OpenDatabase – This method creates a connection between the application and the ODBC
database and assigns it to a database type object.
Syntax:
Dim db as Database
Example : To view the details of all the employees in a company named XYZ company
Add a new Form to the project and set its caption as Emp Details.
Add controls -- six label controls, six textboxes and nine command buttons to the form.
Dim rsAsRecordset
DSN=XYZCompany)
Txt_empno.Text=rs.Fields(“Emp_no”)
Txt_name.Text=rs.Fields(“Emp_name”)
Txt_sal.Text=rs.Fields(“Sal”)
Txt_date.Text=rs.Fields(“Joindate”)
Txt_dept.Text=rs.Fields(“Dept_no”)
Txt_desig.Text=rs.Fields(“Desig”)
End Sub
To move to the First, Last,Previous and Next records , the code has to be attached in the Click
event of the
Command buttons cmdFirst, cmdLast, cmdPrev and cmdNext.
rs.MoveFirst
MoveFields
End Sub
rs.MoveLast
MoveFields
End Sub
rs.MovePrevious
If rs.BOF Then
rs.MoveFirst
End If
MoveFields
End Sub
rs.MoveNext
If rs.EOF Then
rs.MoveLast
End If
MoveFields
End Sub
To add a new record the following code is added in the click event of cmdAdd command button
Txt_empno.Text=””
Txt_name.Text=””
Txt_sal.Text=””
Txt_date.Text=””
Txt_dept.Text=””
Txt_desig.Text=””
rs.AddNew
End Sub
To save the changes after entering the details the following code is added in the click event of
cmdSave
command button.
If rs.EditMode=dbEditAdd Then
rs(“Emp_no”)=Txt_empno.Text
rs(“Emp_name”)=Txt_name.Text
rs(“sal”)=Txt_sal.Text
rs(“Joinmdate”)=Txt_date.Text
rs(“Dept_no”)=Txt_dept.Text
rs(“Desig”)=Txt_desig.Text
End If
rs.Update
End Sub
To modify or change any fields in a record add the following code in the click event of
cmdModify command
button
If rs.EditMode=dbEditNone Then
rs.Edit
End If
End Sub
rs.MoveNext
If rs.EOF Then
rs.MoveLast
End If
MoveFields
End Sub
Create a Sub procedure called MoveFields as below to assign the values of the Recordset to the
text property
of the textboxes.
Txt_empno=rs(“Emp_no”)
Txt_name=rs(“Emp_name”)
Txt_sal=rs(“sal”)
Txt_date=rs(“Hiredate”)
Txt_dept=rs(“Dept_no”)
Txt_Desig=rs(“Desig”)
End Sub
A particular record from a table can also be viewed using Find methods. FindFirst method finds
the first record satisfying the specified criteria, searching forward from the beginning of the
Recordset. FindLast method finds the last record satisfying the specified criteria, searching
backward from the end of the Recordset. FindPrevious method finds the previous record
satisfying the specified criteria, searching backward from the current record. FindNext method
finds the first record satisfying the specified criteria, searching forward from the current record.
Example:
End Sub
Dim a As String
a=Text1.Text
If MySet.NoMatch Then
Else
MySet.Edit
Text1.Text=MySet(0)
Text2.Text=MySet(1)
Text3.Text=MySet(2)
Text4.Text=MySet(3)
Text5.Text=MySet(4)
End If
End Sub
A field can be added to an existing table of a database at run time by appending a field to an
existing collection
of fields.
Example:
Dim newTdAsTableDef
newTd.Fields.AppendnewFld
myDb.Close
Dim td AsTableDef
“ODBC;UID=USER1;PWD=SSI;DSN=XYZCompany)
Set td=db.TableDefs(“emp”)
Set ind=td.CreateIndex(“NameIndex”)
ind.Fields.Appendtd.CreateField(“emp_name”)
td.Indexes.Appendind
End Sub
Dim td AsTableDef
“ODBC;UID=USER1;PWD=SSI;DSN=XYZCompany)
Set td=db.TableDefs(“emp”)
Td.Indexes.Delete “NameIndex”
MsgBox “Index Deleted”
End Sub
db.TableDefs(“Emp”).Indexes.Delete “empno_index”
Visual Basic supports three transaction methods such as BeginTrans, CommitTrans and
Rollback. They are:
CommitTrans --->Method that commits all changes till the most recent invoking of the
BeginTrans method
Rollback --->This method cancel all changes till the most recent invoking of the BeginTrans
method.
Example:Function changeDeptno()
“ODBC;UID=USER1;PWD=SSI;DSN=XYZCompany)
Set rs = db.OpenRecordset(“Emp”,dbOpenDynaset)
myWs.BeginTrans
Do Until rs.EOF
If rs(“dept_no”) =9 Then
rs.Edit
rs(“dept_no”) = 10 Then
rs.Update
End If
rs.MoveNext
Loop
Then
myWs.CommitTrans
Else
myWs.Rollback
End If
rs.Close
End Function
A Data control is used to create applications that display, edit and update information from
numerous
types of existing databases. In addition, data control allows the user to access and manipulate
external Open
Database Connectivity(ODBC) databases such as Microsoft SQL Server and Oracle.The Data
Control
implements data access by using the Microsoft Jet database engine. It can be added the form and
perform the
Attach data fields to bound controls, where values can be displayed and changed
Add new records or update a database with the data displayed on the bound controls.
The dbgrid control is a spreadsheet-like bound control that displays a series of rows and columns
representing rows and fields from a recordset object. the dbgrid control’s datasource property
can be set to a data control so that the control is automatically filled and its column headers are
set automatically from a data control’s recordset object. it can hold text or picture values but not
linked or embedded objects. accessing client server data source odbcdirect can be used to
access client server data by enabling without loading jet database engine. to set up a vb
application that tests the oracle data source name, the following steps have to be followed. create
a standard exe project.
from the project components menu, add a reference to the microsoft data bound grid control.
the dbgrid control appears in the project’s toolbox. add an instance of the dbgrid control and a
standard
odbc;uid=user1;pwd=ssi;dsn=xyzcompany
in the data control’s recordsource property, enter the following sql string.
select * from emp set the dbgrid control’s datasource property to data1
To add new employee details attach the following code in the click event of Add command button:
Data1.Recordset. AddNew
End Sub
To delete an employee from the database include the following code in the click event of delete
command:
Data1,Recordset.Delete
Data1,Recordset.MoveNext
If Data1.Recordset.EOF Then
Data1,Recordset.MoveLast
End If
End Sub
To save the changes made to the record, add the following code in the click event of update
command :
Data1.UpdateRecord
End Sub
To cancel the changes made to the data , the following code is attached to the cancel command :
Data1.UpdateControls
End Sub
The Remote Data Control is another way for accessing remote data in Visual Basic Application.
From the list of Components, select Microsoft Remote Data Control 2.0. Also add a reference to
the
Click Ok. The Remote Data and Databound Grid controls appear in the Visual Basic toolbox.
Click the Remote Data Control from the toolbox and add it to the form.
Change the Remote Data Control’s UserName property to the user’s choice.
The Remote Data Control’s Password property is changed as per user’s choice.
Set the Remote Data Control’s SQL property to select * from emp.
In the DataSourceName property of the Remote Data Control, select the DSN namely XYZ
company
for the SQL Server database.
Set the DBGrid control’s DataSource property to MSRDC1 which is the name of the Remote
Data
Control.
Press F5 to run the application. The application retrieves the contents of the table emp and displays
it in the
data grid.
The basic idea behind Remote Data Objects is to give the user an object-oriented, implementation –
independent way of acquiring access to client server data. The following are the steps to get started
with
Select References from Visual Basic’s Project Menu. The References dialog appears.
Click Ok. Remote Data Objects will be available now in the application.
The RDO consists of objects and collections that form a framework for manipulating the
components
of a remote ODBC database system. The relationships among objects and collections represent the
rdoEngine: object is the top-level object used to access all remote data and it handles all the
requests. rdoEngine creates one or more rdoEnvironment object which contains information about
current environment for data connections.
rdoEnvironment: objects can create rdoConnectionobjects.This object contains the details needed
to establish a connection between an application and the remote data source. Each rdoConnection
can create one or more rdoResultset objects. This object contains a direct reference to all the rows
and columns in the dataset and it creates a collection of records after a connection is made to the
remote data source. The complete hierarchy of Remote Data Objects is shown in the following
figure.
\
The rdoTable object has information about each column in the base table that exists on the
remote
data source.
The rdoColumn object has the information about each column in the rdoTable or rdoResultset
object.
The rdoQuery object provides a method for creating and excuting defined queries or views on
the
remote data source. rdoQuery objects are accessed through the rdoQueries collection object.
The rdoParameter object manages the parameters that are passed during the processing of
queries.
More than one rdoParameter object can be defined for each rdoQuery object.
After the connection is established and the database is opened, the user can execute SQL
statements
The results are returned in a rdoResultset object. With the rdoResultset object’s methods and
properties, the user can access the records, edit them and save them.
Establishing a connection
Syntax to establish a connection is:
connect ---> String expression used to pass arguments to the ODBC driver manager for opening the
database.
Options ---> Variant or Constant that determines how the operation is carried out.
OpenResultSet method of the Connection object is used to run queries against the database.
Syntax
name ---> string specifying the source for new rdoResultSet object. It can specify the name of a
type ---> specifies the type of cursor and can have anyone of the following values:
locktype ---> determines the way in which other users can access the data in the resultset.and it can
rdConcurReadOnly --->used when the user opens the resultsets that will not be updated.
rdConcurLock ---> Locks the page that contains the record and frees it only after the application
Records can be inserted, existing records can be modified and unwanted records can be deleted
using
RDO objects.
Example: Create a new project called employee details and add the controls as in the figure shown:
Dim envAsrdoEnvironment
Dim cnAsrdoConnection
Dim rsAsrdoResultset
Select the Data Source Name. Use OpenConnection method in the Form_Load event to prompt the
user to
Set env=rdoEnvironments(0)
Env.CursorDriver=rdUseOdbc
Call loademp
End Sub
The employee detail sis retrieved using the following sub routine loademp()
Dim s As String
If rs.EOF<>True Then
Call Displayrecord
Else
End If
To scroll through the records add the following code in the click event of the cmdFirst,
rs.MoveFirst
Call Displayrecord
End Sub
If rs.EOF<>True Then
rs.MoveNext
If rs.EOF=True Then
rs.MoveLast
Else
Call Displayrecord
End If
End If
End Sub
If rs.BOF<>True Then
rs.MovePrevious
If rs.BOF=True Then
rs.MoveFirst
Else
Call Displayrecord
End If
End If
End Sub
rs.MoveLast
Call Displayrecord
End Sub
Add the following code in the add command click event and to store the details in the database add
the coding
Call ClearRecord
rs.AddNew
End Sub
rs(“emp_no”) = txtempno.Text
rs(“emp_name”) = txtempname.Text
rs(“sal”) = txtsal.Text
rs(“Joindate”) = txtdate.Text
rs(“dept_no”) = txtdept.Text
rs.Update
End Sub
To delete a record add the following rcode in the click event of delete command button as follows:
rs.Delete
Call Displayrecord
End Sub
Add the following routines in the form for displaying and retrieving.
txtempno.Text=rs(“emp_no”)
txtname.Text=rs(“emp_name”)
txtsal.Text=rs(“sal”)
txtdate.Text=rs(“Joindate”)
txtdept.Text=rs(“dept_no”)
End Sub
txtempno.Text=””
txtname.Text=””
txtsal.Text=””
txtdate.Text=””
Dim envAsrdoEnvironment
Dim rsAsrdoResultset.
Add the following code in the Form_Load event for prompting the user to specify the data source
name.
WindowState=2
Set env=rdoEnvironments(0)
Env.CursorDriver=rdUseOdbc
Set cn=env.OpenConnection(dsname:=””,Prompt:=rdDriverPrompt,ReadOnly:=False,Connect:=””)
End Sub
Attach the following code in the click event of the command button to retrieve the details of the
employees.
Set q.ActiveConnection=cn
Set rs=q.OpenResultSet
List1.Refresh
Do Until rs.EOF
List1.AddItem “ Name-“ & “ “ &rs(“emp_name”) & “ “ & “ Emp_No- “ & “ “ &rs(“emp_no”) & “
“&“
Salary- “ &rs(“Sal”)
rs.MoveNext
Loop
End Sub
The rdoTable object contains information about every column in the database table that exists in the
remote data source. The rdoTables collection can be used to obtain the list of all the tables available
in a
particular database.
Add the following code in the declaration section of the form to dimension the object variables for
the
Dim envAsrdoEnvironment
Dim rsAsrdoResultSet
Dim cnAsrdoConnection
Dim q AsrdoQuery
Add the following code in the Form_ Load event to specify the DSN name to open a connection.
Set env=rdoEnvironments(0)
env.CursorDriver=rdUseOdbc
End Sub
Now add the following code in the click event of the Command button to display all the table
names that are
Cn.rdoTables.Refresh
List1.Clear
List1.AddItem t.Name
Next
End Sub
Class based projects , Provides the feature of code reusability. Advantage of other technology such
as remote distribution of objects.
ActiveX DLL
An ActiveX DLL is an in-process server. It runs on the same thread as client. They are faster so
they become part of the application that uses them.
ActiveX EXE
An ActiveX EXE is an out-of process server. It runs as a separate process. A single EXE server can
service multiple clients. More efficient in terms of resource allocation but slow in exchanging
information between servers.
Go to Program ---> Visual Basic 6.0 ---> and the New Project dialog box opens. Select ActiveX
EXE as shown in the Figure:
A class module namely class1 opens by default. Press F4 and edit the properties
Include the following code in the general declaration section of the class module to perform
addition
Addn=A+B
End Function
Define a Function Diff in the general declaration section to find the difference between any two
Diff= A-B
End Function
The same logic holds good for the code given below to perform multiplication for any two
numbers and the
Prod= A*B
End Function
Div= A/B
End Function
Include a function named modulus in the general declaration section as below using mod
operator:
Modulus= A Mod B
End Function
This completes the development of the ActiveX EXE component Calculator. This has to be run
and compiled.
Before running select File ---> Save Project As and save it as ActiveXCalculator.vbp and the
class module as
Calculator.cls.
Make Folder dialog appears as shown in the figure. Choose a folder to save EXE and click OK.
Now the ActiveXCalculator is compiled and registered it can be used in any projetcs.
Create instances of class Calculator in the general declaration section and use it in the project as
given below:
Add the following code in the click event of cmdAdd com, cmdSubtract ,cmdMultiply and
cmdDivide and
End Sub
End Sub
End Sub
End Sub
End Sub
Now run the application. An input box appears as shown in the figure and on entering a number,
another input box appears asking for the second number.
Creating activex dll component
Determine the objects required to divide the functionality of the component in a logical
fashion.
Design the interface that is, the properties, methods and events for each class provided by the
component.
Create a project group consisting of the users component project and a test project.
As each interface element or feature is added, features are added to the test project to exercise
the new
functionality.
Compile the DLL and test it with all potential target applications.
Example:
Start an instance of Visual Basic and select an ActiveX DLL project and it opens into a class
module by
Option Explicit
Sub Main()
gdatServerStarted= Now
End Sub
Step by Step Procedures to create two properties and one method for the Interest class.
Option Explicit
Option Explicit
Dim R As Integer
R=10
FixInterest=(P*R*T)/100
End Function
Dim R As Single
R=8.0
RecInterest=(P*R*T)/100
End Function
Dim R As Single
R=7.5
RecInterest=(P*R*T)/100
End Function
To test the ActiveX DLL project, select Add project from File menu and select a Standard EXE .
Goto References from the project menu and then select the InterestCalculator component and
click
The user has to give the input for principal amount, time period and select the choice of deposit
scheme. Add the following code in the click event of cmdResult command:
Private Sub cmdResult_Click()
Dim a As Single
I= txtPamt.Text
V=txtTime.Text
A=Combochoice(1).Text
If the Deposit Scheme is selected as Fixed Deposit, the interest is calculated by calling
FixInterest function
c=Intobject.FixInterest(I,v) + 1
If the Deposit Scheme is selected as Recurring Deposit, the interest is calculated by calling
RecInterest
c=Intobject.RecInterest(I,v) + 1
If the Deposit Scheme is selected as Cumulative Deposit, the interest is calculated by calling
CumInterest
c=Intobject.CumInterest(I,v) + 1
End If
Object Linking and Embedding: OLE fundamentals, Using OLE Container Control, Using
OLE Automation objects, OLE Drag and Drop, File and File System Control: File System
Controls, Accessing Files.
Introduction
OLE is a means of communication, which gives any application the power to directly use and
manipulate other Windows applications. OLE specification gives the user to link and embed
objects and also to edit the object within the container application.
OLE fundamentals
DDE is an acronym for Dynamic Data Exchange. It is the basic foundation for inter process
communication between applications. While using DDE, unformatted data is exchanged. OLE
enables the programmer to create an application that can display data from many different
applications. The user can edit the data from within the application in which it was created. It
contains the correct underlying object so the information is fully editable.
The object is added to the Toolbox using the Custom Controls command on the Tools menu.
It embeds the object within the interface of a Form in our application.
The CreateObject or GetObject functions can be used for creating the objects in code. This
technique creates the object in a running instance of the application that provides the object.
The object can be embedded or linked within an OLE container control. This technique
permits the change of objects on the Form. The controls in the toolbox in Visual Basic represent
a class. This object known as a control does not exist until it is placed on a Form. The instance of
the class created is the object that is referenced to an application. The Form we work with during
design time is a class. During run time Visual Basic creates an instance of a class.
OLE automation
Some applications provide objects that support OLE automation and some support linking and
embedding. The properties and methods of these objects can be accessed using Object property.
Container application
An application that receives and displays an object’s data is a container application. For
example: Visual Basic application that uses an OLE container control to embed or link data from
another application is a container application.
Linked objects
Data associated with a linked object is stored by the application that supplied the object. This
application stores only link references that displays a snapshot of the source data. Any
application containing a link to that object can access the object’s data and change it. The OLE
container control can be used to create a linked object in our Visual basic application.
Embedded objects
When an embedded object is created, all the data associated with that object is contained in the
object. For Example: if a spreadsheet is an embedded object, all the data associated with the cells
would be contained in the OLE container control. The name of the application that created the
object is saved along with the data. On selecting the embedded object, the spreadsheet
automatically gets started, so that we can edit those cells. When an object is embedded in an
application, no other application has access to the data in the embedded object.
The OLE container control allows adding objects from other applications. An OLE control can
have only one object at a time. Using OLE control we can do the following:
Create objects from the data that was copied onto the clipboard.
Perform an action if the user moves, sizes or updates the objects in the OLE control.
Provide backward compatibility with an application that includes many OLE container
controls.
Each time an OLE control is drawn on a Form, an Insert Object dialog appears as shown in the
Figure: This presents a list of available objects that can be linked to or embedded in the
application.When an object is inserted into the OLE control at design time, the Class, SourceDoc
and SourceItem properties that identify the application that supplies the object, the source
filename and any specific file that is linked from within that file are automatically set. The
following example creates a linked object using Insert Object dialog box.
Example:
This example creates a link from an existing application. An OLE control is drawn on the Form.
This displays an Insert Object dialog box as in the following figure: The Create from File option
is clicked and the Browse button is chosen. A Browse dialog box appears. The desired file is
selected from the directory and the OK button is clicked. The Insert Object dialog is displayed
again. The Link CheckBox is selected and the OK button is clicked. When a linked object is
created, the data displayed in the OLE control exists in one place, which is the source file. The
file can be edited in its original application and saved. The object’s data can be accessed from
any of the other applications that contain links to that data and the data in the source file can be
changed from within any application.
Example:
An OLE control is drawn on the Form. This displays an Insert Object dialog box. The Create
from File option is clicked and the Browse button is chosen. A Browse dialog box appears.
The desired file is selected from the directory and the OK button is clicked. The Insert Object
dialog box returns. The OK button is clicked.
When an embedded object is created, we can either embed data from a file or create a new
empty object that can be filled later with data. When the data is embedded from a file, a copy of
the specified file’s data is displayed in the OLE container control.
When a new object is created, the application that created the object is invoked and data can
be entered into the object.
Example:
This example creates a new file using OLE container. OLE control is drawn on the Form. Insert
dialog box is displayed at this point of time. Create New option is chosen and Microsoft Excel
Worksheet is selected from the list of options displayed as shown in the Figure:
Now right click on the OLE container and choose option. This takes us to the Excel application.
The details required are entered in the excel worksheet and the file is saved as “student.xls”.
Paste Special Dialog box can be used to create an object during design time. This dialog box is
useful if only a portion of a file is to be used, For e.g., a paragraph from a word document, or a
range of cells from an Excel Spreadsheet.
Example :
An Excel worksheet containing data that is to be linked or embedded is opened. The desired
data is selected from the sheet.
Right click the OLE control drawn in a Visual Basic form and choose Paste Special command
from the pop-up menu.
It will display the Paste Special Dialog Box as shown in the figure:
Choose Paste option to create an embedded object and Paste Link option to create a linked
object.
To create a linked or embedded object at run time, various methods and properties are used in
the code.We can create a linked object at run time using the SourceDoc property and CreateLink
method. The following code fragment creates a linked object at run time. (Assume we have a file
called ole.xls).
OLE1.CreateLink “C:\OLE.xls”
The CreateEmbed method can be used to specify an empty embedded object at run time. The
following code fragment inserts a file template for a Microsoft Excel Worksheet in the OLE
container control.
The following code creates an empty embedded object and the application is created using the
DoVerb action.
OLE1.DoVerb -5
The Insert Object dialog box can be displayed at run time, with which we can create a variety of
objects. This can be used in document-centered applications, where the user combines data from
different applications to create a single document. The InsertObjDlg method is used to display
the Insert Object dialog box. The following code fragment displays the dialog box.
Consider an OLE control and a CommandButton are added to a Form. The following code is
entered in the Command1_Click() procedure
OLE1.InsertObjDlg
If OLE1.OLEType=vbOLENone Then
End If
End Sub
Once the dialog box is displayed, the user can make a choice from the options that are displayed.
If the user cancels the dialog, an object is not created. If the user selects a choice, the selected
object is displayed.
Any changes made to the object can be updated in the OLE control by choosing Update from the
File menu in that object. Once the application is chosen to be linked, it is necessary to check if
the application is running. To check if the application is running, the following code
(OLE1.AppIsRunning) is used.
The OLE container control has an ObjectMove event, which is triggered when the object
associated with the control is moved or resized. An ObjectMove event occurs when the user
moves or resizes the object contained in the OLE container control. The arguments of the
ObjectMove represent the coordinates of the object within the object’s container.The following
example illustrates this:
Example:
An OLE control is added to a Form. The following code is entered in the OLE1_ObjectMove()
procedure.
End Sub
OLE Automation is an industry standard technology that applications use to expose their OLE
objects to development tools, macro languages, and other applications that support OLE
Automation. For example, a
A word processor might expose objects such as application, document, paragraph, sentence,
bookmark or selection. When an application supports OLE Automation, the objects it expose can
be accessed by Visual Basic. Visual Basic could be used to manipulate these objects by invoking
methods on the object or by getting and setting the object’s properties. For example, if we create
an OLE Automation object named MyObj, the following code could be written for manipulating
the object.
MyObj.Bold = True
MyObj.FileSaveAs “C:\WORDPROC\DOCS\TESTOBJ.DOC”
The objects, functions, properties and methods supported by an application are usually defined
in the application’s object library. Every application that supports OLE automation provides at
least one type of object. For example, a word processing application may provides an application
object, a document object, and a toolbar object. To create an OLE Automation object, assign the
object returned by CreateObject to an object variable which is shown as follows:
When this code is executed , the application creating the object is started (Microsoft Word in the
illustration given below). If it is already running , a new instance of the application is started ,
and an object of the specified type is created. Once an object is created, we reference it in code
using the object variable we have defined. In the above example, we access properties and
methods of the new object using the object variable, WordBasicObject.
For example
WordBasicObject.filenew
WordBasicObject.FilePrint
WordBaasicObject.FileSaveAs “C:\DOCS\TEST.DOC”
Filenew in the above code opens a new file in the word object. Similarly, we can pass the object
returned by the CreateObject function to a function expecting an object as an argument. For
example
The CreateObject method is used when there is no current instance of the object. The following
example uses the CreateObject function to set a reference (myApp) to Microsoft Excel. It uses
the reference to access the visible property of Microsoft Excel.
Example
A new project is opened and the following code is entered in the Form_Load() procedure.
myApp.filenew
myApp.Visible= True
The following example uses the GetObjectFunction to get a reference to a specific Microsoft
Excel Worksheet. The file, OLE.XLS in the example , must exist in the specified location;
otherwise a Visual Basic error known as the OLE Automation error is generated.
The following code is entered in the Form_Load() procedure of a new Standard EXE project.
Err.Clear
MyXL.Application.Visible = True
MyXL.Parent.Windows(1).Visible = True
The above example uses the worksheet’s Application property to make Microsoft Excel visible,
to close it and so on. The first call to GetObject causes an error if Microsoft Excel is not already
running. In this example, the error causes the ExcelWasNotRunning flag to be set to True. The
second call to GetObject specifies the file to opened. If Microsoft Excel is not already running,
this second call starts it and returns a reference to the worksheet represented by the file. Next,
the code in the example makes both Microsoft Excel and the window containing the specified
worksheet visible. Finally, if there was no previous version of Microsoft Excel running, the code
uses the Application object’s Quit method to close Microsoft Excel . If the application was
already running , no attempt is made to close it . The reference itself is released by setting it to
Nothing.
After declaring a variable that refers to the OLE Automation object, the object can be
manipulated in Visual Basic using the object.property syntax. The following example sets the
Name property of the application object.
myApp.Caption= “MyObject”
Some applications might name objects, properties or methods using characters that have special
meaning in Visual Basic. These are called nonstandard names. For example , a Microsoft Word
provides methods that return strings. The name of each of these methods ends in a dollar sign ($)
which has a special meaning in Visual Basic. To use one of the Microsoft Word string functions
in Visual Basic, the name is enclosed in square brackets.
NameofStyle = MyWord.[StyleName] ()
OLE drag and drop is a more versatile kind of drag and drop. OLE drag and drop method is only
used when we move a file in explorer from one directory(or drive) to another. OLE drag and
drop involves several methods and events, which are dealt with, in this section.
OLEDrag Method
This method is used to initiate an OLE drag operation.TheOLEDrag Method is called when data
is copied between two OLE containers. The following syntax is used object.OLEDrag where
object is the OLE container object that acts as the source for the drag operation.
OLEDragMode Property
This property is used to determine if the object can act as an OLE drag source, and if the
OLEDrag operation is done manually or automatically. The allowable property values are
vbOLEDragManual-0:This is the default value. It is used when the user’s own OLE drag
handlers are used in the application.
vbOLEDrag Automatic-1 :This is used when the application has to handle the drag and drop
operations.
OLEDropModeProperty
This property determines the methodology of processing OLE drop events in the application. It
can take any one of the following values.
vbOLEDropNone-0:This is the default value. It prevents the OLE container from allowing
OLE drop events.
vbOLEDropAutomatic-1:This is set when the user entrusts Visual Basic with handling of the
OLE drag routines.
OLEDropAllowed Property:This property determines whether the OLE drop operations are
allowed or not. If this is set to True, it allows OLE drop operations on the container, otherwise
drop operations are prohibited.
OLEDragDrop() event :This event is fired whenever an OLE drop operation is performed on
an OLE container which allows OLE drop operations.
As Single, y As Single)
OLE DataObject can be referenced using the GetData method to retrieve the data being dropped
in this event. Effect parameter is used to communicate to the target component the action that is
to be performed on the data. The effect parameter can be any one of the following as shown
inTable:
PARAMETER DESCRIPTION
vbDropEffectNone – 0 Target cannot accept OLE data
vbDropEffectCopy --1 Specifies that data should be copied from
source to destination
The button parameter is used to identify the button on the mouse that was clicked during OLE
drag operations as in the table below:
VALUE DESCRIPTION
1 Left Button
2 Right Button
3 Middle Button
The x and y parameters indicate the current position of the mouse pointer. These values are used
if precision dropping is required within the target control.
OLECompleteDrag() event is fired when data has been dropped from the source control and it
has either successfully performed a Move or Copy operation or the operation was cancelled.
OLEStartDrag() event is fired when the source control’s OLEDragMode property is set to
manual. It is also fired when the source component initiates an OLE Drag operation and the
OLEDragMode property is set to automatic.
OLEDragOver() event is fired when the mouse is moved over an OLE container during an
OLE drag operation.
OLESetData() event is fired when the target component issues a GetData method on the
source’s DataObject. The syntax for this event is as follows:
Private Sub Object_OLESetData(data As DataObject, dataformat As Integer)
Example:
Start a new project by selecting Sandard EXE from the New Project dialog box.
Save the form as olefrm.frm and set the Name property to ole frm and caption property to
OLE Drag and Drop Demonstration Project.
Add two text boxes of equal size as shown in the figure below the project by dragging them
from the toolbox and name them as OLEtext1, OLEtext2. Clear their text property and set their
Multiline property to true.
OLEtext1.Text = Data.GetData(vbCFText)
End Sub
Effect = vbDropEffectCopy
End Sub
Effect = vbDropEffectCopy
OLEtext2.Text = Data.GetData(vbCFText)
End Sub
Effect = vbDropEffectCopy
Data.SetData OLEtext2.Text vbCFText
End Sub
Now press F5 to run the project to get the output as in the figure:
Three file system controls available in Visual Basic are DriveListBox, DirectoryListBox and
FileListBox. In an application that allows to selecting files from drives, these controls are used
in combinations. When we need to select a file, a dialog box including all these three controls is
displayed on the screen. We can select the desired file by selecting a drive from the
DriveListBox, a directory from the DirectoryListBox and a file from the FileListBox.
Example:
A new standard EXE project is opened and the Form of the project is saved as Select.Frm and
the project is saved as Select.Vbp. The application is designed as per the following specification
in the Table.
The following code is entered in the general declaration section of the Form.
Option Explicit
The following code is entered in the Form_Load () procedure.
Private Sub Form_Load()
Combo1.AddItem “All files(*.*)”
Combo1.AddItem “Text files(*.DOC)”
Combo1.AddItem “All files(*.TXT)”
Combo1.ListIndex = 0
Label4.Caption= Dir1.Path
End Sub
The following code entered in the Drive1_Change() procedure is executed whenever the
DriveListBox is
changed.
Private Sub Drive1_Change()
On Error GoToErrorTrap
Dir1.Path=Drive1.Drive
Exit Sub
ErrorTrap:
MsgBox “Drive Error1”, vbExclamation, “Error”
Drive1.Drive= Dir1.Path
Exit Sub
End Sub
An error trap is set before the procedure. This executes the command that changes the Path
property of the DirListBox. This error trap is required, because changing the path of the
DirListBox may cause an error at run time.
The following code is entered in the Dir1_Change procedure and is executed whenever the
DirListBox is changed.
Private Sub Dir1_Change()
File1.Path = Dir1.Path
Label4.Caption= Dir1.Path
End Sub
Enter the following code in the Combo1_Click() procedure which updates the Pattern property
of the FileListBox according to the selected file type. The Pattern property returns or sets a value
indicating the filenames displayed in a FileListBox control at run time.
Private Sub Combo1_Click()
Select Case Combo1_ListIndex
Case 0
File1.Pattern = “*.*”
Case 1
File1.Pattern = “*.DOC”
Case 2
File1.Pattern = “*.TXT”
End Select
End Sub
The following code entered in the cmdOK_Click() procedure. The If statement checks for the
selected
file and displays a message box.
Private Sub cmdOK_Click()
If Text1.Text = “” Then
MsgBox“ No file was selected”
Else
MsgBox “Selected File is” + Text1.Text
End If
End Sub
Enter the following code in the cmdCancel_Click () procedure which terminates the application.
Private Sub cmdCancel_Click()
End
End Sub
Accessing files
A File Consists of a series of related bytes located on a disk.There are three ways of accessing
files in Visual Basic. They are as follows:
Random Access
Sequential Access
Binary Access
Random access files
A random access file is like a database. It is made up of records of identical size. Each record is
made up of data of identical size. Figure shows a random access file with two fields per record.
DEEPA22VIDYA23
The following program allows us to maintain a database file called Product.Dat that holds the
record of product information.
Example:
A new Standard EXE project is opened and the Form and the project are saved as Product.frm
and Product.vbp. The Form is designed as per the following specification table. The designed
Form appears as shown in the Figure:
Besides the Form file the application also requires a program module. Hence , a module is added
to the project, by selecting Add Module from the Project menu.
Enter the following code in the general declaration section of Module1 to declare a user-defined
type that corresponds to the fields of a record in the Product Dat file.
Option Explicit
Type ProductInfo
Price As String * 8
End Type
The following code is entered in the general declaration section of the Form.
Option Explicit
Dim Filenum
The file must be opened before the data can be written to or read from the file. The following
code in
RecordLen = Len(product)
Filenum=FreeFile
CurrentRecord =1
If LastRecord = 0 Then
LastRecord = 1
End If
ShowCurrentRecord
End Sub
FreeFile() function is used to get a file number that is not already in use.
The RecordLen and Filenum variables are now updated and the procedure opens the file
Product.Dat
Variable CurrentRecord is used to store the record number of the currently displayed record.
Variable LastRecord is used to store the record number of the last record in the file.
A new procedure called SaveCurrentRecord is created which is responsible for saving the
contents of
Product.code=Text2.Text
Product.price = Text3.Text
Product.manufacture_date = Text4.Text
End Sub
Put statement stores the contents of the variable in record number CurrentRecord of the file.
A new procedure called ShowCurrentRecord() is created in the declarations section of the Form
that displays
Text1.Text=Trim(Product.Name)
Text2.Text=Trim(Product.code)
Text3.Text=Trim(Product.price)
Text4.Text=Trim(Product.manufacture_date)
End Sub
Get statement is used to fill the variable Product with the data of the current record. After it is
filled the
contents are displayed by updating the Textbox controls.Trim function is used to remove the
trailing blanks.
The following code is entered in the cmdNew_Click() procedure, adds a new record to the file.
SaveCurentRecord
LastRecord= LastRecord + 1
Product.Product_Name = “”
Product.Product_Code = “”
Product.date_of_manufacture_date = “”
Put #Filenum, LastRecord, Product
CurrentRecord = LastRcord
ShowCurrentRecord
Text1.SetFocus
End Sub
If CurrentRecord = 1 Then
Else
SaveCurrentRecord
CurrentRecord= CurrentRecord – 1
ShowCurrentRecord
End If
Text1.SetFocus
End Sub
The following code is entered in the cmdExit_Click() procedure, which is executed when the
Exit
button is clicked.
SaveCurrentRecord
Close #Filenum
End
End Sub
Sequential Access Files are accessed line by line and are ideal for applications that manipulate
text files. When data is written into a sequential file, we write lines of text into a file and when
data from a sequential access file is read, we read lines of text from a file. Sequential access file
is opened in one of the three ways – output, append or input.
In order to create a sequential file, we need to open a file for output. After the file is created, we
can use output command to write lines to the file. The following code example creates the file
OUTPUT.TXT and writes the contents of the TextBox Text1 into the file.
Example:
A new Standard EXE project is opened and a TextBox and CommandButton is added to the
Form. The Form and the project files are saved as SEQ.FRM and SEQ.VBP.
filenum = FreeFile
Close filenum
End Sub
The application is run by clicking F5. Text that is necessary is entered in the TextBox and the
CommandButton is clicked.
The enetered text appears in the file OUTPUT.TXT file. This can be viewed by opening the file
in the
Notepad after terminating the application. The following code appends the existing file:
Two more CommandButton controls namely Command2 and Command3, and a TextBox
control Text2 are
Filenum = FreeFile
Close filenum
End Sub
In order to open the sequential file for input, we can use the Input statement. Once the file is
opened
for input, the Input() function can be used to read the entire contents of the file into the TextBox
or a string
variable.
Filenum = FreeFile
Filelength = LOF(1)
Text1.Text = Filelength
Close filenum
End Sub.
Binary access files are accessed byte by byte. Once a file is opened for binary access we can
read from and write to any byte location in the file. The ability to access any desired byte in the
file makes it the most flexible one. Before accessing a file in binary mode, the file should be
opened first for binary access.
Example :
A new project is opened and the Form of the project is saved as BIN.FRM and the project file as
BIN.BAT. A CommandButton is added and the following code is entered in the Click event:
filenum = FreeFile
Close filenum
End Sub
The applicaton is created and the click event of the CommandButton creates the file
BINARY.DAT.
UNIT 5
CONTROLS IN VB
Additional controls in VB: sstab control, setting properties at runtime, adding controls to tab,
list control, tabstrip control, MS Flexgrid control, Why ADO, Establishing a reference,
Crystal and Data Reports.
SSTab control:
It provides an easy way of presenting several dialogs or screens of information on a single form.
Only one tab is active in the control at a time,displaying the controls it contains to the user,while
hiding the controls in the other tabs. Either open the property pages for a control or open the
printer dialog box properties to see .each tabs displays a separate set of controls. The Tabbed
Dialog control provides a group of tabs, each of which acts as a container for other controls. The
controls are exclusive to the particular tab. Other tabs can’t use the controls of one tab. Not
possible to see one tab’s control in another tab.
The properties are set using the property pages. Some properties are in runtime .
Properties:
Tab0:General
Tab1:Financial
Tab2:Personal
At the run time, the user can navigate through the tabs by either clicking on them, by pressing
CTRL+TAB. To create a tab called ‘general’ and allows the user to access the tab with keyboard
combination ALT+G.
The General tab of the Property Pages dialog box for the ImageList control. The list of images
contained in the ImageList control can be managed through the Images tab of the Property Pages
dialog box, as shown in Figure. This tab enables you to add and remove images from the control
as well as set additional information about each image. The Index of each image is assigned by
Visual Basic. The Index starts at 1 for the first image and increments by 1 for each additional
image.
The Key property to refer to an image in the ImageList's collection of images. The Key property
is a string value that can use in place of the Index property to refer to an image in the list. The
easiest way to add images to the ImageList is to use the Images tab at design time. Just click on
the Insert Picture button, and you can browse for the *.ico and *.bmp files that you want to add
to the control.
After added images to the ImageList control, they are available for our application to use in
other controls. Also can load images into PictureBoxes and Image controls from theImageList.
Although you can add all the images you may need in your application to theImageListat design
time, there are times when you will have to manipulate these images at runtime. This can be
done through the ListImages Collection of the ImageList control. e ListImages Collection
contains ListImage objects.
The Add method of the ListImages Collection to add images to the ImageList at runtime. The
syntax for Add is as follows:
ImageList1.ListImages.Add([index], [key], picture)
Here ImageList1 is the name of the ImageList control on your form. Index and Key are
optional parameters. If Index is specified, it will be the location at which the image is loaded into
the ListImages Collection. If Index is omitted, the new image will be inserted at the end of the
collection. Key is a string value that you can use to refer to an image in the list without knowing
its index value.
To create Tab objects at run time, use the Add method for Tab objects. Note One Tab object is
created by default. The code below adds 2 tabs to a tab control
void CForm1::Form_Load()
// Add tabs
// to an imagelist control
// You need to set the images before (either at design or run time)
m_AxTabstrip1.Tabs.Clear();
}
Difference between SSTab and TabStrip
SSTab:
1) Is a container
2) Can be buggy (always put a frame or picturebox on each tab and site your controls inside
those containers)
TabStrip:
1) Not a container. You must toggle the visibility/zorder of actual containers, which makes them
appear to be 'contained' by the TabStrip, hence more code
3) If you are already using MS Common Controls in your app, probably the best option.
MSFlexGride Control:
Basic Properties
The grid’s cells can contain text, numbers, or images. Can also assign a value ‘ to a cell in
several ways, but all methods required to first select the cell by means of its address on the grid
and assign the desired value to its Text property. ‘The address of a cell is given by its Row and
Cot properties, whose values start at 0. Row 0 is the fixed title row, and column 0 is the fixed
title column.
Grid.Row = 1
Grid.Col = 1
After specify the cell’s address, to examine its contents with a statement like:
Grid.Text = “January”
This method of reading or setting cell values requires too many statements for such a simple
task, and it’s probably available to be compatible with the old Grid control. The simplest way to
address a cell on the grid is by means of the TextMatrix property, which has the following
syntax :
Grid.TextMatrix(row, col)
The row and col arguments are the cell’s coordinates in the grid. To extract the value of the first
editable cell, use’ a statement like:
The names of the months and the corresponding profit figures of the grid shown in Figure are
assigned with the following loop, which is executed from within the Display Data button’s event
handler.
Visual Basic has a number of grid controls: the data grid control, the flex grid control, and the
hierarchical flex grid control. Like charts, grids give a way of displaying data. Whereas charts
present data in graphical format, grids appear like spreadsheets.A grid presents the user with a
twodimensional array of individual cells. When you display a grid, it seems that users should be
able to just type the data they want into the grid, but that’s not the way it works. Grid controls
can hold data in each cell when you put it there, but the user can’t simply enter that data—also
add the code to do that. The flex grid control is often used to display database data in read-only
format. It also features the ability to rearrange its columns under user control, as we’ll see, as
well as the ability to display images in each cell instead of just text. Each cell supports word
wrap and formatting. To add a flex grid control to your program, open the Components dialog
box by selecting Project[vbar]Components, click the Controls tab, select the Microsoft FlexGrid
Control entry, then click on OK to close the Components dialog box.
ActiveX Data Objects
Prior to VB6 and the introduction of ADO (ActiveX Data Objects), VB programmers would
generally use DAO (Data Access Objects) to interact with local databases such as MS Access
and use RDO (Remote Data Objects) to interact with client/server databases such as Oracle and
SQL Server. The concept behind Visual Basic ADO was Universal Data Access (UDA), where
one database access method could be used for any data source; it was designed to replace both
DAO and RDO.
The ADO (ActiveX Data Object) data control is the primary interface between a Visual Basic
application and a database. It can be used without writing any code at all! Or, it can be a central
part of a complex database management system. This icon may not appear in our Visual Basic
toolbox. If it doesn’t, select Project from the main menu, then click Components. The
Components window will appear. Select Microsoft ADO Data Control, then click OK. The
control will be added to your toolbox.
ADO collections
Fields: This collection contains a set of Field objects. The Collection can be used in either a
Recordset object or in a Record object. In a Recordset object, each of the Field objects that make
up the Fields collection corresponds to a column in that Record set object. In a Record object, a
Field can be an absolute or relative URL that points into a treestructured namespace (used for
semi-structured dataproviders like the Microsoft OLE DB Provider for Internet Publishing) or as
a reference to the default Stream object associated with that Record object.
Properties: An object can have more than one Property object, which are contained in the
object's Properties collection.
Parameters:A Command object can have several Parameter commands to change its predefined
behavior, and each of the Parameter objects are contained in the Command object's Parameters
collection
Errors: All provider-created errors are passed to a collection of Error objects, while the Errors
collection itself is contained in a Connection object. When an ADO operation creates an error,
the collection is cleared and a new group of Error objects is created in the collection.
ADO objects
Connection:
The connection object is ADO's connection to a data store via OLE DB. The connection object
stores information about the session and provides methods of connecting to the data store. As
some data stores have different methods of establishing a connection, some methods may not be
supported in the connection object for particular OLE DB provider. A connection object
connects to the data store using its 'Open' method with a connection string which specifies the
connection as a list of key value pairs.
Catalog='Northwind';Integrated Security='SSPI';".
The start of this connection string must identify the type of data store connection that the
connection object requires:
a remote provider and server (see RDS), using the syntax "Remote provider=" and
"Remote server="; or
Command:
After the connection object establishes a session to the data source, instructions are sent to the
data provider via the command object. The command object can send SQL queries directly to the
provider through the use of the CommandText property, send a parameterised query or stored
procedure through the use of a Parameter object or Parameters collection or run a query and
return the results to a dataset object via the Execute method. There are several other methods
that can be used in the Command object relating to other objects, such as the Stream, RecordSet
or Connection objects.
Recordset:A recordset is a group of records, and can either come from a base table or as the
result of a query to the table. The RecordSet object contains a Fields collection and a Properties
collection. The Fields collection is a set of Field objects, which are the corresponding columns in
the table. The Properties collection is a set of Property objects, which defines a particular
functionality of an OLE DB provider. The RecordSet has numerous methods and properties for
examining the data that exists within it. Records can be updated in the recordset by changing the
values in the record and then calling on the Update or UpdateBatch method.
Immediate:
The recordset is locked using the adLockOptimistic or adLockPessimistic lock. The data are
updated at the data source after the record is changed and the Update method is called.
Batch:
The recordset is locked using adLockBatchOptimistic and each time Update is called the data are
updated in a temporary buffer. Finally, when UpdateBatch is called the data are completely
updated back at the data source. This has the advantage of it all being done in memory, and if a
problem occurs then UpdateCancel is called and the updates are not sent to the data source.
Transaction:
If the OLE DB provider allows it, transactions can be used. To start the transaction, the
programmer invokes the BeginTrans method and does the required updates. When they are all
done, the programmer invokes the CommitTrans method. RollbackTrans can be invoked to
cancel any changes made inside the transaction and roll back the database to the state before the
transaction began.
Record:
This object represents one record in the database and contains a fields collection. ARecordSet
consists of a collection of Record objects.
Stream:
A stream, mainly used in a RecordSet object, is a means of reading and writing a stream of
bytes. It is mostly used to save a recordset in an XML format, to send commands to an OLE DB
provider as an alternative to the CommandText object and to contain the contents of a binary or
text file.
Property:
This object is specific to the OLE DB provider and defines an ability that the provider has
implemented. A property object can be either a built-in property — it is a well-defined property
implemented by ADO already and thus cannot be altered — or can be a dynamic property —
defined by the underlying data provider and can be changed
Error:
When an OLE DB provider error occurs during the use of ADO, an Error object will be created
in the Errors collection. Other errors do not go into an Error object, however. For instance, any
errors that occur when manipulating data in a RecordSet or Field object are stored in a Status
property.
Basic usage
Some basic steps are required in order to be able to access and manipulate data using ADO :
4. Populate the recordset by opening it and passing the desired table name or SQL statement as a
6. Commit the changes you made to the data (if any) by using Update or UpdateBatch methods.
Via Windows Control Panel, double-click on Administrative Tools, then Data Sources (ODBC).
The ODBC Data Source Administrator screen is displayed, as shown below. Click on the System
DSN tab.
Click the Select button. The Select Database dialog box appears. On a default installation of
VB6 or Visual Studio 6, the BIBLIO.MDB sample database should reside in the folder
C:\Program Files\Microsoft Visual Studio\VB98. Navigate to that folder, select
BIBLIO.MDB from the file list, and click OK.
ADO stands for ActiveX data objects. As ADO is ActiveX-based, it can work in different
platforms and different programming languages. Besides, it can access many different kinds of
data such as data displayed in the Internet browsers, email text and even graphics other than the
usual relational and non-relational database information.To be able to use ADO data control, you
need to insert it into the toolbox. To do this, simply press Ctrl+T to open the components dialog
box and select Microsoft ActiveX Data Control 6. After this, you can proceed to build your
ADO-based VB database applications.
OLE DB
Object Linking and Embedding Database (OLE DB) is a group of APIs used to facilitate and
abtract access to application data of different file formats, including spreadsheets, structured
query language (SQL)-based database management systems (DBMS), indexedsequential files,
and personal databases. OLE DB is based on the Component Object Model (COM) and is part of
the Microsoft Data Access Components (MDAC) software package, which is used to read and
write data. The OLE DB object model components are data source objects (DSO), command
objects, rowset objects and session objects. OLE DB uses abstraction sets to segregate stored
application data, because different programs require access to different DSO types.
Providers: Software components that supply consumer data by using OLE DB APIs When
requesting OLE DB data, an application follows this sequence: Initialize the OLE.
Crystal Reports and Data Reports are report generators. Crystal Reports is a third party product
developed by Seagate of Singapore. It has been bundled with various data access tools. It can
work with Visual Basic on your PC or with the AS/400 as well.
Hardware : A printer must be installed. It need not be physically connected though. This is
because Crystal Reports builds the reports based on the properties of the printer.
Application : We can access Crystal Reports only through the VB IDE. If Crystal Reports has
not been installed then follow the steps given below. Prepare a pencil copy of the report structure
that we want to create.
Installation : So, Crystal Reports has been installed and we have a rough ‘copy’ of the report that
we want. Let us get started. Click on Add_Ins. Select Report Designer. Click on Field and Select
New. Or click on the icon that represents a new report.
DATA REPORT
Data Report as it stands today is meant for programmers. To use Data Report, we need to use
ADO or Data Environment.
Create a data source using ADO Add the Data Report object to our project Place textboxes
representing the various fields that we want on the DataReport object. Link the Textboxes to the
various fields of the data source. Display the report using the Show method.
To add Data Report designer to the form right click on the toolbox and select Components from
the pop-up menu. Click on the ‘Designers’ tab and select ‘Data Report’. The Data Report
Designer is the form on which we design the layout of the report. The Data Report object is the
programmable object that represents the Data Report Designer
PARTS OF THE DATA REPORT
Section Object
Data Report Object can be used to programmatically control the form which is its Visual
Component . The Data Report Designer consists of a number of Sections like header, footer and
detail sections. Each of these section objects can be configured at design time or controlled
through code at run time. Each section has a set of properties that can be manipulated. Data
Report Controls are special control that can be created on the Data Report Designer and these
tools are placed under separate tab in the toolbox.
Report Header: Title of the report is given in this section. If the first page of the report should
contain only the title, ForcePageBreak property is set to rptPageBreakAfter.
Group Header/Footer : To give the heading for every group. A group header must also have a
group footer.
Details : This section contains the actual data. The records are displayed in this section.
Page Footer : To give the page footer and it can be page number or any relevant text like the
date of report etc.
Report Footer :To give the summary for the report which can contain address, bibliography etc.
The Report Footer appears between the last Page Header and Page Footer.
Label Control (RptLabel) ---> To display the labels on the report to identify fields or sections.
Image Control (RptImage) ---> To display pictures on the report. This control cannot be tied to a
data field.
Line Control (RptLine) ---> To draw lines on the report.
Shape Control (RptShape) ---> To draw rectangles, circles, etc on the report.
Function Control (RptFunction) --->Special Textbox that calculates values as the report is
generated.
Create a data source using ADO. Invoice.mdb is used. Create a list that consists of
CustomerName,
Dim adoconAsADODB.Connection
Dim adorsAsADODB.Recordset
To create a connection and recordset add the following code in the Form load event :
adocon.Open “DSN-Invoice”
Add a CommandButton and enter the following code in the click event:
orders_data.customercode”).
Add three RptTextBox controls to the Data Report designer. The textbox caption is Unbound
which means that these controls are not bound to any data source or data field. Binding the
RptTextBox to a data field: In the Properties Window of the RptTextBox enter the name of the
field to be displayed in the Data Field property. The Data Report designer will look as in the
figure:
DISPLAYING THE REPORT
The Recordset is created and the fields are assigned in the Data Report Designer. To link the
recordsource to the Data Report Show method of the Data Report is called. Add the following
codes in the command button click event: Set DataReport1.DataSource = adors
DataReport1.Show
There are two ways of handling the ‘multiple reports’ situation.We can create a Data Report or
we can display different data using only one or a few DataReport forms. Both the approaches
have their merits and demerits.
Let us use the DataReport1 to create another report. In this report we will display the Customer
Name, Customer Address and the Order Value. Add another button to the form. Give the caption
like “Report2”.
orders_data.customerid”)
DataReport1.Sections(2).Controls(“Label3”).Caption = “Address”
DataReport1.Sections(3).Controls(“Text3”).DataField = “ordervalue”
DataReport1.Sections(3).Controls(“Text2”).DataField = “address2”
DataReport1.Sections(3).Controls(“Text1”).DataField = “customer_name”
DataReport1.Sections(5).Controls(“Function1”).DataField = “ordervalue”
DataReport1.Show
A fresh recordset is created and the value for the column headers are given during runtime.
Similarly the data that has to be displayed is also specified at runtime. In this way we can create
multiple reports using one DataReport designer.