1728973795-Visual Basic Lesson Notes
1728973795-Visual Basic Lesson Notes
UNIT I
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.
1
Thereafter, Microsoft declared VB6 a legacy
programming language in 2008. Fortunately,
Microsoft still provides some form of support for
VB6. [Link] is a fully object-oriented programming
language implemented in the .NET Framework. It was
created to cater for the development of the web as well
as mobile applications. However, many developers
still favor Visual Basic 6.0 over its successor Visual
[Link].
2
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.
• Menu Bar
• Tool Bar
• Project Explorer
• Properties window
• Form Layout Window
• Toolbox
• Form Designer
• Object Browser
3
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.
4
Menu Bar
5
Toolbox
6
Control Description
Displays a True/False or
CheckBox
Yes/No option.
7
Displays a list of items from
ListBox
which a user can select one.
8
(rectangle, square or circle)
to a Form
Project Explorer
9
form, classes and modules. All of the object that make
up the application are packed in a project. A simple
project will typically contain one form, which is a
window that is designed as part of a program's
interface. 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
10
every form in an application is considered an object.
Now, each object in Visual Basic has characteristics
such as color and size. Other characteristics affect not
just the appearance of the object but the way it
behaves too. All these characteristics of an object are
called its properties. Thus, a form has properties and
any controls placed on it will have propeties too. All
of these properties are displayed in the Properties
Window.
Object Browser
11
Object naming conversions of controls (prefix)
Form -frm
Label-lbl
TextBox-txt
CommandButton-cmd
CheckBox -chk
OptionButton -opt
ComboBox -cbo
ListBox-lst
Frame-fme
PictureBox -pic
Image-img
Shape-shp
Line -lin
HScrollBar -hsb
VScrollBar -vsb
1.3 Working with Forms
12
Form
13
Setting the Start-Up Form
14
the following syntax :
Load FormName
Unload FormName
[Link] mode
15
optional argument mode determines whether the Form
will be Modal or not. It can have one of the following
syntax :
* 0-Modeless (default)
* 1-Modal
Hiding Forms
[Link]
16
To hide a Form from within its own code, the
following code can be used.
[Link]
17
Caption Form3
Form
Name frm3
Click on a button to display a
Caption
Form
Label
Name
Label1
18
Run the application. Clicking on the buttons will
display the Forms respectively. But you can see that in
the cmd2_Click( ) event additionally VbModal
argument has been added. You can see the difference
after you display the forms by clicking on the
command buttons. You can notice that you cannot
switch to any other Forms in the application unless
you close the Form3.
19
In the click event of the Hide button Following code is
entered.
[Link]
Unload Me
20
Example 2.2 Changing Background and Foreground
Color at Random
21
white and (0,0,0) is black. Do not worry about the
jargons, you will learn them in later lesson.
• Form1-MyForm
• Label1-LblMessage
• Command1-cmd_bgColor
• Command2-cmd_fgColor
22
r = Int(Rnd() * 256)
g = Int(Rnd() * 256)
b = Int(Rnd() * 256)
Lbl_Msg.ForeColor = RGB(r, g, b)
End Sub
When you run the program, each time you press on the
'Change Background Color' button, you will see
different background color. Similarly, each time you
press on the 'Change Foreground Color', you will see
the message on the Label changes color. The output is
shown in Figure 4.
Figure 4.
23
[Link] Fundamentals
2.1Variables in Visual Basic
Variables are the memory locations which are used to
store values temporarily. A defined naming strategy
has to be followed while naming a variable. A variable
name must begin with an alphabet letter and should
not exceed 255 characters. It must be unique within
the same scope. It should not contain any special
character like %, &, !, #, @ or $.
There are many ways of declaring variables in Visual
Basic. Depending on where the variables are declared
and how they are declared, we can determine how they
can be used by our application. The different ways of
declaring variables in Visual Basic are listed below
and elucidated in this section.
• Explicit Declaration
• Using Option Explicit statement
• Scope of Variables
Explicit Declaration
24
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
For example,
Intcount = Intcount + 1
25
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.
Option Explicit
26
Scope of variables
Local Variables
27
freed and can be reclaimed. Variables that are declared
with keyword Dim exist only as long as the procedure
is being executed.
Static Variables
28
Function RunningTotal ( )
Static Accumulate
Accumulate = Accumulate + num
RunningTotal = Accumulate
End Function
29
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.
30
all procedures in the module to share data and that also
can be accessed from outside the module. In this case,
however, it's more appropriate to describe such a
variable as a property:
31
numeric values, "" for strings, Nothing for object
variables).
Modules
32
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.
33
• Must not contain a space or an embedded
period or type-declaration characters used to
specify a data type; these are ! # % $ & @
• Must not be a reserved word (that is part of
the code, like Option, for example)
• The dash, although legal, should be avoided
because it may be confused with the minus
sign. Instead of First-name use First_name or
FirstName.
34
1. Numeric
Store integer values in the range of 0 -
Byte
255
Store integer values in the range of (-
Integer
32,768) - (+ 32,767)
Store integer values in the range of (-
Long
2,147,483,468) - (+ 2,147,483,468)
Store floating point value in the range of
Single
(-3.4x10-38) - (+ 3.4x1038)
Store large floating value which
Double
exceeding the single data type value
store monetary values. It supports 4
Currency digits to the right of decimal point and
15 digits to the left
2. String
3. Date
35
4. Boolean
5. Variant
+ Add 5+5 10
- Substract 10-5 5
/ Divide 25/5 5
\ Integer 20\3 6
36
Division
* Multiply 5*4 20
Exponent
^ 3^3 27
(power of)
Remainder of
Mod 20 Mod 6 2
division
String "George"&" "George
&
concatenation "&"Bush" Bush"
Relational Operators
37
Logical Operators
Operators Description
Operation will be true if either of the
OR
operands is true
Operation will be true only if both the
AND
operands are true
38
Procedures used in one program can act as building
blocks for other programs with slight modifications.
Sub Procedures
Event Procedures
39
Private Sub Form_Load()
....statement block..
End Sub
General Procedures
40
• 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.
41
Function Procedures
Property Procedures
42
properties for Forms, Standard modules and Class
[Link] Basic provides three kind of property
procedures-Property Let procedure that sets the value
of a property, Property Get procedure that returns the
value of a property, and Property Set procedure that
sets the references to an object.
43
If...Then...Else selection structure
44
You can use Nested If either of the methods as shown
above
Method 1
If < condition 1 > Then
statements
ElseIf < condition 2 > Then
statements
ElseIf < condition 3 > Then
statements
Else
Statements
End If
Method 2
If < condition 1 > Then
statements
Else
If < condition 2 > Then
statements
Else
If < condition 3 > Then
statements
Else
Statements
End If
End If
EndIf
45
e.g.: Assume you have to find the grade using nested if
and display in a text box
46
Case 1
Statements
End Select
average = [Link]
Select Case average
Case 100 To 75
[Link] ="A"
Case 74 To 65
[Link] ="B"
Case 64 To 55
[Link] ="C"
Case 54 To 45
[Link] ="S"
Case 44 To 0
[Link] ="F"
Case Else
MsgBox "Invalid average marks"
End Select
47
2.5 VB Array - Arrays in Visual Basic 6
Declaring arrays
48
arrays are declared in a procedure using Dim or Static.
Array must be declared explicitly with keyword "As".
Fixed-sized Arrays
Declaring a fixed-array
49
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.
Multidimensional Arrays
50
array dimensions, but most people will need to use
more than two or three dimensional-arrays.
51
' This is a static array.
Dim Names (100) As String
52
If you're creating an array that's local to a procedure,
you can do everything with a single ReDim statement:
Sub PrintReport()
' This array is visible only to the procedure.
ReDim Customers(1000) As String
' ...
End Sub
53
When you're resizing an array, you can't change the
number of its dimensions nor the type of the values it
contains. Moreover, when you're using ReDim
Preserve on a multidimensional array, you can resize
only its last dimension:
54
2nd dimension
' Evaluate total number of elements.
NumEls = (UBound(Cells) _ LBound(Cells) + 1) * _
(UBound(Cells, 2) _ LBound(Cells, 2) + 1)
55
Dim ElectronicGoods as ProductDetails ' One Record
Dim ElectronicGoods(10) as ProductDetails ' An array
of 11 records
[Link] = [Link]
[Link] = ElectronicGoods(i).ProdName
56
Constants, Data Type Conversion, Visual Basic
Built-in Functions
Constants
[Link] = 2
57
The same task can be performed using a Visual Basic
constant
[Link] = vbMaximized
Boolean Cbool
Byte Cbyte
Currency Ccur
Date Cdate
Decimals Cdec
Double CDbl
Integer Cint
Long CLng
58
Single CSng
String CStr
Variant Cvar
Error CVErr
59
applications and deserve an in-depth look. Date and
Time are internally stored as numbers in Visual Basic.
The decimal points represents the time between
0:00:00 and 23:59:59 hours inclusive.
60
Day ( ) Day (Now)
61
month and day
DateDiff Function
Format Function
62
expression.
63
instance, a code could be written in a CommandButton
control's click event procedure that would load a file
or display a result.
Classification of Controls
• MSChart control
• The Communications control
• The Animation control
64
• 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
65
user should have no problem in manipulating
the buttons.
• A lot of programmers like to use a
meaningful name for the Name Property may
be because it is easier for them to write and
read the event procedure and easier to debug
or modify the programs later. However, it is
not a must to do that as long as you label your
objects clearly and use comments in the
program whenever you feel necessary
• One more important property is whether the
control is enabled or not
• Finally, you must also considering making
the control visible or invisible at runtime, or
when should it become visible or invisible
66
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.
67
• 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.
68
beginning of the contents of the TextBox
control, SelStart returns 0; when it's at the
end of the string typed by the user, SelStart
returns the value Len(Text). You can modify
the SelStart property to programmatically
move the caret.
• 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. You can assign a
nonzero value to this property to
programmatically select text from code.
Interestingly, you can assign to this property
a value larger than the current text's length
without raising a run-time error.
• 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. Use it to directly retrieve the
highlighted text without having to query
Text, SelStart, and SelLength properties.
What's even more interesting is that you can
assign a new value to this property, thus
replacing the current selection with your own.
If no text is currently selected, your string is
simply inserted at the current caret position.
69
the concatenation operator) to reduce flickering and
improve performance:
[Link] = Len([Link])
[Link] = StringToBeAdded
70
[Link] text, [format]
[Link] ([format])
Property/
Description
Method
Properties
Enabled specifies whether user can
71
interact with this control or not
Index Specifies the control array index
If this control is set to True user
Locked can use it else if this control is set
to false the control cannot be used
Specifies the maximum number
of characters to be input. Default
MaxLength value is set to 0 that means user
can input any number of
characters
Using this we can set the shape of
MousePointer the mouse pointer when over a
TextBox
By setting this property to True
Multiline user can have more than one line
in the TextBox
This is to specify mask character
PasswordChar
to be displayed in the TextBox
This to set either the vertical
scrollbars or horizontal scrollbars
ScrollBars to make appear in the TextBox.
User can also set it to both
vertical and horizontal. This
property is used with the
Multiline property.
Text Specifies the text to be displayed
72
in the TextBox at runtime
This is used to display what text
ToolTipIndex
is displayed or in the control
By setting this user can make the
Visible Textbox control visible or
invisible at runtime
Method
SetFocus Transfers focus to the TextBox
Event
procedures
Action happens when the
Change
TextBox changes
Action happens when the
Click
TextBox is clicked
Action happens when the
GotFocus
TextBox receives the active focus
Action happens when the
LostFocus
TextBox loses it focus
Called when a key is pressed
KeyDown
while the TextBox has the focus
73
Called when a key is released
KeyUp
while the TextBox has the focus
74
You can use two other properties at design time to
modify the behavior of a CommandButton control.
You can 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, you can set
the Cancel property to True if you want to associate
the button with the Escape key.
75
Properties of a CommandButton control
76
..................
End Sub
77
optYearly. You can test which one has been selected
by the user as follows:
If [Link] Then
' User prefers weekly frequency.
ElseIf [Link] Then
' User prefers monthly frequency.
ElseIf [Link] Then
' User prefers yearly frequency.
End If
Strictly speaking, you can 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.
78
for example—but Frame controls are often the most
reasonable choice.
Example
79
Name optHex
Caption &Decimal
OptionButton
Name optDec
80
(Octal, Hexadecimal) that is in effect and then reads in
the number.
81
Private Sub optDec_Click()
[Link] = Format(currentval)
End Sub
82
Properties
By setting this property to
True or False user can decide
Enabled
whether user can interact
with this control or not
Specifies the Control array
Index
index
String array. Contains the
strings displayed in the drop-
List
down list. Starting array
index is 0.
Integer. Contains the number
ListCount
of drop-down list items
Integer. Contains the index
of the selected ComboBox
ListIndex
item. If an item is not
selected, ListIndex is -1
Boolean. Specifies whether
Locked user can type or not in the
ComboBox
Integer. Specifies the shape
of the mouse pointer when
MousePointer
over the area of the
ComboBox
Integer. Index of the last item
NewIndex
added to the ComboBox. If
83
the ComboBox does not
contain any items ,
NewIndex is -1
Boolean. Specifies whether
Sorted the ComboBox's items are
sorted or not.
Integer. Specifies the style of
Style
the ComboBox's appearance
Boolean. Specifies whether
TabStop ComboBox receives the
focus or not.
String. Specifies the selected
Text
item in the ComboBox
String. Specifies what text is
ToolTipIndex displayed as the ComboBox's
tool tip
Boolean. Specifies whether
Visible ComboBox is visible or not
at run time
Methods
Add an item to the
AddItem
ComboBox
Removes all items from the
Clear
ComboBox
RemoveItem Removes the specified item
84
from the ComboBox
Transfers focus to the
SetFocus
ComboBox
Event Procedures
Called when text in
Change
ComboBox is changed
Called when the ComboBox
DropDown
drop-down list is displayed
Called when ComboBox
GotFocus
receives the focus
Called when ComboBox
LostFocus
loses it focus
85
Run Time : The AddItem method is used to add items
to a list at run time. The AddItem method uses the
following syntax.
[Link], Index
86
[Link] 1
[Link] 2
[Link] 3
[Link] 4
[Link] 5
[Link] 6
End Sub
[Link] index
87
Sorting the List
88
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.
Example
89
• Open a new Standard EXE project is opened
an named the Form as [Link] and save
the project as [Link]
• Design the application as shown below.
Object Property Settings
Caption ListBox
Form
Name frmListBox
Text (empty)
TextBox
Name txtName
Label Caption Enter a name
ListBox Name lstName
Caption
Name Amount
lblName Entered
Label
Name lblAmount
Caption
(empty)
Name
Label lblDisplay
Border
1 Fixed Single
Style
Caption Add
CommandButton
Name cmdAdd
CommandButton Caption Remove
90
Name cmdRemove
Caption Clear
CommandButton
Name cmdClear
Caption Exit
CommandButton
Name cmdExit
91
button
'if atleast one character
'is entered
[Link] = True
End If
End Sub
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.
92
Private Sub cmdClear_Click()
[Link]
[Link] = [Link]
End Sub
End If
End Sub
93
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.
94
on either side of the scroll bar indicator. 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.
' Move the indicator near the top (or left) arrow.
[Link] = [Link]
' Move the indicator near the bottom (or right) arrow.
[Link] = [Link]
95
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. The reason for
these two distinct possibilities is mostly historical.
First versions of Visual Basic supported only the
Change event, and when developers realized that it
wasn't possible to have continuous feedback when
users dragged the indicator, Microsoft engineers added
a new event instead of extending the Change event. In
this way, old applications could be recompiled without
unexpected changes in their behavior. At any rate, this
means that you must often trap two distinct events:
96
select a color and then copy its numeric value to the
clipboard and paste it in your application's code as a
decimal value, a hexadecimal value, or an RGB
function.
97
Left, Right, Up, Down, PgUp, PgDn, Home, and End
keys. For example, you can take advantage of this
behavior to create a read-only TextBox control with a
numeric value that can be edited only through a tiny
companion scroll bar. This scroll bar appears to the
user as a sort of spin button, as you can see in the
figure below. To make the trick work, you need to
write just a few lines of code:
98
To be certain, scrolling forms aren't the most
ergonomic type of user interface you can offer to your
customers: If you have that many fields in a form, you
should consider using a Tab control, child forms, or
some other custom interface. Sometimes, however,
you badly need scrollable forms, and in this situation
you are on your own because Visual Basic forms don't
support scrolling.
Sub MoveCanvas()
[Link] -[Link], -[Link]
End Sub
99
near the form's bottom border you set its Top property
to a negative value. It's really that simple. You do this
by calling the MoveCanvas procedure from within the
scroll bars' Change and Scroll events. Of course, it's
critical that you write code in the Form_Resize event,
which makes a scroll bar appear and disappear as the
form is resized, and that you assign consistent values
to Max properties of the scrollbar controls:
100
[Link]
[Link] = 0
101
[Link] = False
End If
' Make the filler control visible only if necessary.
[Link] = ([Link] Or
[Link])
MoveCanvas
End Sub
102
• 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.
103
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.
Don't let the term array lead you to think control array
is related to VBA arrays; they're completely different
objects. Control arrays can only be one-dimensional.
They don't need to be dimensioned: Each control you
add automatically extends the array. The Index
property identifies the position of each control in the
control array it belongs to, but it's possible for a
control array to have holes in the index sequence. The
lowest possible value for the Index property is 0. You
reference a control belonging to a control array as you
would reference a standard array item:
Text1(0).Text = ""
104
Sharing Event Procedures
The fact that multiple controls can share the same set
of event procedures is often in itself a good reason to
create a control array. For example, say that you want
to change the background color of each of your
TextBox controls to yellow when it receives the input
focus and restore its background color to white when
the user clicks on another field:
105
Control arrays are especially useful with groups of
OptionButton controls because you can remember
which element in the group has been activated by
adding one line of code to their shared Click event.
This saves code when the program needs to determine
which button is the active one:
106
property settings are copied from the lowest existing
element in the array.
Index 0
Caption 2
Index 1
CommandButton Caption 3
107
Name cmd
Index 2
Caption 4
Index 3
Caption 5
Index 4
Caption 6
Index 5
Caption 7
Index 6
CommandButton Caption 8
108
Name cmd
Index 7
Caption 9
Index 8
Caption 0
Index 10
Caption .
Index 11
Caption AC
CommandButton
Name cmdAC
Caption +
CommandButton
Name cmdPlus
109
Caption -
CommandButton
Name cmdMinus
Caption *
CommandButton
Name cmdMultiply
Caption /
CommandButton
Name cmdDivide
Caption +/-
CommandButton
Name cmdNeg
Name txtDisplay
TextBox
Text ( empty )
Caption =
CommandButton
Name cmdEqual
110
The following variables are declared inside the general
declaration
111
Current = Val([Link])
End Sub
112
Choice = "/"
End Sub
113
Select Case Choice
Case "+"
Result = Previous + Current
[Link] = Result
Case "-"
Result = Previous - Current
[Link] = Result
Case "*"
Result = Previous * Current
[Link] = Result
Case "/"
Result = Previous / Current
[Link] = Result
End Select
Current = Result
End Sub
114
For example, you can clear the contents of all the
items in an array of TextBox controls as follows:
115
' This code assumes that txtField(0) is the only control
that was
' created at design time (you can't unload it at run
time).
Do While [Link] > 1
Unload txtFields([Link])
Loop
116
with a nonzero Index value—but you can't create new
submenus or new top-level menus.
117
UNIT - II
118
command in the Tools menu, but you probably won't
use it often.
119
When you want to create a submenu, you press the
Right Arrow button (or the Alt+R hot key). When you
want to return to work on top-level menus—those
items that appear in the menu bar when the application
runs—you click the Left Arrow button (or press
Alt+L). You can move items up and down in the
hierarchy by clicking the corresponding buttons or the
hot keys Alt+U and Alt+B, respectively.
120
An expanded menu
121
the Visual Basic IDE, copy one or more menu items to
the clipboard, and then paste those menu items in the
application under development. You can do that with
controls and with pieces of code, but not with menus!
The best thing you can do in Visual Basic is load the
FRM file using an editor such as Notepad, find the
portion in the file that corresponds to the menu you're
interested in, load the FRM file you're developing (still
in Notepad), and paste the code there. This isn't the
easiest operation, and it's also moderately dangerous:
If you paste the menu definition in the wrong place,
you could make your FRM form completely
unreadable. Therefore, always remember to make
backup copies of your forms before trying this
operation.
122
complete path, typically c:\Program Files\Microsoft
Visual Studio\VB98\Template, can be found in the
Environment tab of the Options dialog box on the
Tools menu. The Template Manager was already
available with Visual Basic 5, but it had to be installed
manually and relatively few programmers were aware
of its existence.
123
The Menu Editor dialog also provides several
CheckBoxes to control the appearance of the Menu.
124
3.2 Creating Menus
Caption Name
File mnuFile
Open mnuOpen
Save mnuSave
Exit mnuExit
Edit mnuEdit
Copy mnuCopy
Cut mnuCut
Paste mnuPaste
125
Run the application by pressing F5. You can see that
you can select a menu. There are other Menus in
Visual Basic 6
126
[Link] EVENTS IN VISUAL BASIC 6
127
or middle mouse button was clicked. The second
argument in an integer called shift. The value of this
argumnet indicates whether the mouse button was
clicked simultaneously with the Shift key, Ctrl key or
Alt key. The third and fourth arguments X and Y are
the coordinates of the mouse location at the time the
mouse button was clicked. As the Form_MouseDown(
) is executed automatically whenever the mouse button
is clicked inside the Form's area the X, Y co-ordinates
are referenced to the form.
128
Form Caption MouseDown
Name frmMouseDown
Credit card is
OptionButton Caption
selected
Name
optCredit
Value
True
OptionButton Caption Cash is selected
Name optCash
Image Name imgCredit
Picture c:/[Link]
Image Name imgCash
Picture c:/[Link]
129
Private Sub Form_MouseDown(Button As Integer,
Shift As Integer, X As Single, Y As Single)
If optCredit = True Then
[Link] X, Y
Else
[Link] X, Y
End If
End Sub
130
4.2 Dialog Boxes
Modal and Modeless Dialog Boxes
131
4.3 The Multiple Document Interface (MDI) in
Visual Basic 6
The Multiple Document Interface (MDI) was designed
to simplify the exchange of information among
documents, all under the same roof. With the main
application, you can maintain multiple open windows,
but not multiple copies of the application. Data
exchange is easier when you can view and compare
many documents simultaneously.
132
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.
133
Parent and Child Menus
134
* Design a menu that has the following structure.
[Link]
End
135
Double click on Child Close and enter the following
code in the click event
Unload Me
136
Graphical Mouse Application In Visual Basic 6
The mouse events can be combined with graphics
methods and any number of customized drawing or
paint applications can be created. The following
application combines MouseMove and MouseDown
events, and illustrates a drawing program.
137
Line ([Link], [Link])-(X, Y)
End If
End Sub
138
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
MouseMove application
139
and name the caption as Clear and set the name as
cmdClear.
140
Introduction
141
columns of data, however one of the most versatile,
hence its name, is the FlexGrid. Most of the other grid
objects are specifically designed for data binding,
whereas the FlexGrid has many collections of
properties, methods and events that lend themselves to
several environments in addition to just data-binding.
142
These are just a few of the possibilities available with
FlexGrids, we'll take a look at more later on.
143
Figure 5: Components Dialog Box
144
Figure 6: Default FlexGrid Appearance
145
Then use this variable to resize to individual column
widths, by dividing it by the number of columns.
With MSFlexGrid
146
lngWidth = .Width - SCROLL_BAR_WIDTH
.Cols = 4
.FixedCols = 1
.Rows = 0
.AddItem vbTab & "Heading Text One" & vbTab &
_
"Heading Text Two" & vbTab & "Heading Text
Three" & _
vbTab & "Heading Text Four"
.Rows = 12
.FixedRows = 1
.WordWrap = True
.RowHeight(0) = .RowHeight(0) * 2
.ColWidth(0) = lngWidth / 4
.ColWidth(1) = lngWidth / 4
.ColWidth(2) = lngWidth / 4
.ColWidth(3) = lngWidth / 4
147
Figure 7: Initialised FlexGrid Appearance
148
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.
149
UNIT-III
Input –Output Organization: Input –output
interface –I/O Bus and Interface –I/O Bus Versus
Memory Bus –Isolated Versus Memory –Mapped
I/O –Example of I/O Interface. Asynchronous
data transfer: Strobe Control and Handshaking
150
tomorrow if user has to access Sybase, they have to
use functions provided by Sybase to access its
database. That not only makes the life of programmer
tough (as he has to learn a new set of functions again),
it also necessitates great amount of changes to
programs. In brief, each DBMS provides its own set of
functions to access its database. So program becomes
database dependent. That means a change in the type
of database (say from Sybase to Oracle) needs the
program to be modified to a larger extent.
When things were getting more heterogeneous and
database independent programs were much desired,
Microsoft designed a new interface called Open
Database Connectivity (ODBC). Well, in nutshell, it
makes the program database independent. That means
whether accessing of Oracle or Sybase or DB2, user
can write the program and in the same manner they
can shift database from one to another.
5.1.2 How does ODBC Function?
To understand how does ODBC function. Each
database vendor provides a program called as ODBC
driver, which takes standard ODBC calls and
translates them into the language the database can
understand. So the application uses ODBC calls
(called as ODBC API) either directly or indirectly (for
example RDOs calling required ODBC calls) to access
the database. And these ODBC calls are translated by
ODBC driver of the specific database to the required
native language. As a result the program uses the same
ODBC calls irrespective of the database it is accessing
151
and the ODBC driver takes care of converting the
standard calls to the native calls.
But how does system know which ODBC driver to
use? Where are these drivers? Where is the
information regarding these drivers? Who supplies
ODBC drivers? We have to answer to these questions
now.
First of all, each database vendor, such as Oracle
corporation, Microsoft , IBM and so on, provides
ODBC driver for its database. Remember if user do
not have ODBC driver he cannot access the database
using ODBC interface. It should also be noted, that
there are some third party ODBC drivers. There are
companies that are specialized in creating ODBC
drivers, for example Intersolv.
ODBC drivers have to be loaded for database that user
need to access. For example, if user want to access
Oracle, they need to load ODBC driver for Oracle.
When they load ODBC driver, Windows OS stores the
details of the driver in System Registry (a part of
Windows where important information is stored).
ODBC driver manager which is a part of Windows OS
loads the required ODBC driver and passes the calls to
driver and takes results from driver and pass the result
to Application.
ODBC driver manager comes to know about the driver
to be used and the database to be accessed through
using Data source name (DSN) used by the application
program.
5.1.3Data Source Name
152
An ODBC data source is accessed using DSN. Data
source name is a name that identifies the following:
• The name of the database to be used
• The type of the database and the ODBC driver to be
used to access the database
DSN is created using ODBC Data Source
Administrator, which is a program supplied by
Windows OS. It is available in Control panel. When
an application intends to access ODBC data source, it
will create ODBC data source name (DSN) and
accesses database through DSN.
So let us summarize the entire process.
• Application sends ODBC calls to ODBC Driver
Manager
• ODBC Driver Manger sends ODBC calls to the
appropriate ODBC Driver
• ODBC Driver converts ODBC calls to the native
calls and accesses the database.
5.1.4Accessing Oracle Database using ODBC
We have just understood various pieces involved in
accessing an ODBC data source. Now let us access
Oracle database through ODBC. For this purpose we
could use either DAOs or RDOs, but when it comes to
accessing ODBC data source, RDO is the obvious
[Link] are the steps in accessing Oracle:
• Makes sure Oracle is installed in the system and it is
up and running. It can be checked using SQL*Plus. If
it is successfully connected to Oracle using SQL*Plus
that means Oracle is accessible to the user.
153
• Makes sure your system contains ODBC driver for
Oracle. This can be done with ODBC Data Source
Administrator.
• Create a DSN for Oracle database. Use ODBC Data
Source Administrator.
• Use DSN in Visual Basic application to access
Oracle database.
To create DSN to access Oracle:
1. Start ODBC data source administrator by running
ODBC (32 Bit) program from Control Panel of
Windows OS.
2. Select Driver tab and check whether the user has
ODBC driver for Oracle. It may have the name
“Microsoft ODBC for Oracle”. If no ODBC driver for
Oracle is existing, user has to load one before
proceeding.
3. Select User DSN tab and click on Add button.
4. When Create New Data Source dialog is displayed,
select Microsoft ODBC for Oracle (or some other
driver meant for Oracle) and click on Finish button.
5. In Microsoft ODBC for Oracle setup dialog enter
Oracle as Data Source Name, Oracle 7.3 database as
Description.
6. If users are using Personal Oracle, leave remaining
blank. If they are using Oracle Server (Client/Server
Oracle) then enter Oracle service name (the one that
you enter as Host String in Sql*plus) as Server.
7. Click on Ok.
8. User should see a new entry in the list of User Data
Sources.
154
5.2 DATA ACCESS OPTIONS
5.2.1. INTRODUCTION
Visual Basic provides variety of options when it
comes to accessing the data stored in the database.
Find all options below.
155
Basic, because now you could work with all kinds of
data formats in the fields of a database: text,
numbers, integers, longs, singles, doubles, dates,
binary values, OLE objects, currency values,
Boolean values, and even memo objects (up to
1.2GB of text). The Jet engine also supports SQL,
which database programmers found attractive.
Fig F.5.1
The figure F.5.1 shows the Data Access objects
Hierarchy.
156
To support the Jet database engine, Microsoft added
the data control to Visual Basic, and you can use
that control to open Jet database (.mdb) files.
Microsoft also added a set of Data Access Objects
(DAO) to Visual Basic:
• DBEngine—The Jet database engine
• Workspace—An area can hold one or
more databases
• Database—A collection of tables
• TableDef—The definition of a table
• QueryDef—The definition of a query
• Recordset—The set of records that make
up the result of a query
• Field—A column in a table
• Index—An ordered list of records
• Relation—Stored information about the
specific relationship between tables
157
bound controls. In fact, you can perform most data
access operations using the data control—without
writing any code. Data-bound controls automatically
display data from one or more fields for the current
record, and the data control performs all operations
on the current record. If the data control is made to
move to a different record, all bound controls
automatically pass any changes to the data control to
be saved in the database. The data control then
moves to the requested record and passes back data
from the current record to the bound controls where
it’s displayed.
When an application begins, Visual Basic uses data
control properties to open a selected database,
create a DAO Database object, and create a
Recordset object. The data control’s Database and
Recordset properties refer to those Database and
Recordset objects, and you can manipulate the data
using those properties. For example, if you have an
SQL statement to execute, you place that statement
in the data control’s RecordSource property, and
the result appears in the Recordset property.
5.2.4 Steps for creating an ODBC Data Source
Name
1. In the Windows Control Panel, double-
click Administrative Tools. The
Administrative tools window opens.
158
2. Double-click Data Sources (ODBC). The
ODBC Data Source Administrator window
opens.
3. Select the System DSN tab and click Add.
The Create New Data Source dialog opens.
4. Select an appropriate Oracle driver and
click Finish. The Oracle ODBC Driver
Configuration window opens.
159
• In the Description field, enter an optional
description for the data source.
• In the TNS Service Name drop-down, select
the TNS Service Name for the database your
workspace repositories will be stored in. If no
choices are shown, or if you are unsure which
name to select, contact your DBA.
• In the User ID field, enter the database user ID
supplied by your DBA.
6. Click Test Connection. The Oracle ODBC Driver
Connect window opens.
7. In the Oracle ODBC Driver Connect window
the Service Name and User ID fields are prefilled
with the information you supplied in the Oracle
ODBC Driver Configuration window. Enter the
password for your user ID and click OK. You are
notified that the connection was created
successfully. Click OK.
8. Click OK to exit the Driver Configuration
window. Then click OK again to exit the ODBC
Data Source Administrator window.
5.2.5 Operations with DAO RecordSet
160
1. Use the AddNew method to create a record
you can edit.
2. Assign values to each of the record's fields.
3. Use the Update method to save the new
record.
Dim dbsNorthwind As [Link]
Dim rstShippers As [Link]
Set dbsNorthwind = CurrentDbSet rstShippers =
[Link]("Shippers")
[Link]
rstShippers!CompanyName = "Global Parcel Service"
.
. ' Set remaining fields.
[Link]
When you use the AddNew method, the Microsoft
Access database engine prepares a new, blank record
and makes it the current record. When you use
the Update method to save the new record, the record
that was current before you used the AddNew method
becomes the current record again.
The new record's position in the Recordset depends
on whether you added the record to a dynaset-type or a
table-type Recordset object. If you add a record to a
dynaset-type Recordset, the new record appears at the
end of the Recordset, no matter how the Recordset is
sorted. To force the new record to appear in its
properly sorted position, you can either use
the Requery method or recreate the Recordset object.
If you add a record to a table-type Recordset, the
record appears positioned according to the current
161
index, or at the end of the table if there is no current
index. Because the Access databse engine allows
multiple users to create records in a table
simultaneously, your record may not appear at the end
of the Recordset. Be sure to use
the LastModified property rather than
the MoveLast method to move to the record you just
added.
162
database restores the table's record count to the correct
[Link] following example creates a snapshot-
type Recordset object, and then determines the
number of records in the Recordset:
Function FindRecordCount(strSQL As String) As
Long
Dim dbsNorthwind As [Link]
Dim rstRecords As [Link]
On Error GoTo ErrorHandler
Set dbsNorthwind = CurrentDb
Set rstRecords =
[Link](strSQL)
If [Link] Then
FindRecordCount = 0
Else
[Link]
FindRecordCount = [Link]
End If
[Link]
[Link]
Set rstRecords = Nothing
Set dbsNorthwind = Nothing
Exit Function
ErrorHandler:
MsgBox "Error #: " & [Link] & vbCrLf &
vbCrLf & [Link]
End Function
As your application deletes records in a
dynaset-type Recordset, the value of
the RecordCount property decreases. However, in a
163
multiuser environment, records deleted by other users
are not reflected in the value of
the RecordCount property until the current record is
positioned on a deleted record.
At that time, the setting of
the RecordCount property decreases by one. Using
the Requery method on a Recordset,followed by
the MoveLast method,sets the RecordCount property
to the current total number of records in
the Recordset. A snapshot-type Recordset object is
static and the value of its RecordCount property does
not change when you add or delete records in the
snapshot's underlying table.
164
Dim rstOrders As [Link]
Set rstOrders =
Forms![Link]
This code always creates the type of Recordset being
cloned (the type of Recordset on which the form is
based); no other types are available. Note that
the Recordset object is declared with the object
library qualification. Because Access can use both
DAO and ADO, it is better to fully qualify the data
access variables by including the object library
reference name.
165
Set dbsNorthwind = CurrentDb
strSQL = "SELECT * FROM Products WHERE
Discontinued = No " & _"ORDER BY ProductName"
Set rstProducts
=[Link](strSQL)
The disadvantage of this approach is that the query
string must be compiled each time it runs, whereas the
stored query is compiled the first time it is saved,
which usually results in slightly better performance.
How to: Create a DAO Recordset from a Table in
the Current Database
The following example uses
the OpenRecordset method to create a table-
type Recordset object for a table in the current
database:
Dim dbsNorthwind As [Link]
Dim rstCustomers As [Link]
Set dbsNorthwind = CurrentDb
Set rstCustomers =
[Link]("Customer
s")
166
Set dbsNorthwind = OpenDatabase("[Link]")
' Set the Archive property to True.
SetProperty dbsNorthwind, "Archive", True
With dbsNorthwind
[Link] "Properties of " & .Name
' Enumerate Properties collection of the
Northwind database.
For Each prpLoop In .Properties
If prpLoop <> "" Then [Link] " " & _
[Link] & " = " & prpLoop
Next prpLoop
' Delete the new property because this is a
' demonstration.
.[Link] "Archive"
.Close
End With
End Sub
167
' Create property, set its value, and append it to the
' Properties collection.
Set prpNew = [Link](strName, _
dbBoolean, booTemp)
[Link] prpNew
Resume Next
Else
' If different error has occurred, display message.
For Each errLoop In [Link]
MsgBox "Error number: " & [Link] &
vbCr & _errLoop.Description
Next errLoop
End
End If
End Sub
168
strSQL = "SELECT * FROM Shippers ORDER BY
CompanyName, ShipperID"
SetrstShippers=[Link]
(strSQL,dbOpenDynaset)
'If no records in Shippers table, exit.
If [Link] Then Exit Sub
strName = rstShippers![CompanyName]
[Link]
Do Until [Link]
If rstShippers![CompanyName] = strName Then
[Link]
Else
strName = rstShippers![CompanyName]
End If
[Link]
Loop
Exit Sub
ErrorHandler:
MsgBox "Error #: " & [Link] & vbCrLf &
vbCrLf & [Link]
End Function
When you use the Delete method, the Microsoft
Access database engine immediately deletes the
current record without any warning or prompting.
Deleting a record does not automatically cause the
next record to become the current record; to move to
the next record you must use the MoveNext method.
However, keep in mind that after you have moved off
the deleted record, you cannot move back to it.
169
If you try to access a record after deleting it on a table-
type Recordset, you will see error 3167, "Record is
deleted." On a dynaset, you will see error 3021, "No
current record."
If you have a Recordset clone positioned at the
deleted record and you try to read its value, you will
see error 3167 regardless of the type
of Recordsetobject. Trying to use a bookmark to
move to a deleted record will also result in error 3167.
170
[Link] EXE and ActiveX DLL
6.1 INTRODUCTION
A standard exe application is one that is created using
Standard EXE project. It is the most widely used
Project type using VB6. Standard EXE application is
normally the most widely used among the available
Project types in Visual Basic. Stand-alone programs
have an .EXE file extension.
A standard EXE application is normally used when
you want to develop a stand-alone application.
Examples include calculators, text editors, and other
similar applications. An ActiveX EXE application is
one that is created using ActiveX EXE project.
ActiveX EXE are widely used in conjunction with
standard EXE applications. There are three types of
widely used of ActiveX projects. These are:
a. ActiveX EXE
b. ActiveX DLL
c. ActiveX Control
171
.DLL file extension.
ActiveX Control: Unlike an ActiveX DLL or
ActiveX EXE file, an ActiveX Control file usually
provides both subprograms and a user interface that
you can reuse in other programs. It has an .OCX file
extension.
172
An ActiveX Exe provides the reusability of code, by
accessing it from different clients.
An ActiveX Exe is a component that can be called by
another application by providing a reference to the
component. But a Standard Exe application cannot be
called in this way.
An ActiveX EXE's code is run in a separate process.
When the main program calls an ActiveX EXE's
method, the application passes required parameters
into the ActiveX EXE's and calls the method. The
ActiveX EXE, upon execution may return the results
to the main program. This is slower than running an
ActiveX DLL's method inside the main program's
address space.
173
Fig: F.6.4.1 ActiveX-6; Dialog Box showing the type
of project to open.
Change the name property of form to frmTestActivex
and caption to “Test form”.
Object Property Setting
CmdShowSelVal
Command Name
Show Selected Value in ActiveX
button Caption
Exe
Command Name cmdCallActivex
button Caption Show Form From ActiveX Exe
optNumbers
Option Name
Choose Numbers in
button Caption
ActiveX Exe
174
OptAlphabets
Option Name
Choose Alphabets in ActiveX
button Caption
Exe
175
Private Sub CmdShowSelVal_Click()
'function that gets the value selected in ActiveX Exe
'and dispalys in a message box
If actvixTest Is Nothing Then
MsgBox "You have selected Nothing.", 64,
"Selected Item in ActiveX Exe"
Else
MsgBox "You have selected " &
[Link] & " in ActiveX Exe.", ,
"Selected Item in ActiveX Exe"
End If
End Sub
176
6.5 Interacting with ActiveX exe from Standard
exe and vice versa.
To demonstrate how the Standard EXE interacts with
the ActiveX EXE, run the test project. Assuming that
the code is entered properly, a form as shown below is
displayed:
177
On selecting and clicking the button opens a form in
ActivexEx Component as shown in below figure.
In this case, Alphabets Drop-Down box is disabled as
“Choose Numbers in ActiveX Exe” has been selected.
Here a value is passed from Standard Exe to ActiveX
Exe based on the option button we selected and its
corresponding drop-down box is enabled in ActiveX.
178
Fig : F.6.5.4 ActiveX-12; Here the Control is passed to
the ActiveX EXE application.
179
Fig : F.6.5.5 ActiveX-13; Control is passed back to the
Main (Standard EXE).
Below shows the item that was selected in ActiveX
Exe.
180
As you can see, in the above example, we have
selected “numbers” in the Standard EXE, and later
selected “2” in the ActiveX EXE. The number “2” is
passed on to the Standard EXE upon request.
Note that this is only a brief example provided to
demonstrate the concept. Practically, the ActiveX
EXE/DLL could be quite large, such as a calculator.
The calling program may be a Text Editor.
Class Module:
Option Explicit
Public Function LoadForm(numbers_disp As Boolean,
alphabets_disp As Boolean) 'Load the form
Load frmActivexEx
[Link] = [Link]
'make the controls on the form as disabled initially
[Link] = False
[Link] = False
'Based on the option user selected
'make its corresponding drop-down box enabled
If numbers_disp = True Then
[Link] = True
ElseIf alphabets_disp = True Then
[Link] = True
End If
[Link]
End Function
Private Sub Class_Initialize()
181
'selectedItem is a global variable declared in
module
'set it to nothing initially
'whcih implies that no item has been selected
selectedItem = "Nothing"
End Sub
Private Sub Class_Terminate()
'on terminating unload the form
Unload frmActivexEx
End Sub
Public Function getselectedchar() As String
'function that gets the item selected in the
drop-down box
getselectedchar = selectedItem
End Function
Form ActiveX :
Option Explicit
Private Sub cboAlphabets_Click()
'assign the selectedItem variable to the item
that is selected in the drop-down box
selectedItem = [Link]
'variable of type clsActivexEx class in Activex_ex
component
Dim actvixTest As clsActivexEx End Sub
Private Sub cboNumbers_Click()
'assign the selectedItem variable to the item that
is selected in the drop-down box
selectedItem = [Link]
End Sub
Private Sub cmdSelAndClose_Click()
182
Unload Me
End Sub
Standard Module :
Option Explicit
'global variable which stores the item selected
in drop-down box
Public selectedItem As String
183
Exe.", , "Selected Item in ActiveX Exe"
End If
End Sub
Private Sub Form_Unload(Cancel As Integer)
Set actvixTest = Nothing
End Sub
6.6 ACTIVEX DLL
Why?
You make an ActiveX DLL or EXE to allow multiple
applications to share the same code. This saves you time
because you only need to write the code once. It also lets
you devote extra time to debugging the shared code. If
you are going to use the code in a lot of different
applications, you can perform extra tests to make sure
the code works correctly and still save time
[Link] the code also lets you fix, upgrade,
and otherwise modify the shared library relatively easily.
You can update the shared DLL/EXE and all of the
applications that use it are automatically updated. The
Binding section talks more about this.
Which?
ActiveX DLLs and ActiveX EXEs are almost exactly the
same in the ways they are built and used. In both cases,
you build one or more classes that applications can use to
do something. The big difference lies in where they are
used. An ActiveX DLL's code is executed within the
main program's address space. It behaves as if the class
was created within the main program's code. Because the
code lies inside the program's address space, calling
methods is very fast.
184
An ActiveX EXE's code is run in a separate process.
When the main program calls an ActiveX EXE's method,
the system marshalls the call to translate the parameters
into the ActiveX EXE's address space, calls the method,
translates the results back into the main program's
address space, and returns the result. This is slower than
running an ActiveX DLL's method inside the main
program's address [Link] of the difference in
speed, an ActiveX DLL is almost always preferable. The
reason ActiveX EXEs are useful is they can run on a
different computer than the main program while an
ActiveX DLL must run on the same computer as the
main [Link] you want to build a library of shared
routines to save programming and debugging, use an
ActiveX DLL because it will give you better
performance. Even if you need to distribute several
copies of the DLL on different computers, it will
probably be worthwhile.
If you want a centralized server library, use an ActiveX
EXE. The EXE can sit on a central computer and work
directly with that computer's resources. If you need to
frequently change how the code works, you can easily
change it in one place.
6.6.1 Making an ActiveX DLL/EXE Project
Start a new project and select ActiveX EXE or ActiveX
DLL. Initially the project is named Project1 and contains
a class named Class1. Change these to meaningful
names. The model Microsoft has in mind is a DLL/EXE
contains several related classes that each perform related
functions. For example, a DLL might contain billing
185
system classes named Customer, Product, and
SalesPerson. The Customer class would contain methods
for manipulating customer data. In this example, you
might change the project name to BillingObjects. You
would change Class1's name to Customer and add two
more classes named Product and SalesPerson. Give the
class Public functions and methods to perform whatever
tasks it should. The main program can only invoke the
Public class methods.
Instancing :
Set the classes' Instancing properties to determine how
the object can be created. In VB6 the allowed values are:
• Private : Code outside the DLL/EXE cannot
create this object type. Other classes in the
DLL/EXE can use this type of class as a helper
but the main program cannot use it.
• PublicNotCreatable : The main program can use
this type of class but cannot create new
instances using the New keyword or with
CreateObject. In this case, you need to provide
some method within the other classes to create
the new object and return it to the main
program.
• SingleUse : The main program can create the
object. Every time you create a new object, the
system makes a new ActiveX EXE instance to
service the object you created. Among other
things, if the EXE contains global variables then
different objects you create get different copies
186
of the variables. This option is allowed for
ActiveX EXEs only.
• GlobalSingleUse:Similar to SingleUse except
you can invoke the properties and methods of
the class as if they were simple global
functions. This option is allowed for ActiveX
EXEs only. See GlobalMultiUse later for more
details.
• MultiUse:The main program can create the
object. When it does, the system makes an
ActiveX DLL/EXE component to handle the
object. If you make other objects, the system
uses the same ActiveX DLL/EXE component to
handle them. This can be a little confusing
depending on whether you are building a DLL
or EXE and whether an EXE is running on
different computers.
If you build an ActiveX DLL, all programs run the
DLL code in their own address spaces. That means
different objects created in the same program will
share the same component server so they could
share global variables defined in the DLL. However,
if the objects are all freed at the same time, the
component server will shut down so any global
values will be lost.
The code in the SharedDll directory available for
download demonstrates this kind of sharing. The
BillingObjects,vbp project contains the project named
BillingObjects. This project holds a BAS module holding
a public variable named g_TheNumber. This variable is
187
visible to other code in the project but not to a main
program using the DLL.
The BillingObjects project also contains a MultiUse
class named Customer. This class has Property Let and
Property Get procedures that set and get the value of
g_TheNumber.
The main program uses two Customer objects like this:
Private m_Customer1 As Object
Private m_Customer2 As Object
Private Sub Form_Load()
Set m_Customer1 =
CreateObject("[Link]")
Set m_Customer2 =
_CreateObject("[Link]")
End Sub
Private Sub cmdGet_Click()
[Link] = m_Customer1.TheNumber
End Sub
Private Sub cmdSet_Click()
m_Customer1.TheNumber =
CInt([Link])
[Link] = ""
End Sub
In the DLL project, open the File menu and select Make
[Link] to build the DLL. Notice how the main
program uses the CreateObject function to create its
instances of the Customer class. The name of the class is
the project's name followed by the class name:
[Link].
188
Notice also that the program creates the two Customer
objects when it starts and it keeps those objects running.
That means the component stays running so the objects
share the value of g_TheNumber. If you use the Set
button to save a value into this variable and then use the
Get button to retrieve the value, you should get back the
value you saved.
This behavior is what you would expect if you included
the DLL's modules directly inside the main program. If
you want that behavior, make the DLL MultiUse. If you
want each class object to have its own global variables,
make the DLL SingleUse. Or better still, move the
variables inside the class so each object gets its own
variables but you still only need one component instance.
That will save some overhead.
The interesting thing is any program that uses a shared
component server can share the values. Compile the test
program and use Windows Explorer to launch two
instances of the program. Enter 1234 in one instance and
click Set. Then click Get in the other instance. The
second program should see the value set by the first.
Note that this sometimes gets messed up and a
component server is left running so you may end up with
two programs running different component servers. The
ActiveX EXE project in the SharedExe directory
demonstrates this sharing using an ActiveX EXE. It's
basically the same as the previous example except is uses
an ActiveX EXE instead of a DLL. Compile the test
program and use Windows Explorer to launch two
instances of the program. Enter 1234 in one instance and
189
click Set. Then click Get in the other instance. The
second program should see the value set by the first.
• GlobalMultiUse: This is similar to MultiUser
except the main program can reference methods
and properties as if they were globally declared.
The code in the GlobalMultiUse directory
demonstrates this. The ActiveX EXE code is the
same as in the previous example except the
Customer class is marked GlobalMultiUse. The
main program uses the Customer's TheNumber
property procedures like this:
Private Sub cmdGet_Click()
' Implicit [Link]
[Link] = TheNumber
End Sub
Private Sub cmdSet_Click()
TheNumber = CInt([Link])
[Link] = ""
End Sub
190
a syntax that is more similar to that used by DLLs built
in C++ and other languages and that's probably why
Microsoft implemented these. They hide the fact that
there is an underlying class object, however, so they
increase your chances for confusion.
Test Projects
The previous sections glossed over a few details dealing
with test projects. After you create your ActiveX DLL
project, you can add a test application. Open the File
menu, select Add Project, and add a Standard EXE. That
project can act as the main program to test your DLL.
This is handy because it means you don't need to
compile the DLL before you can test it. It also means
you don't need to jump back and forth between the DLL
and test application projects.
After you have the DLL code working, you can compile
it into a DLL file. Then you can create independent
applications to use it.
6.6.2 Binding
You can bind your DLL or EXE either at runtime (late
binding) or at design time (early binding). When you use
early binding, you tell the main program all about the
DLL. That lets it do things like provide intellisense for
the DLL's methods. It is also faster than late binding.
Early Binding
To use early binding, load the main program, open the
Project menu, and select References. Find your DLL in
the list and select it. If the DLL project's name is
BillingObjects, then look for an entry named
BillingObjects. If you have had a couple versions of the
191
project in different locations, you may see more than one
entry. Click on one and look at the location displayed
near the bottom of the dialog to see if you have the right
one. If you can't figure it out, click the Browse button
and find the DLL yourself. When you have selected the
DLL, click OK.
Now the program can explicitly refer to the classes in the
DLL. For example, it could declare and create a
Customer object like this:
Dim customer1 As Customer
Set customer1 = New Customer
If you now type "customer1.", intellisense will be able to
list the public methods provided by the Customer class.
In this example, this is just the TheNumber property
procedure.
Early binding has the disadvantage that it imposes more
restrictions on the DLL's compatibility. If you change the
DLL's methods as they are visible to outside code, the
main program will no longer have a correct picture of the
DLL. For example, if you add a new Public method to a
class, the main program will not know about that
method. When you try to create an instance of the class,
the system will decide that the program is looking for an
incompatible DLL version and will display the message:
Class does not support Automation or does not support
expected interface
To fix this, load the main program, open the Project
menu, and select References. Deselect the DLL and click
OK. Then open the References dialog again and reselect
the DLL. Now the program will work again.
192
Depending on your exact arrangement, you may also get
the error:
Type mismatch
To fix this, recompile the main program.
Late Binding
To use late binding, declare references to DLL objects to
have type Object. Then use the CreateObject statement
to instantiate the objects like this:
Dim customer1 As Object
Set customer1
=CreateObject("[Link]")
This code creates an instance of the Customers class that
is defined by the DLL project named BillingObjects.
After this the program can use the Public properties and
methods of the customer1 object just as if it had declared
it using early binding.
Now if you change the DLL's public methods, the
compiled executable will still work (if you removed the
methods the program uses). The downside with late
binding is you don't get intellisense and calling the
DLL's methods takes longer than it does with early
binding.
193
UNIT IV
Priority Interrupt: Daisy-Chaining Priority,
Parallel Priority Interrupt. Direct Memory
Access: DMA Controller, DMA Transfer. Input –
Output Processor: CPU-IOP Communication.
194
can create as many objects for the class which have
defined.
Ways of creating an object in VB:
1. The Custom Control command on the
tools menu is used for adding object in
the toolbox and it it drawn directly on the
form.
2. The functions CreateObject or GetObject
are used to create on object.
3. The object can be embedded or linked
within an OLE container control.
As an example we can say the form we work with
during design time is a class and during the run time
VB creates in instance of a class.
OLE Server: This is an application that can provide
objects to other applications. This is also called as
OLE Source application.
OLE Client :
This is an application that uses objects provided by
OLE Server. This is also called as OLE Container as it
contains objects provided by OLE Server. Not every
application is an OLE Server. Only a few applications
are capable of providing objects. In the same way not
all applications are capable of receiving objects.
However, there are applications, such as MS-Word
and MS-Excel that are capable of being OLE source as
well as OLE Container.
7.3Object Embedding
In object embedding, an object is embedded in the
client application. Along with the object, client
195
application also stores the information regarding
source application (or server) that created the object.
The data stored in client application is separate and no
link is maintained between the data supplied by source
application and data stored in client application.
The advantage with Object Embedding is, client
application maintains its own copy of the data. The
disadvantage is, changes made to original data (in
source application) will not be incorporated in the data
maintained by client.
Whenever you double click on the object in container
application, the source application will be invoked (as
information regarding source application is
maintained) and the data of client application is placed
in source application for editing.
The following example, where we embed a few cells
of Excel spreadsheet to a Word document, will make
this process clear:
1. A collection of cells from a spreadsheet of MS-
Excel is copied to clipboard. As MS-Excel is an OLE
Server, it copies the data in the form of an object.
2. Paste the data (now in the form of an object) from
Clipboard to a document in Ms-Word.
3. Now the data is embedded into MS-World
document as an object. Ms-Word document contains
its own copy of the data.
4. If you double click on the object in MS-Word, then
an instance of MS-Excel is invoked and data from
MS-Word is copied into MS-Excel.
5. User can edit embedded data using MS-Excel.
196
6. If user saves changes and exits MS-Excel then
modified data is placed in MS-Word document.
As you have seen in the above example, once an
object is embedded into MS-Word, you do not have to
invoke source application manually, instead just
double click on the object and that will invoke source
application automatically.
However, if data is changed in the original worksheet
of MS-Excel then those changes are not copied to the
data in MS-Word. This is because in Object
Embedding, source and container applications
maintain two different copies of the data.
197
[Link] Information
You can maintain control over the source through
object linking. The link goes back to information that
you can control, so you can quickly and conveniently
update the information or graphic without needing to
point the user to a new source. A person can go back
and revisit the link over and over again to get the new
information.
2. Convenience
An embedded file can be quite convenient for users of
the presentation or document, as they will be able to
view the file or graphic right in the document without
having to click through a link or follow a web address,
which may require the user to log in first or jump
through other hurdles.
3. Restricted Access
All users have to have access to the file and the
application that runs it, which may prove to be a
disadvantage if you have people who need to access
the link who don't have the right permissions or who
aren't able to install the correct program. In that case,
your presentation or document is only as good as the
privileges or software that your users have. This is not
as big of a problem if you have a lot of users who are
on the same network or work in the same office.
4. Embed Problems
An embedded file will show up as just a snapshot or it
won't be displayed at all if a user can't obtain access to
198
the file. This can derail a critical presentation or
document that depends on the information you are
embedding within it. You may have to test the embed
from the systems that will need to reach it to ensure
that it works, which may take a lot of time to do.
199
Each time an OLE control is drawn on a form, an
Insert Object dialog box appears as shown in
following Fig. F.7.3
Fig F.7.3
Example :
This example is used to create a link from an existing
application.
• When an OLE control to a form, the Insert
Object dialog box appears in order to allow
you to insert an OLE object into the new
control. New OLE object is created with the
Insert Objectdialog box. However, it can also
embed or link to an existing file.
200
• Click the Create From File option button in
the Insert Object dialog box. When a file is
selected by typing its path and name into the
File text box or by using the Browse button,
and then click on OK, that file is embedded
as an OLE object in the OLE control.
• Embedding an existing file by this way is
handy and it saves the time of creating the
file over again from scratch in a new OLE
object.
7.6.2 Creating an Embedded object at Design Time
The following example will create a new file using
OLE container.
• OLE control is drawn in the [Link]
dialog box is displayed.
• ‘Create new’ option is chosen and MSExcel
worksheet is selected from the list of options
as in the figure F.7.3
• Right click on the OLE container and choose
Open.
• Then excel sheet is opened and details can be
added and it is saved as ‘[Link]’ as in the
fig F.7.4
201
Fig F.7.4
Fig F.7.5
7.6.3 Creating Objects using Paste Special Dialog
Box
To create OLE objects at run time, you use the OLE
control. It provides the methods listed in table T.7.1 to
create objects.
OLE Control Method Use
202
Displays the standard OLE
Insert Object dialog box to
[Link]
enable the user to select an OLE
object to create
Creates an embedded object in
[Link]
code without displaying the
file [, type]
OLE Insert Object dialog box
Table T.7.1
Follow these steps to create an OLE object at run time:
1. Draw an OLE control on a form. VB displays the
standard Insert Object dialog box (Fig F.7.6).
Fig F.7.6
203
To create a linked or embedded object at run time,
click the Insert Object dialog box's Cancel button.
1. Click Cancel to close the Insert Object dialog
box without selecting an OLE object to
create.
2. In an event procedure, use the InsertObjDlg,
CreateEmbed, or CreateLink methods to
create an object for the control, as in the
following example:
Private Sub OLE1_DblClick()
' Let the user choose an object to create.
[Link]
End Sub
204
Embed [Link].
End Sub
If you specify a file name for CreateEmbed, Visual
Basic ignores the second argument. If a file contains
more than one type of object, Visual Basic simply uses
the first object in the file. You cannot specify an object
within a file by using CreateEmbed.
Fig. F.7.7
When you try to move or resize an embedded object, it
"snaps back" to its original position.
205
To enable users to move or size OLE objects at run
time, use the ObjectMove event procedure.
ObjectMove has the following form:
Private Sub OLE1_ObjectMove(Left As
Single, Top As Single, _
Width As Single, Height As Single)
'...your code here
End Sub
The arguments to the ObjectMove event procedure are
the position and dimensions to which the user dragged
the object. To make the object respond to the user's
action, simply assign the ObjectMove arguments to the
OLE control's Left, Top, Width, and Height properties,
as follows:
Private Sub OLE1_ObjectMove(Left As
Single, Top As Single, _
Width As Single, Height As Single)
[Link] = Left
[Link] = Top
[Link] = Width
[Link] = Height
End Sub
Now when the user moves or resizes the OLE object,
the OLE control adjusts to the new size and location as
shown in figure F.7.8
206
Fig F.7.8
207
✓ vbOLESizeAutoSize—2; Autosize. The OLE
control is resized todisplay the entire object.
✓ vbOLESizeZoom—3; Zoom. The object is
resized to fill the OLEcontainer control as
much as possible while still maintaining the
originalproportions of the object.
Getting the OLE Automation Object from Linked
or Embedded Objects
Use the OLE control's Object property to get the OLE
Automation object from a linked or embedded object
on a form. Not all applications provide OLE
Automation objects. If an object does not support OLE
Automation, the Object property returns Nothing.
When working with OLE Automation objects, you
should create an object variable to contain the OLE
Automation object. For example, the following lines
of code declare an object variable and establish a
reference to an embedded worksheet when the form
loads:
Option Explicit
Dim mobjExcelSheet
Private Sub Form_Load()
' Embed a worksheet in the OLE control
named oleExcel.
[Link] "c:\excel\[Link]"
' Establish a reference to the OLE
Automation object for the
' embedded worksheet.
Set mobjExcelSheet = [Link]
End Sub
208
In the preceding example, the variable
mobjExcelSheet has module-level scope; that is, other
procedures in the module have access to the variable.
For instance, the following Click event procedure uses
the OLE Automation object mobjExcelSheet to print
the embedded worksheet:
Private Sub cmdPrintSheet()
[Link]
End Sub
Unlike other applications that support OLE
Automation, Microsoft Word requires the following
special syntax to get its OLE Automation object:
Set objVar = [Link]
This is used as special syntax because Word exposes
only the WordBasic language for OLE Automation.
When working with the Word OLE Automation
object, remember that methods and properties apply to
the current document, which might not be the one that
the OLE control is currently displaying.
The following lines of code establish a reference to the
WordBasic OLE Automation object:
Option Explicit
Dim mobjWordBasic
Private Sub Form_Load()
' Embed a Word document in the OLE control
named oleWord.
[Link]
"c:\docs\[Link]"
' Establish a reference to the OLE
Automation object for the
209
' embedded worksheet.
Set mobjWordBasic =
[Link]
End Sub
The following two event procedures demonstrate how
the WordBasic methods apply to the current
document.
' Open a new file in Word (changes the
current document).
Private Sub cmdOpenNew()
[Link]
End Sub
' Print the current document in Word.
Private Sub cmdPrintDocument()
[Link]
End Sub
8.1 INTRODUCTION
This chapter is on the file system controls helps the
user in understanding the methodology of using them
for choosing disk files for application. It also gives a
detailed description of accessing files in VB.
8.2 FILE SYSTEM CONTROLS
The DriveListBox control is a specialized drop-down
list that displays a list of all the valid drives on the
user's system. The most important property of the
210
DriveListBox is the Drive property, which is set when
the user selects an entry from the drop-down list or
when you assign a drive string (such as "C:") to the
Drive property in code. You can also read the Drive
property to see which drive has been selected.
To make a DirListBox display the directories of the
currently selected drive, you would set
the Path property of the DirListBox control to
the Drive property of the DriveListBox control in
the Change event of the DriveListBox, as in the
following statement:
[Link] = [Link]
The DirListBox control displays a hierarchical list of
the user's disk directories and subdirectories and
automatically reacts to mouse clicks to allow the user
to navigate among them. To synchronize the path
selected in the DirListBox with a FileListBox, assign
the Path property of the DirListBox to
the Path property of the FileListBox in
the Change event of the DirListBox, as in the
following statement:
[Link] = [Link]
The FileListBox control lists files in the directory
specified by its Path property. You can display all the
files in the current directory, or you can use
the Pattern property to show only certain types of
files.
211
Similar to the standard ListBox and
ComboBox controls, you can reference
the List, ListCount, and ListIndex properties to
access items in a DriveListBox, DirListBox, or
FileListBox control. In addition, the FileListBox has
a MultiSelect property which may be set to allow
multiple file selection.
The following program shows the selection of file
from [Link] selecting desired file, a
message box is displayed which displays the name of
the selected file. The application is designed as in the
following form.
All controls are added as in the form below and is
shown figure F.8.2.1
212
Fig F.8.2.1
Then the coding is added for each control as follows.
Private Sub Combo1_Change()
Select Case [Link]
Case 0
[Link] = "*.*"
Case 1
[Link] = "*.DOC"
Case 2
[Link] = "*.TXT"
End Select
End Sub
Private Sub Dir1_Change()
[Link] = [Link]
[Link] = [Link]
213
End Sub
Private Sub Drive1_Change()
On Error GoTo ErrorTrap
[Link] = [Link]
Exit Sub
ErrorTrap:
MsgBox "Drive Error", vbExclamation, "Error"
[Link] = [Link]
Exit Sub
End Sub
Private Sub File1_Click()
[Link] = [Link]
End Sub
Private Sub Form_Load()
[Link] "All Files(*.*)"
[Link] "Doc Files(*.DOC)"
[Link] "Text Files(*.TXT)"
[Link] = 0
[Link] = [Link]
End Sub
Private Sub Label5_Click()
End
End Sub
214
End Sub
After that the project get run displays the output as
follows.
Fig. F.8.2.2
215
number being [Link] Example, The Number 17 is
stored as two separate characters "1" and "7" which
means that 17 is stored as [49 55] and not as [17].
In the Binary Mode, everything is written and
retrieved as a Number. Hence, The Number 17 will be
stored as [17] in this mode and characters will be
represented by their ASCII Value as always.
One major difference between Text Files and
Binary Files is that Text Files support Sequential
Reading and Writing. This means that we cannot read
or write from a particular point in a file. The only way
of doing this is to read through all the other entries
until you reach the point where you want to 'actually'
start reading. Binary Mode allows us to write and read
anywhere in the file. For example we can read data
directly from the 56th Byte of the file, instead of
reading all the bytes one by one till we reach 56.
Just like the Binary Mode, the Random Access
Mode allows us to gain instant access to any piece of
information lying anywhere in the file at a cost.
In this case, we must standardize each piece of
information. For example, if we need to store a few
names in the file Random Access Mode requires us to
mention the length of the 'Names' Field.
Some Names might not fit and for the shorter names
the space is inefficiently used. Random Access Mode
allows us to read or write data at a particular record
position rather than a byte position like in Binary
Mode.
A Good Example of Sequential Mode is the Audio
216
[Link] we have tolisten to a particular Song in the
cassette, we have to play the tape right from the
beginning until we reach the beginning of the song.
And so obviously, CDs, DVDs etc. are examples of
Binary Mode.
217
in the current directory.
To close the file we use the CLOSE Command like
this:
Close #1
This Closes the File referred to by File Handle 1. The
Close Command can also be called with no arguments,
but in this case it would close all open Files.
For the rest of this section, assume the [Link] file
to contain the following data:
"Sanchit",9811122233
"Friend",9812345634
"Enemy",9821630236
Now let try to read from this file. We can read each
line separately into a string by using the Line Input
Command. Take a look at this snippet:
Dim tmp as String
Open "C:\[Link]" For Input as #1
Line Input #1, tmp
Close #1
Msgbox tmp
As you can see, the MessageBox displays:
“Sanchit”,9811122233
The Line Input Command extracts the line currently
pointed to by the File Pointer (this happens internally)
into a string. If we add another Line Input Command
after the first, the MessageBox willdisplay: "Friend",
9812345634. We can now write a Program that
displays the entire contents of a file in a MessageBox,
using the Line Input Command.
Dim tmp as String, contents as String
218
Open "C:\[Link]" For Input as #1
While Eof(1) = 0
line input #1,tmp
contents = contents + tmp
Wend
Close #1
Msgbox contents
The Output is:
"Sanchit",9811122233"Friend",9812345634"Enemy",
9821630236
The Eof() Function determines if the End of the
specified file has been reached.
If you look at the original file, there are newline
characters after every entry. But when we use Line
Input or any other Sequential Mode Function, the
Newline character is never considered. Hence the
Output shown is without the Newline Characters.
Now what if we wanted to separate the two fields and
store the Name and Phone Number into two variables,
we use with the help of the Input #<File> Command.
SYNTAX :
Input#<file_handle>,<var1>,[var2],…[varN]
To use the Input# Command, we must know the exact
number and type of fields present in a data file.
Remember that in case the argument types are
mismatched, it results in an Error.
As we have seen earlier, there are two modes for
writing data into a file, OUTPUT mode
and APPEND [Link] OUTPUT Mode creates a
new file irrespective of whether a file with the
219
samename exists or not. In other words, If no file by
the specified filename is present, a new file is created
else the previous file is overwritten.
The APPEND Mode does exactly what the OUTPUT
Mode does but with a difference. It can also create a
file if it doesn't exist in the directory. But if the file is
present, it adds data (provided by the programmer) to
the end of the file. This means that we can add new
information without destroying the information that
was present before. This mode can be used in a Web-
Access Logger Program. Everytime a User accesses
a webpage, the program can add the visitor's IP
Address to a given file. If the OUTPUT Mode was
used in this case, only the most recent visitor's IP
Address would be stored in the file.
220
My Phone number is 12345678 910
"My Phone number is 12345678",910
With Print#, what appears in the file would be the
exact image of what would appear on the screen (i.e.
No quotes around strings and no commas)In this case
the file will contain the string: "My Phone number is
12345678" followed by 2 spaces, numeral 9, numeral
1, numeral 0, another space followed by two
characters (0xD 0xA) That make up the Carriage
Return/Line Feed Combination.
The Write# Command Writes Strings into the File
with the Quotes, Numbers as they are and separates
different fields by using a comma. It is good practice
to use this command instead of Print# since the Input#
Command is able to separate Records into Fields from
Records that are written by the Write# Command. (It
can work with Print# too, but it requires additional
code and yet may not work as expected)
We must remember one important thing about Print#
and Write#. After every Print#
or Write# Command, the respective command
automatically inserts a Carriage
Return/Line Feed Characters (0xD 0xA) and hence
every subsequent Write# or Print#
Command will write data to the next line in the file. If
you wish to write data
on the same line in the file, add it to the same
Print#/Write# Command.
Example:
Write #1,"ABCD"
221
Write #1,123
Write #1,"ABCD",123
OUTPUT:
"ABCD"
123
"ABCD", 123
Write# has a major advantage over Print# when it
comes to Storage of Strings. In the previous example,
the string:"My Phone number is 12345678" was stored
as "My Phone number is 12345678 " (with two
additional spaces) by using Print#. Sometimes 7
Additional Spaces are stored, at times 3 or 5 and the
number varies with each string. Hence it becomes
difficult to figure out if the 'additional' spaces are
actually a part of the string or are added by VB itself.
This also makes it difficult to separate a record into
different fields. The Write# Command on the other
hand stores the entire string within quotes, so there is
no doubt about the content as well as the length of the
string.
• FreeFile()
DESCRIPTION : Returns an Integer representing the
next file number available for use by the Open
statement.
SYNTAX : FreeFile[(rangenumber)]
The optional range number argument is a Variant that
specifies the range from which the next free file
222
number is to be returned. Specify a 0 (default) to
return a file number in the range 1 – 255, inclusive.
Specify a 1 to return a file number in the range 256 –
511.
223
The required filenumber argument is an Integer
containing a valid file number.
USE: LOF() is used to find the length of a file when a
file is
currently open.
• Seek()
DESCRIPTION : Returns a Long specifying the
current read/write position
within a file opened using the Open statement.
SYNTAX : Seek(filenumber)
The required filenumber argument is an Integer
containing a valid file number.
USE : Seek() is used to get the Byte Position where
the Next Operation will take place.
SEQUENTIAL FILE HANDLING EXAMPLES
Example 1: Getting the Number of Lines in a File.
Dim counter As Long, tmp As String
counter = 0
Open "c:\names_database.txt" For Input As #1
While Not EOF(1)
Line Input #1, tmp
counter = counter + 1
Wend
Close #1
MsgBox counter ' Outputs the Number of Lines
' in a File.
Example 2: Deleting a Record From a File (Using
Delete...Rename Method)
ASSUMPTION : The File [Link] contains:
"Sanchit", "Karve"
224
"ABCD", "PQRS"
"Steve", "Jackson"
"XYZ", "DEF"
CODE:
225
Dim file_length As Long, i as Long
strdelstring = "Steve"
file_length = 0
Open "C:\[Link]" For Input As #1
226
Next i
Close #1
Example 4: Storing/Reading a User Defined Type
in a String
STORING:
Dim x As Student, y As Student
[Link] = "Nerd"
[Link] = 18
[Link] = "A+"
[Link] = "Dunce"
[Link] = 18
[Link] = "F"
Open "c:\[Link]" For Output As #1
Write #1, [Link], [Link], [Link]
Write #1, [Link], [Link], [Link]
Close #1
READING:
Dim x As Student, y As Student
Open "c:\[Link]" For Input As #1
Input #1, [Link], [Link], [Link]
Input #1, [Link], [Link], [Link]
Close #1
MsgBox [Link] + " " + Str([Link]) + " " + [Link]
MsgBox [Link] + " " + Str([Link]) + " " + [Link]
227
major difference between Text Files and Binary Files
is that Text Files support Sequential Reading and
Writing. This means that we cannot read or write from
a particular point in a file. The only way of doing this
is to read through all the other entries until you reach
the point where you want to 'actually' start reading.
Binary Mode allows us to write and read anywhere in
the file. For example we can read data directly from
the 56th Byte of the file, instead of reading all the
bytes one by one till we reach the 56th byte.
Let us start with a very simple example:
'Add a Command Button with name as Command1
onto a Form
Private Sub Command1_Click()
Dim f As Long
f = FreeFile()
Open "c:\[Link]" For Binary As #f
Close #f
End Sub
As you can see, the FreeFile() function can also be
used for binary files. The Open Statement opens
c:\[Link] in Binary Mode and the next statement
closes the file.
As obvious as it may sound, you need to open a file
before using it and close it when you have finished
reading or writing to it. Many programmers forget to
add the Close statement which results in the File
Already Open Error, and it can be a pain to track down
the exact location that caused the error when you're
dealing with many files.
228
You should note that this snippet does more than open
and close a file. If the [Link] file is not present in C
drive, then it creates a blank file with the same name.
8.3.2 READING AND WRITING IN BINARY
MODE
Now that you know how a file is opened, let us see
how we can read and write data in Binary mode.
Here's an example which writes a string in a Binary
File.
'Create a Command Button as Command1
Private Sub Command1_Click()
Dim f As Long
f = FreeFile()
Open "C:\[Link]" For Binary As #f
Put #f, , "This is the Test file."
Close #f
End Sub
The string "This is the Test file." is written to the
[Link] file in the C drive. The Put Statement is used to
write data to a binary file. The Syntax of Put is as
follows:
Put #fileNumber, [startByte], varName
where
#fileNumber = A file handle ('f' is the file handle in the
previous example)
startByte = (Optional) Byte position to start writing at.
varName = Variable/Literal whose contents are to be
written. varName can be a variable of any data type. In
the above example, we have skipped the second
parameter which means that the string is written at the
229
current position of the file, which in this case is the
beginning of the file.
We can choose to write data at a different position by
specifying this [Link] the Put Statement
from the previous example to Put #f,13,”B” .
Now if we run the program and then open the [Link]
file. Now the file contains the content as "This is the
Best file." The Put statement in this case writes "B" at
the 13th byte in the file. We can see that the 13th
position in the file is the letter "T". Hence "T" gets
replaced by "B".
A logical opposite of Put is Get, and that's what you'll
need to use to read data from a Binary File.
Private Sub Command1_Click()
Dim f As Long
Dim x As Byte
f = FreeFile()
Open "C:\[Link]" For Binary As #f
Get #f, , x
Close #
MsgBox x
End Sub
This will display 84 (ASCII Value of T) in a Message
Box. The syntax of the Get Statement is exactly the
same as that of the Put statement. Experiment with the
second parameter and notice how you get ASCII
values of the elements.
Let's try to read in the first word of the file. We know
that the first word is"This", so we'll create a Byte
Array of length 4 like this:
230
Private Sub Command1_Click()
Dim f As Long
Dim x(3) As Byte 'Creates Array from Index 0 to 3
Dim readresult As String
f = FreeFile()
Open "C:\[Link]" For Binary As #f
Get #f, , x
Close #f
readresult = Chr(x(0)) & Chr(x(1)) & Chr(x(2)) &
Chr(x(3))
MsgBox readresult
End Sub
Visual Basic will automatically fill in every element of
the array x until it can't store any more. So it starts
from the first position (2nd parameter is not specified)
and copies the first 4 characters into the Byte Array x.
Since the array x is of data type Byte, we need to
convert it to a string and then display it as shown.
Private Sub Command1_Click()
Dim f As Long
Dim readresult As String
f = FreeFile()
Open "C:\[Link]" For Binary As #f
Get #f, , readresult
Close #f
MsgBox readresult
End Sub
The output of this code is totally unexpected. It is null.
The Message Box doesn't display anything. Because
the Get statement automatically detects the length of
231
the string and fills up data into the variable till it store
any more.
The length of the readresult string is zero because
nothing is stored in it initially, and hence nothing will
be stored in it after the Get statement. To get the code
to work as expected, we need to specify the length of
the string by either defining it as a fixed-length string
or initializing it to a string of non-zero length.
We can either define the string as a fixed-length string
like this:
Dim readresult As String * 4
or initialize the string to something with its length as
4 like this:
Dim readresult As String
readresult = String(4, " ") ' or even readresult =
"ABCD"
Now, make the appropriate changes in the previous
example and run the program. The Message Box
should display "This".
232
access file has a very definite structure. A random access
file is made up of a number of records, each record
having the same length (measured in bytes). Hence, by
knowing the length of each record, we can easily
determine (or the computer can) where each record
begins. The first record in a random access file is Record
1, not 0 as used in Visual Basic arrays. Each record is
usually a set of variables, of different types, describing
some item. The structure of a random access file is:
Record 1
Record N
Record 2
Record N
Record 3
Record N
.
.
Record Last
N Bytes
233
require all of our random access records to be the same
length - not a good choice on CD’s!
To write and read random access files, we must know the
record length in bytes. Some variable types and their
length in bytes are:
Type Length (Bytes)
Integer 2
Long 4
Single 4
Double 8
String 1 byte per character
So, for every variable that is in a file’s record, we need to
add up the individual variable length’s to obtain the total
record length. To ease this task, we introduce the idea of
user-defined variables.
user-defined variables
Data used with random access files is most often stored
in user-defined variables. These data types group
variables of different types into one assembly with a
single, user -defined type associated with the group.
Such types significantly simplify the use of random
access files. The Visual Basic keyword Type signals
the beginning of a user-defined type declaration and the
words End Type signal the end. An example best
illustrates establishing a user-defined variable. Say we
want to use a variable that describes people by their
name, their city, their height, and their weight. We
would define a variable of Type Person as follows:
Type Person
Name As String
234
City As String
Height As Integer
Weight As Integer
End Type
To create variables with this newly defined type, we employ
the usual Dim statement. For our Person example, we
would use:
Dim Lou As Person
Dim John As Person
Dim Mary As Person
And now, we have three variables, each
containing all the components of the variable type
Person. To refer to a single component within a user-
defined type, we use the dot-notation:
[Link]
As an example, to obtain Lou’s Age, we use:
Dim AgeValue as Integer
.
.
AgeValue = [Link]
Note the similarity to dot-notation we’ve been using to set
properties of various Visual Basic tools.
Writing and Reading Random Access Files
We look at writing and reading random access
files using a user -defined variable. For other variable
types, refer to Visual Basic on-line help. To open a
random access file named RanFileName, use:
Open RanFileName For Random As #N Len =
RecordLength
where N is an available file number and RecordLength is
235
the length of each record. Note you don’t have to specify
an input or output mode. With random access files, as long
as they’re open, you can write or read to them.
To close a random access file, use: Close
As mentioned previously, the record length is the
sum of the lengths of all variables that make up a record. A
problem arises with String type variables. You don’t
know their lengths ahead of time. To solve this problem,
Visual Basic lets you declare fixed lengths for strings. This
allows you to determine record length. If we have a string
variable named StrExample we want to limit to 14
characters, we use the declaration:
Dim StrExample As String * 14
Recall each character in a string uses 1 byte, so the length
of such a variable is 14 bytes. Recall our example user-
defined variable type, Person. Let’s revisit it, now with
restricted string lengths:
Type Person
Name As String * 40
City As String * 35
Height As Integer
Weight As Integer
End Type
The record length for this variable type is 79 bytes
(40 + 35 +2 + 2). To open a file named PersonData as
File #1, with such records, we would use the statement:
Open PersonData For Random As #1 Len = 79
The Get and Put statements are used to read from and
write to random access files, respectively. These
statements read or write one record at a time. The
236
syntax for these statements is simple:
Get #N, [RecordNumber], variable
Put #N, [RecordNumber], variable
The Get statement reads from the file and stores data in
the variable, whereas the Put statement writes the
contents of the specified variable to the file. In each case,
you can optionally specifiy the record number. If you do
not specify a recordnumber, the next sequential position is
[Link] variable argument in the Get and Put statements
is usually a single user- defined variable. Once read in,
you obtain the component parts of this variable using dot-
notation. Prior to writing a user-defined variable to a
random access file, you ‘load ’ the component parts using
the same dot-notation.
There’s a lot more to using random access files;
we’ve only looked at the basics. Refer to your Visual
Basic documentation and on-line help for further
information. In particular, you need to do a little cute
programming when deleting records from a random
access file or when ‘resorting’ records.
237
UNIT V
[Link] CONTROLS IN VB
Memory Organization: Memory Hierarchy –Main
Memory-Associative memory: Hardware
Organization, Match Logic, Read Operation, Write
Operation. Cache Memory: Associative, Direct, Set-
associative Mapping –Writing into Cache
Initialization.
9.1 INTRODUCTION
The Advanced Visual Basic toolbox controls and
teaches the end users how to use them to build useful
interface features. In this introduction part, the end
users will learn how to:
• Name Visual Basic objects.
• Use basic controls to display text and process input.
• Use file system controls to browse the files and
folders on your computer.
• Use data input controls to display lists and check
boxes.
238
elements, such as command buttons, image boxes, and
list boxes.
Object
An object is a type of user interface element you create
on a Visual Basic form by using a toolbox control. (In
fact, in Visual Basic, the form itself is also an object.)
You can move, resize, and customize objects by
setting object properties. Objects also have what is
known as inherent functionality — they know how to
operate and can respond to certain situations on their
own. (A list box “knows” how to scroll, for example.)
You can customize Visual Basic objects by using
event procedures that are fine-tuned for different
conditions in a program.
Property
A property is a value or characteristic held by a Visual
Basic object, such as Caption
or
Fore Color
Properties can be set at design time by using the
Properties window or at run time by using statements
in the program code. In code, the format for setting a
property is:
Object. Property = Value
Where,
Object is the name of the object you’re customizing.
Property is the characteristic you want to change.
Value is the new property setting.
For example,
[Link] = "Hello"
239
Could be used in the program code to set the Caption
property of the Command1 object to “Hello”.
Event Procedure
An event procedure is a block of code that runs when a
program object is manipulated.
For example, clicking the first command button in a
program executes the Command1_Click event
procedure. Event procedures typically evaluate and set
properties and use other program statements to
perform the work of the program.
Program Statement
A program statement is a combination of keywords,
identifiers, and arguments in the code that does the
work of the program.
Visual Basic program statements create storage space
for data, open files, perform calculations, and do
several other important
tasks.
Method
A method is a special keyword that performs an action
or a service for a particular program object. In code,
the format for using a method is,
Object. Method Value
Where,
Object is the name of the object you are working with.
Method is the action you want the object to perform.
240
Value is an optional argument to be used by the
method.
For example, this statement uses the
Add Item method to put the word Check in the List1
List box:
[Link] "Check"
Variable
A variable or identifier is a special container that holds
data temporarily in a program.
You create variables to store calculation results, create
file names, process input, and so on. Variables can
store numbers, names, property values, and references
to objects.
Naming Visual Basic Objects
You may be a Visual Basic beginner now, but that
won’t be true for long. As your programs increase in
size and sophistication, the number of objects you use
on your forms will multiply quickly. There is an easy
way to avoid mistaking one object for another in the
Properties window or in your program code: assigning
a unique name to each object soon after you creates it.
It’s simple — when you set your other object
properties, just click the (Name) property, and then
givethe object a unique name.
Syntax
241
[Link] [ = tabnumber ]
The Tab property syntax has these parts:
242
TabCaption Property (SSTab Control)\
Syntax
[Link](tab) [ = text ]
The TabCaption property syntax has these parts:
243
ampersand is displayed in the caption and no
characters are [Link] example adds or
removes an extra word from the tabs of an SSTab
control that lists the defensive players of a sport on one
tab and the offensive players on another tab. By
clicking the CheckBox control on the Form, the user
can togglebetween longer captions or shorter ones.
Syntax
[Link](tab)[ = boolean ]
The TabEnabled property syntax has these parts:
244
Part Description
Syntax
[Link] [= integer]
[Link] [= integer]
The TabFixedHeight and TabFixedWidth properties
syntax has these parts:
245
The TabFixedHeight property applies to all Tab
objects in the TabStrip control. It defaults either to the
height of the font asspecified in the Font property, or
the height of the ListImage object specified by the
Image property, whichever is higher,plus a few extra
pixels as a border. If the TabWidthStyle property is set
to tabFixed, and the value of the TabFixedWidth
property is set, the width of each Tab object remains
the same whether you add or delete Tab objects in the
control.
246
Tab Index Property
Returns or sets the tab order of most objects within
their parent form.
Syntax
[Link] [= index]
The TabIndex property syntax has these parts:
247
The TabIndex property isn't affected by the ZOrder
method. Note A control's tab order doesn't affect its
associated access key. If you press the access key for a
Frame or Label control, the focus moves to the next
control in the tab order that can receive the focus.
When loading forms saved as ASCII text, controls
with a TabIndex property that aren't listed in the form
description are automatically assigned a TabIndex
value. In subsequently loaded controls, if existing
TabIndex values conflict with earlier assigned values,
the controls are automatically assigned new values.
When you delete one or more controls, you can use the
Undo command to restore the controls and all their
properties except for the TabIndex property, which
can't be restored. TabIndex is reset to the end of the
tab order when you use [Link] example reverses
the tab order of a group of buttons by changing the
TabIndex property of a command button array. To try
this example, paste the code into the Declarations
section of a form that contains four CommandButton
controls. Set the Name property to CommandX for
each button to create the control array, and then press
F5 and click the form to reverse the tab order of the
buttons.
248
For I = 0 To 3
CommandX(I).Caption = X ' Set caption.
CommandX(I).TabIndex = X - 1 ' Set tab order.
If CommandX(0).TabIndex = 3 Then
X = X - 1 ' Decrement X.
Else
X = X +1 ' Increment X.
End If
Next I
End Sub
249
dynamically create a checkbox on the form at run time.
More on that in a few minutes. First,We need to tell
Visual Basic that the Checkbox is a member of a
Control Array---I do that merely by changing its Index
property from the default blank value to a number---in
this case 0.
250
Check1(1).Caption = "New Checkbox"
End Sub
Load Check1(1)
251
Private Sub Command1_Click()
Load Check1(1)
Check1(1).Caption = "New Checkbox"
Check1(1).Visible = True
End Sub
The code:
252
Check1(1).Top=Check1(0).Top + Check1(0).Height
253
way, at run time, the controls are created and
seemingly out of no [Link] review, here’s a
summary of the steps necessary to create a new control
using the Control Array method.
254
In short, each control that is placed on the form either
at Design time or runtime is made a member of the
intrinsic Visual Basic Collection called the Controls
Collection. For those of you not familiar with Visual
Basic Collections, a Collection is similar to a one
dimensional array.
Each control on the form has a reference placed on the
Controls collection when it is placed there at design
time. In the same way, a control that is placed on the
form at run time (the way we just did using the Control
Array Method) also has a reference placed on the
Controls Collection.
It's also possible to create a control at runtime by
adding a reference to a control directly to the Controls
Collection. Doing so avoids the necessity of first
having to create a 'template' control on the form at
design time---the reason for that is that VB maintains
templates for all of the controls in the hidden Visual
Basic Global Object called VB(again, more on this in
my Objects Book).Suffice to say that all that is
required to create a control at runtime using this
method is to execute four lines of code, like this…
255
This line of code
Dim ctlName As Control
[Link] = True
[Link] = Check1(0).Top + Check1(0).Height
256
The Add Method has three arguments---the first is the
name of the template for the control you are creating,
the second is the name of the control as it will appear
in the Controls Collection, and the third argument is
the control's container (ordinarily the form, but it could
be the name of a Frame Control if you wanted the
control to be placed'within' a Frame on the form).The
Textbox control is called Textbox, the Command
Button control is called CommandButton. If you open
the Visual Basic Object Browser (View-Object
Browser from the Visual Basic Menu Bar) and select
the VB Global Object in the library listbox.
257
Again, for more information on the Visual Basic
Object Browser, check out my Objects [Link] we now
run the program, and click on the command button,
we'll see this screenshot.
258
Included with the Microsoft Windows common
controls meaning, part of the file Comet132.0cx—is a
TabStrip control. The Microsoft TabStrip control
works differently from the SSTab control. In my
opinion, it is not as user-friendly as the SSTab:
Code is required to make it work. Instead of having
access to individual tab pages at design time as with
the SSTab control, you must manipulate the TabStrip
pages with code at runtime. This means that you have
to place all control containers on what appears to be
the first tab page of the TabStrip control as shown in
the below figure. From there, using code, you can re-
size the containers to fit the client area of the tab page
and bring the correct container to the front using the
ZOrder method.
259
An example of a working TabStrip control with
picture box containers is available on the companion
CD-ROM as [Link]. Here's how to get the
TabStrip control to work. Start a new project and add a
TabStrip to a form, sizing it as you wish. Open the
TabStrip Control Properties windows found under the
Custom property and move to the Tabs tab page to set
up three tab pages. On the Tabs tab page enter a
caption for the first tab page, and then press the Insert
Tab button to create a second tab page. Enter a caption
for this tab page, and then create a third tab page by
again pressing the Insert Tab button. Add a caption for
that tab page, and then click OK to close the Properties
window. Add an array of three picture box controls to
act as containers to the TabStrip control, as shown
back in Figure 8-6. Add a different check box to each
picture box, and then open the form's Code window.
Add the following code to the form's Load event to
size the picture control array to cover the client area of
the tab control and set the first picture control on top:
260
End Sub
Then, add a line of code to the TabStrip's Click event
to bring the correct picture control to the front when
the user changes tab pages:
Private Sub tabSundae_Click()
picContainer(tabDemo.SelectedItemAndex1).Z0rder 0
End Sub
Run the demonstration application now and see how
the picture boxes are resized and correctly brought to
the front when a specific tab page is selected.
Creating a Wizard
261
3. Plan the number of panels you'd like and the
number of controls that will appear on each panel.
4. Open the [Link] code module in the Code
Editor. Find the SetUpWiz procedure. It will look like
this:
Private Sub SetUpWiz()
'Panel 1
ItemsInPanel 0
'Panel 2
ItemsInPanel 0
'Panel 3
ItemsInPanel 0
End Sub
The number of calls to ltemslnPanel represents the
number of panels in the Wizard; the argument passed
to ItemsInPanel tells the Wizard how many controls
are on that panel. The user needs to change the code to
reflect your particular Wizard. For example, if you
wanted to create a four –panel Wizard with two
controls on each panel, you would change SetUpWiz
to read as follows:
Private Sub SetUpWiz()
'Panel 1
ItemsInPanel 2
'Panel 2
ItemsinPanel 2
'Panel 3
ItemsInPanel 2
'Panel 4
ItemslnPanel 2
262
End Sub
5. Next, add the controls you'd like to the [Link].
The Wizard manages the visibility and invisibility of
these controls through their Tag properties, so it's
important that you set .Tag correctly. The first control
you add should have its .Tag property set to 5. (This
value is one more than the number of Wizard common
controls. Four controls appear on every panel: three
buttons and a line.)
The second control should have its .Tag property set to
6, and so on. You must set the Tag properties so the
panels are managed properly. In the example with two
controls per panel, the controls should have Tag
properties as shown in Table 8-2.
Table 8.2 Tag Properties for Controls on a Four-Panel
Wizard with Two Controls per Panel
263
Public Sub ShutDown()
MsgBox "Doing what has to be done with values and
stuff...ending!"
Unload ThisWizard
End
End Sub
264
Whenever you are doing any project, always a need
arises where you have to display the Data in a Tabular
Format. There are several Controls in VB6 Which can
take care of such displays. But, I have always found
MSFlexGrid come in handy. As the name itself
suggests, it is really a Flexible Grid. There are 2 ways
to display the Data in FlexGrid :
• DataBinding
• Manually
• EmpNo (Numeric)
• EmpName (Text(100))
• DOJ (Date)
• BasicSalary (Number)
• Allowances (Number)
Say, you have all the data loaded in the database. First
of all, Open a New Project Add this in Reference as
Microsoft Active-X Data Objects Library 2.0• (or any
265
higher version if u have.).
Now to Add MSFlexGrid: Goto Menu
Project>Components, Select MSFlexGrid Control 6.0.
Check it and Click [Link] the Grid will be loaded in
the ToolBox. Add the MSFlexGrid Control to your
Form and Rename it.
'Open the Connection say “AConn”•, Declare a
[Link] Object say RST. And query the
EmpMaster Table:
266
If Not [Link] Then
[Link]
Do While Not [Link]
i=i+1
Rows = i + 1
.TextMatrix(i, 0) =RST(“EmpNo”) & “ “
.TextMatrix(i, 1) =RST(“EmpName”) & “ “
.TextMatrix(i, 2) =RST(“DOJ”•) & “ “
.TextMatrix(i, 3) =RST(“BasicSalary”•) & “ “
.TextMatrix(i, 4) =RST(“Allowances”•) & “ “•
TCurr = Val(RST(“BasicSalary”) & “ “) ) +
Val(RST(“Allowances”•) & “ “•) .TextMatrix(i, 5) =
TCurr
[Link]
Loop
End If
End With
267
[Link] DATA OBJECT (ADO)
10.1 WHY ADO?
ActiveX Data Objects expose their properties by
means of COM interfaces; they can be accessed by
any language that can utilize COM. In this chapter we
will discuss how to access ADO from Visual Basic.
ActiveX Data Objects (ADO) is an application
program interface from Microsoft that lets a
programmer writing Windows applications get access
to a relational or non-relational database from both
Microsoft and other database providers. For example,
if you wanted to write a program that would provide
users of your Web site with data from an IBM DB2
database or an Oracle database, you could include
ADO program statements in an HTML file that you
then identified as an Active Server Page. Then, when a
user requested the page from the Web site, the page
sent back would include appropriate data from a
database, obtained using ADO code.
ActiveX Data Objects (ADO) is a collection of
software components providing a programmatic
268
interface to access the data sources from client
applications. ADO acts as a layer to access any data
store in a generic way from the application code. It
eliminates the need to possess the knowledge of
database implementation and reduces the complexity
of dealing with the low level code needed to handle
the data.
269
understand and excellent for both beginners and
advanced developers.
270
When redistributing ADO applications, you should use
MDAC redistributable package available for download
from Microsoft‘s website.
271
Dim con As [Link]
272
If you know for a fact that no other class library listed
in the References dialog box of your current Visual
Basic application has the same class name as ADO,
you may remove the ADODB prefix when declaring
and instantiating object variables. However, if you are
using more than one object model with the same class
definitions, not specifying the library that comes first
in the list of references to the project.
273
place a list box named 1stAuthor on the form at design
time.
274
‘ create two strings to define the connection and the
recordset
Dim sConString As String
Dim sSQL String As String
‘ Create list box control
Set lstAuthors =[Link](“[Link]”,
_“lstAuthors”, _ Me)
[Link] = True
Do Until ([Link])
[Link] rst(“Author”).Value
[Link]
Loop
[Link] “Getting data now...”
Do Until ([Link])
[Link] rst (“Author”).Value
275
[Link]
Loop
[Link] “End of data.”
‘ Close and remove the Recordset object from memory
[Link]
Set con =Nothing
[Link] “Closed and removed ” _ & “Recordset
object from memory.”
‘close and remove the Connection object from
memory.”
[Link]
Set con= Nothing
[Link] “Closed and removed” _ & “Connection
object from memory.”
End Sub
Private Sub Form_Resize()
‘ this code is added for asthetics
[Link] =0
[Link] =0
[Link] =[Link]
[Link] =[Link]
End Sub
276
Referencing the Type Library
277
1. From the Visual Basic Menu Bar, find the
References menu item. Depending on the version of
Visual Basic that you are running, this is either under
the Project (VB6) or under the Tools (VBA) menu.
278
you will see that these libraries have been moved up to
the top of the list with the other referenced libraries.
The base SAS IOM library name is "sas". You can use
this to qualify any identifier defined in that library. For
example, the base SAS library has a FormatService
component. If another library in your application has
its own identifier with the same name, then you would
reference the SAS component by using
[Link].
279
Object Browser is typically available via a toolbar
icon, a menu selection or the F2 key.
280
for the selected item. In the editor, if you press F1 with
your cursor on a name, you will get help for that name.
281
"FinanceDept") given to you by your system
administrator. Please see SAS Workspace Manager for
more information on creating workspaces on remote
servers.
282
CreateWorkspaceByServer method for creating a new
workspace.
283
property of the object variable and set that default
property. This is very different than assigning an
object reference to the variable itself.
284
to reference your workspace’s FileService. The
declaration would be:
285
After you create an object variable and set it with an
object reference, you can make calls against the object
and access the object’s properties.
286
' Should print "mysaslib"
[Link] [Link]
287
When passing parameters, you must first understand
whether the parameter is for input or output (also
known as ByVal and ByRef in Visual Basic).
Unfortunately, the Visual Basic Object Browser does
not provide this information. In many cases,
understanding the role of the parameters will make it
obvious. For example, the Libname string passed to
DeassignLibref is used by that method to know which
Libref to deassign but the method does not update the
parameter. Thus, it is an input parameter. If you are
not sure which type of parameter is required, then you
can consult the Help or documentation to find out.
288
actually defines for that parameter, make sure that you
understand Visual Basic’s data conversion rules.
289
For example, if you want to open a stream for writing,
you would pass a constant of
[Link].
290
minimum. This means that many IOM methods have a
large number of parameters and accept arrays for those
parameters. Visual Basic Intellisense technology is
very helpful for keeping track of parameters as your
code them. The next section describes how to pass
arrays in Visual Basic method calls.
291
declared with the Redim statement is dynamic. For
array output parameters you must use dynamic array
variables because the size that SAS will return is not
known when the array variable is declared.
292
' Print each name in the returned array
For Each vName in arLibnames
[Link] vName
Next vName
' Print the size of the array
[Link] "Number of librefs was: " &
Ubound(arLibnames)+1
[Link]
293
each dimension In order to allow better compatibility
with other client programming languages, all IOM
calls require that the lower bound be zero. Input arrays
will not be accepted if their lower bound is not zero.
Output arrays will always be returned with a lower
bound of zero.
Dim table()
294
When passing input arrays, you can pass a fixed size
array if you know the size in advance. The following
code provides an example:
' Create a workspace on the local machine using
the Workspace Manager
Dim obWSMgr As New
[Link]
Dim obWS As [Link]
Dim errString As String
Set obWS =
[Link]("
My workspace", VisibilityNone, Nothing, "", "",
errString)
295
' Get up to 1000 lines of output
[Link] 1000, arCC, arLT, arList
' Print each name in the returned array
For Each vOutLine in arList
[Link] vOutLine
Next vOutLine
[Link]
296
Notes on Using Enumeration Types in Visual Basic
Programs
297
arLT(0) = LanguageServiceLineTypeSource
Object Lifetime
You should use the [Link] method to close
a workspace when you are done with it. This will also
delete all objects within the workspace. For some
types of objects, such as streams, you can be done with
the object long before you are done with the
workspace. These objects typically have their own
Close method which removes the object and performs
other termination processing (such as closing the file
against which the stream is open). The lifetime of
objects that do not have a Close (or similar) method, is
managed by the Workspace in which the object is
created.
298
being left on a machine when clients fail to close their
workspaces properly. If a client program terminates
abruptly or is killed by the user from the Task
Manager, then COM notifies SAS of this at a later
time. In current versions of COM this takes about six
minutes.
Exceptions
299
Different errors are assigned different codes. IOM
method calls can return many different codes. The
code that they return are listed in various enumerations
whose names end in "Errors". For example, the IOM
DataService defines an enumeration called
DataServiceERRORS in which the constants for all of
the possible errors returned by the DataService are
defined. The documentation and on-line help show the
errors that a particular call is most likely to raise. In
addition to those listed explicitly for the method,
[Link] is always possible.
Receiving Events
300
definitions for the event procedures. The following
code segment is a definition that is provided for the
ProcStart event, along with a line that has been added
to print a debug message tracing the start of the
procedure.
Private Sub obLS_ProcStart(ByVal Procname As
String)
[Link] "Starting PROC: " & Procname
End Sub
301
report on paper first to make sure your design is
clear.
Crystal
Mod- Reports
Query Export for
ule
Blackbaud
302
11.1 CREATING AN EXPORT FILE
Before you design and create your report, you need
to decide what kind of information you want to
display. What fields do you need from The Raiser’s
Edge to generate the correct data on your report?
Creating the export file is the first and most
important step. Without the correct fields in your
export, you will not be able to produce the results
you want on your report.
303
Based on your Trustee query, create an export file with
the fields Name, Home Phone, and Business Phone.
Your Director of Development wants a list of all the
current trustees and their home and business phone
numbers, if available. Use your Trustee query to
create an export file with fields Name, Home Phone,
and Business Phone. Design a custom Crystal report
displaying the trustee names in alphabetic order, with
a grand total at the bottom.
304
4. In the Export format field, select “Blackbaud Report
Writer Database (MDB)”. Selecting an .MDB file type
tells the program to format the data in a way Crystal
Report.
305
Choose the appropriate Export format as Blackbaud
Report Writer Database (MDB).
306
9. Highlight the Trustees query.
307
Home Phone, and Business Phone in your export,
you must select those fields from the tree view on the
left.
13. From the tree view on the left, in the Available
Fields to Export frame, click the plus sign next to
Biographical.
[Link] fields are in alphabetical order. Scroll down the
list and highlight Name. To move Name into the
Output box, click Select at the bottom of the screen.
308
309
15. Because you want to include Constituent Export
from the tree view on the left, in the Available Fields
to Export frame, scroll down the list and click the
plus sign next to Address. Then, click the plus sign
next to Preferred Address.
310
[Link] Select at the bottom of the screen. The
Phones screen appears.
311
.
312
21. Under Phones, highlight Phone number and
click Select. The Phones screen appears.
313
24. This completes the selections for the export. Click
Export Now in the lower right corner.
314
[Link] Save and the export processes. A screen
appears telling you the number of constituent
records exported.
[Link] OK.
[Link] the “X” in the top right corner of the
New Constituent Export screen. A message
appears, asking if you want to save the export.
[Link] Yes and name the export “Trustee Phone
List”.
315
[Link] Save. You return to the main Export page.
Report Setup
To create a new custom report in Crystal Reports, you
need to open a new blank report and attach the export
file you created to serveas the data. Once you start
building your report, only data generated in the export
file is available. You are not connected to your
Raiser’s Edge database.
Creating a new custom report
Now that you have created your export, you are ready
to start creating your new custom report and
formatting your report to create the look you want.
316
In the Create a New Crystal Report Document frame,
select As a Blank Report. The blank form is shown in
the following page.
3. 3. In the Create a New Crystal Report Document
frame, select As a Blank Report.
4. Click OK. The Data Explorer screen appears
317
[Link] the plus beside Database Files to expand the
tree view.
318
You return to the Data Explorer screen. Notice all
your database fields are listed in the tree view.
319
you avoid repeating steps if you leave intended fields
for your report behind.
320
10. Click Close. A blank Crystal report opens, with the
Vis ual Linking Expert screen on top.
321
available, along with the Field Explorer box. This
box contains all the fields you exported from The
Raiser’s Edge. You will use these fields to build your
report.
322
fields into the correct sections. For example, any field
you want the program to calculate, like Gift Amount,
must be inserted into the Details section.
Report Header. Information in this section appears
at the top of the first page of the report.
323
this report, you are working with a limited number of
fields, and you do not need to write any equations or
formulas. As you begin to insert fields onto the report,
do not be afraid to make a mistake. Because you are
working only with an export file, it is not possible to
damage your database in any way. The Raiser’s Edge
and Crystal Reports are completely separate programs.
Report Layout
324
Remember that links and identifier keys are exported
out of The Raiser’s Edge along with the fields and
data. When you look through the Field Explorer
box, make sure you insert fields onto the report, not
LINKs or IDKEYs.
325
[Link] on your report design, the first field you need
to insert is constituent name. Highlight CnBio_Name.
326
Before you add any other fields, you may need to
move or size this field to make sure it is the correct
size for the data. If the box is too small, the data will
be truncated. If the box is too large, there will be too
much blank space between field.
Sizing fields in a report
If you notice the standard length or height of a field is
too big, or not big enough to display your information
correctly, you can change the size of the field after it is
on the report.
[Link] change the length of a field, click the field once
to highlight it. Move your cursor over the small black
327
square on the right side of the highlighted rectangle
until it changes to a double arrow.
2. Maintaining the double arrow, click and drag the
rectangle to the left to shorten the field size, or to the
right to lengthen the field. For this report, shorten the
constituent name field and the attached header field to
approximately two inches.
328
Moving fields in a report
After you insert your fields into the report, you may
need to move them to get the result you want.
329
keyboard, click CnBio_Name in the Page Head
section.
2. Once both fields are highlighted, click your cursor
in one of the boxes and drag the fields together to the
new location.
330
4. On the toolbar, click the Align Centre button. The
title moves to the centre of the report.
331
Saving a report
Before you save your report, decide whether you want
to save it with your data attached or save only the
report layout.
332
Designer.
Data Report object
This is like a Visual Basic form. It contains the
visible designer and code. Code is used to control
report at runtime by responding to the events
generated by the data report. Visible designer
allows you to design the layout of the report.
Sections Collection
This is collection of section objects. A section
object represents a section of the report. You can
use section objects at runtime to reconfigure the
section. At design time each section is represented
by a header, which is used to select the section.
Data Report Controls
Data report can contain only a set of special
controls. When you are in Data Report Designer,
a different toolbox is displayed with controls that
are specific to Data Report.
333