Visual Basic 6.0 IDE Components Overview
Visual Basic 6.0 IDE Components Overview
Visual basic is initiated by using the Programs option > Microsoft Visual Basic 6.0 > Visual Basic
6.0. Clicking the Visual Basic icon, we can view a copyright screen enlisting the details of the
license holder of the copy of Visual Basic 6.0. Then it opens in to a new screen as shown in figure 1
below, with the interface elements Such as MenuBar, ToolBar, The New Project dialog box. These
elements permit the user to buid different types of Visual Basic applications.
One of the most significant changes in Visual Basic 6.0 is the Integrated Development Environment
(IDE). IDE is a term commonly used in the programming world to describe the interface and
environment that we use to create our applications. It is called integrated because we can access
virtually all of the development tools that we need from one screen called an interface. The IDE is
also commonly referred to as the design environment, or the program.
1. Menu Bar
2. Tool Bar
3. Project Explorer
4. Properties window
5. Form Layout Window
6. Toolbox
7. Form Designer
8. Object Browser
In previous versions of Visual Basic, the IDE was designed as a Single Document Interface (SDI).
In a Single Document Interface, each window is a free-floating window that is contained within a
main window and can move anywhere on the screen as long as Visual Basic is the current
application. But, in Visual Basic 6.0, the IDE is in a Multiple Document Interface (MDI) format. In
this format, the windows associated with the project will stay within a single container known as the
parent. Code and form-based windows will stay within the main container form.
1
Figure 1 Visual Basic startup dialog box
Menu Bar
This Menu Bar displays the commands that are required to build an application. The main menu
items have sub menu items that can be chosen when needed. The toolbars in the menu bar provide
quick access to the commonly used commands and a button in the toolbar is clicked once to carry
out the action represented by it.
Toolbox
The Toolbox contains a set of controls that are used to place on a Form at design time thereby
creating the user interface area. Additional controls can be included in the toolbox by using the
Components menu item on the Project menu. A Toolbox is represented in figure 2 shown below.
2
Control Description
3
Pointer Provides a way to move and resize the controls form
PictureBox Displays icons/bitmaps and metafiles. It displays text or acts as a
visual container for other controls.
TextBox Used to display message and enter text.
Frame Serves as a visual and functional container for controls
CommandButto Used to carry out the specified action when the user chooses it.
n
CheckBox Displays a True/False or Yes/No option.
OptionButton OptionButton control which is a part of an option group allows the
user to select only one option even it displays mulitiple choices.
ListBox Displays a list of items from which a user can select one.
ComboBox Contains a TextBox and a ListBox. This allows the user to select an
ietm from the dropdown ListBox, or to type in a selection in the
TextBox.
HScrollBar and These controls allow the user to select a value within the specified
VScrollBar range of values
Timer Executes the timer events at specified intervals of time
DriveListBox Displays the valid disk drives and allows the user to select one of
them.
DirListBox Allows the user to select the directories and paths, which are
displayed.
FileListBox Displays a set of files from which a user can select the desired one.
Shape Used to add shape (rectangle, square or circle) to a Form
Line Used to draw straight line to the Form
Image used to display images such as icons, bitmaps and metafiles. But
less capability than the PictureBox
Data Enables the use to connect to an existing database and display
information from it.
OLE Used to link or embed an object, display and manipulate data from
other windows based applications.
Label Displays a text that the user cannot modify or interact with.
Project Explorer
Docked on the right side of the screen, just under the tollbar, is the Project Explorer window. The
Project Explorer as shown in in figure servres as a quick reference to the various elements of a
project namely 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.
4
Figure 3 Project Explorer
Properties Window
The Properties Window is docked under the Project Explorer window. The Properties Window
exposes the various characteristics of selected objects. Each and every form in an application is
considered an object. 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 properties too. All of these properties are displayed in the Properties
Window.
Object Browser
The Object Browser allows us to browse through the various properties, events and methods that
are made available to us. It is accessed by selecting Object Browser from the View menu or
pressing the key F2. The left column of the Object Browser lists the objects and classes that are
available in the projects that are opened and the controls that have been referenced in them. It is
possible for us to scroll through the list and select the object or class that we wish to inspect. After
an object is picked up from the Classes list, we can see its members (properties, methods and
events) in the right column.
A property is represented by a small icon that has a hand holding a piece of paper. Methods are
denoted by little green blocks, while events are denoted by yellow lightning bolt icon.
Form -frm
Label-lbl
TextBox-txt
CommandButton-cmd
5
CheckBox -chk
OptionButton -opt
ComboBox -cbo
ListBox-lst
Frame-fme
PictureBox -pic
Image-img
Shape-shp
Line -lin
HScrollBar -hsb
VScrollBar –vsb
Visual basic uses building blocks such as Variables, Data Types, Procedures, Functions and Control
Structures in its programming environment. This section concentrates on the programming
fundamentals of Visual Basic with the blocks specified.
Modules
Code in Visual Basic is stored in the form of modules. The three kind of modules are Form
Modules, Standard Modules and Class Modules. A simple application may contain a single Form,
and the code resides in that Form module itself. As the application grows, additional Forms are
added and there may be a common code to be executed in several Forms. To avoid the duplication
of code, a separate module containing a procedure is created that implements the common code.
This is a standard Module.
Class module (.CLS filename extension) are the foundation of the object oriented programming in
Visual Basic. New objects can be created by writing code in class modules. Each module can
contain:
Declarations : May include constant, type, variable and DLL procedure declarations.
Procedures : A sub function, or property procedure that contain pieces of code that can be executed
as a unit.
These are the rules to follow when naming elements in VB - variables, constants, controls,
procedures, and so on:
6
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.
By default Visual Basic variables are of variant data types. The variant data type can store numeric,
date/time or string data. When a variable is declared, a data type is supplied for it that determines
the kind of data they can store. The fundamental data types in Visual Basic including variant are
integer, long, single, double, string, currency, byte and boolean. Visual Basic supports a vast array
of data types. Each data type has limits to the kind of information and the minimum and maximum
values it can hold. In addition, some types can interchange with some other types. A list of Visual
Basic's simple data types are given below.
1. Numeric
2. String
Use to store alphanumeric values. A variable length string can store approximately 4 billion
characters
3. Date
Use to store date and time values. A variable declared as date type can store both date and time
values and it can store date values 01/01/0100 up to 12/31/9999
7
4. Boolean
Boolean data types hold either a true or false value. These are not stored as numeric values and
cannot be used as such. Values are internally stored as -1 (True) and 0 (False) and any non-zero
value is considered as true.
5. Variant
Stores any type of data and is the default Visual Basic data type. In Visual Basic if we declare a
variable without any data type by default the data type is assigned as default.
Arithmetical Operators
Relational Operators
Logical Operators
8
Operators Description
OR Operation will be true if either of the operands is true
AND Operation will be true only if both the operands are true
Variables in VB 6
Variables are the memory locations which are used to store values temporarily. A defined naming
strategy has to be followed while naming a variable. 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
Declaring a variable tells Visual Basic to reserve space in memory. It is not a must that a variable
should be declared before using it. Automatically whenever Visual Basic encounters a new variable,
it assigns the default variable type and value. This is called implicit declaration. Though this type of
declaration is easier for the user, to have more control over the variables, it is advisable to declare
them explicitly. The variables are declared with a Dim statement to name the variable and its type.
The As type clause in the Dim statement allows to define the data type or object type of the
variable. This is called explicit declaration.
Syntax
For example,
It may be convenient to declare variables implicitly, but it can lead to errors that may not be
recognized at run time. Say, for example a variable by name intcount is used implicitly and is
assigned to a value. In the next step, this field is incremented by 1 by the following statement
9
Intcount = Intcount + 1
This calculation will result in intcount yielding a value of 1 as intcount would have been initialized
to zero. This is because the intcount variable has been mityped as incont in the right hand side of
the second variable. But Visual Basic does not see this as a mistake and considers it to be new
variable and therefore gives a wrong result.
In Visual Basic, to prevent errors of this nature, we can declare a variable by adding the following
statement to the general declaration section of the Form.
Option Explicit
This forces the user to declare all the variables. The Option Explicit statement checks in the module
for usage of any undeclared variables and reports an error to the user. The user can thus rectify the
error on seeing this error message.
The Option Explicit statement can be explicitly placed in the general declaration section of each
module using the following steps.
Scope of variables
10
Local Variables
A local variable is one that is declared inside a procedure. This variable is only available to the code
inside the procedure and can be declared using the Dim statements as given below.
The local variables exist as long as the procedure in which they are declared, is executing. Once a
procedure is executed, the values of its local variables are lost and the memory used by these
variables is freed and can be reclaimed. Variables that are declared with keyword Dim exist only as
long as the procedure is being executed.
Static Variables
Static variables are not reinitialized each time Visual Invokes a procedure and therefore retains or
preserves value even when a procedure ends. In case we need to keep track of the number of times a
command button in an application is clicked, a static counter variable has to be declared. These
static variables are also ideal for making controls alternately visible or invisible. A static variable is
declared as given below.
Variables have a lifetime in addition to scope. The values in a module-level and public variables are
preserved for the lifetime of an application whereas local variables declared with Dim exist only
while the procedure in which they are declared is still being executed. The value of a local variable
can be preserved using the Static keyword. The follwoing procedure calculates the running total by
adding new values to the previous values stored in the static variable value.
Function RunningTotal ( )
Static Accumulate
Accumulate = Accumulate + num
RunningTotal = Accumulate
End Function
If the variable Accumulate was declared with Dim instead of static, the previously accumulated
values would not be preserved accross calls to the procedure, and the procedure would return the
11
same value with which it was called. To make all variables in a procedure static, the Static keyword
is placed at the beginning of the procedure heading as given in the below statement.
Example
The following is an example of an event procedure for a CommandButton that counts and displays
the number of clicks made.
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.
A module level variable is available to all the procedures in the module. They are declared using the
Public or the Private keyword. If you declare a variable using a Private or a Dim statement in the
declaration section of a module - a standard BAS module, a form module, a class module, and so on
- you're creating a private module-level variable. Such variables are visible only from within the
module they belong to and can't be accessed from the outside. In general, these variables are useful
for sharing data among procedures in the same module:
You can also use the Public attribute for module-level variables, for all module types except BAS
modules. (Public variables in BAS modules are global variables.) In this case, you're creating a
strange beast: a Public module-level variable that can be accessed by all procedures in the module
12
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:
You can access a module property as a regular variable from inside the module and as a custom
property from the outside:
The lifetime of a module-level variable coincides with the lifetime of the module itself. Private
variables in standard BAS modules live for the entire life of the application, even if they can be
accessed only while Visual Basic is executing code in that module. Variables in form and class
modules exist only when that module is loaded in memory. In other words, while a form is active
(but not necessarily visible to the user) all its variables take some memory, and this memory is
released only when the form is completely unloaded from memory. The next time the form is re-
created, Visual Basic reallocates memory for all variables and resets them to their default values (0
for numeric values, "" for strings, Nothing for object variables).
A variable can have the same name and different scope. For example, we can have a public variable
named R and within a procedure we can declare a local variable R. References to the name R within
the procedure would access the local variable and references to R outside the procedure would
access the public variable.
VB procedures
Visual Basic offers different types of procedures to execute small sections of coding in applications.
The various procedures are elucidated in details in this section. Visual Basic programs can be
broken into smaller logical components called Procedures. Procedures are useful for condensing
repeated operations such as the frequently used calculations, text and control manipulation etc. The
benefits of using procedures in programming are:
13
It is easier to debug a program a program with procedures, which breaks a program into discrete
logical limits.
Procedures used in one program can act as building blocks for other programs with slight
modifications.
Sub Procedures
A sub procedure can be placed in standard, class and form modules. Each time the procedure is
called, the statements between Sub and End Sub are executed. The syntax for a sub procedure is as
follows:
arglist is a list of argument names separated by commas. Each argument acts like a variable in the
procedure. There are two types of Sub Procedures namely general procedures and event procedures.
Event Procedures
An event procedure is a procedure block that contains the control's actual name, an underscore(_),
and the event name. The following syntax represents the event procedure for a Form_Load event.
General Procedures
A general procedure is declared when several event procedures perform the same actions. It is a
good programming practice to write common statements in a separate procedure (general
procedure) and then call them in the event procedure.
The Code window is opened for the module to which the procedure is to be added.
The Add Procedure option is chosen from the Tools menu, which opens an Add Procedure
dialog box as shown in the figure given below.
14
The name of the procedure is typed in the Name textbox
Under Type, Sub is selected to create a Sub procedure, Function to create a Function
procedure or Property to create a Property procedure.
Under Scope, Public is selected to create a procedure that can be invoked outside the
module, or Private to create a procedure that can be invoked only from within the module.
We can also create a new procedure in the current module by typing Sub ProcedureName, Function
ProcedureName, or Property ProcedureName in the Code window. A Function procedure returns a
value and a Sub Procedure does not return a value.
Function Procedures
Functions are like sub procedures, except they return a value to the calling procedure. They are
especially useful for taking one or more pieces of data, called arguments and performing some tasks
with them. Then the functions returns a value that indicates the results of the tasks complete within
the function.
The following function procedure calculates the third side or hypotenuse of a right triangle, where
A and B are the other two sides. It takes two arguments A and B (of data type Double) and finally
returns the results.
A property procedure is used to create and manipulate custom properties. It is used to create read
only properties The above function procedure is written in the general declarations section of the
15
Code window. A function can also be written by selecting the Add Procedure dialog box from the
Tools menu and by choosing the required scope and type.
Property Procedures 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.
Control structures in VB
Control Statements are used to control the flow of program's execution. Visual Basic supports
control structures such as if... Then, if...Then ...Else, Select...Case, and Loop structures such as Do
While...Loop, While...Wend, For...Next etc method.
The If...Then selection structure performs an indicated action only when the condition is True;
otherwise the action is skipped.
If <condition> Then
statement
End If
The If...Then...Else selection structure allows the programmer to specify that a different action is to
be performed when the condition is True than when the condition is False.
16
e.g.: If average>50 Then
[Link] = "Pass"
Else
[Link] = "Fail"
End If
Nested If...Then...Else selection structures test for multiple cases by placing If...Then...Else
selection structures inside If...Then...Else structures.
Method 1
Method 2
e.g.: Assume you have to find the grade using nested if and display in a text box
17
[Link] = "B"
ElseIf average > 55 Then
[Link] = "C"
ElseIf average > 45 Then
[Link] = "S"
Else
[Link] = "F"
End If
e.g.: Assume you have to find the grade using select...case and display in the text box
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
Note: In this example I have used a message box function. In later lessons you will learn how to use
message box functions.
18
Loop structure
A repetition structure allows the programmer to that an action is to be repeated until given condition
is true.
The Do While...Loop is used to execute statements until a certain condition is met. The following
Do Loop counts from 1 to 100.
A variable number is initialized to 1 and then the Do While Loop starts. First, the condition is
tested; if condition is True, then the statements are executed. When it gets to the Loop it goes back
to the Do and tests condition again. If condition is False on the first pass, the statements are never
executed.
number = 1
While number <=100
number = number + 1
Wend
The Do...Loop While statement first executes the statements and then test the condition after each
execution. The following program block illustrates the structure:
19
The programs executes the statements between Do and Loop While structure in any case. Then it
determines whether the counter is less than 501. If so, the program again executes the statements
between Do and Loop While else exits the Loop.
Do Until...Loop Statement
Unlike the Do While...Loop and While...Wend repetition structures, the Do Until... Loop structure
tests a condition for falsity. Statements in the body of a Do Until...Loop are executed repeatedly as
long as the loop-continuation test evaluates to False.
An example for Do Until...Loop statement. The coding is typed inside the click event of the
command button
Numbers between 1 to 1000 will be displayed on the form as soon as you click on the command
button.
The For...Next Loop is another way to make loops in Visual Basic. For...Next repetition structure
handles all the details of counter-controlled repetition. The following loop counts the numbers from
1 to 100:
Dim x As Integer
For x = 1 To 50
Print x
Next
In order to count the numbers from 1 yo 50 in steps of 2, the following loop can be used
For x = 1 To 50 Step 2
Print x
Next
The above coding will display numbers vertically on the form. In order to display numbers
horizontally the following method can be used.
20
For x = 1 To 50
Print x & Space$ (2);
Next
To increase the space between the numbers increase the value inside the brackets after the &
Space$.
Following example is a For...Next repetition structure which is with the If condition used.
In the output instead of number 4 you will get the "This is number 4".
Dim x As Integer
For x = 1 To 10
Print x
If x = 5 Then
Print "The program exited at x=5"
Exit For
End If
Next
The preceding code increments the value of x by 1 until it reaches the condition x = 5. The Exit For
statement is executed and it terminates the For...Next loop. The Following statement block
containing Do...While loop is terminated using Exit Do statement.
Dim x As Integer
Do While x < 10
Print x
x=x+1
If x = 5 Then
Print "The program is exited at x=5"
Exit Do
End If
Loop
21
When properties are set for objects or methods are called, a lot of coding is included that acts on the
same object. It is easier to read the code by implementing the With...End With statement. Multiple
properties can be set and multiple methods can be called by using the With...End With statement.
The code is executed more quickly and efficiently as the object is evaluated only once. The concept
can be clearly understood with following example.
With Text1
.[Link] = 14
.[Link] = True
.ForeColor = vbRed
.Height = 230
.Text = "Hello World"
End With
In the above coding, the object Text1, which is a text box is evaluated only once instead of every
associated property or method. This makes the coding simpler and efficient.
An array is a consecutive group of memory locations that all have the same name and the same
type. To refer to a particular location or element in the array, we specify the array name and the
array element position number.
The Individual elements of an array are identified using an index. Arrays have upper and lower
bounds and the elements have to lie within those bounds. Each index number in an array is
allocated individual memory space and therefore users must evade declaring arrays of larger size
than required. We can declare an array of any of the basic data types including variant, user-defined
types and object variables. The individual elements of an array are all of the same data type.
Declaring arrays
Arrays occupy space in memory. The programmer specifies the array type and the number of
elements required by the array so that the compiler may reserve the appropriate amount of memory.
Arrays may be declared as Public (in a code module), module or local. Module arrays are declared
in the general declarations using keyword Dim or Private. Local arrays are declared in a procedure
using Dim or Static. Array must be declared explicitly with keyword "As".
Fixed-size array : The size of array always remains the same-size doesn't change during the
program execution.
Dynamic array : The size of the array can be changed at the run time- size changes during the
program execution.
Fixed-sized Arrays
When an upper bound is specified in the declaration, a Fixed-array is created. The upper limit
should always be within the range of long data type.
22
Declaring a fixed-array
In the above illustration, numbers is the name of the array, and the number 6 included in the
parentheses is the upper limit of the array. The above declaration creates an array with 6 elements,
with index numbers running from 0 to 5.
If we want to specify the lower limit, then the parentheses should include both the lower and upper
limit along with the To keyword. An example for this is given below.
In the above statement, an array of 10 elements is declared but with indexes running from 1 to 6.
A public array can be declared using the keyword Public instead of Dim as shown below.
Multidimensional Arrays
Arrays can have multiple dimensions. A common use of multidimensional arrays is to represent
tables of values consisting of information arranged in rows and columns. To identify a particular
table element, we must specify two indexes: The first (by convention) identifies the element's row
and the second (by convention) identifies the element's column.
Tables or arrays that require two indexes to identify a particular element are called two dimensional
arrays. Note that multidimensional arrays can have more than two dimensions. Visual Basic
supports at least 60 array dimensions, but most people will need to use more than two or three
dimensional-arrays.
It is also possible to define the lower limits for one or both the dimensions as for fixed size arrays.
An example for this is given here.
An example for three dimensional-array with defined lower limits is given below.
Basically, you can create either static or dynamic arrays. Static arrays must include a fixed number
of items, and this number must be known at compile time so that the compiler can set aside the
23
necessary amount of memory. You create a static array using a Dim statement with a constant
argument:
Visual Basic starts indexing the array with 0. Therefore, the preceding array actually holds 101
items.
Most programs don't use static arrays because programmers rarely know at compile time how many
items you need and also because static arrays can't be resized during execution. Both these issues
are solved by dynamic arrays. You declare and create dynamic arrays in two distinct steps. In
general, you declare the array to account for its visibility (for example, at the beginning of a module
if you want to make it visible by all the procedures of the module) using a Dim command with an
empty pair of brackets. Then you create the array when you actually need it, using a ReDim
statement:
If you're creating an array that's local to a procedure, you can do everything with a single ReDim
statement:
Sub PrintReport()
' This array is visible only to the procedure.
ReDim Customers(1000) As String
' ...
End Sub
If you don't specify the lower index of an array, Visual Basic assumes it to be 0, unless an Option
Base 1 statement is placed at the beginning of the module. My suggestion is this: Never use an
Option Base statement because it makes code reuse more difficult. (You can't cut and paste routines
without worrying about the current Option Base.) If you want to explicitly use a lower index
different from 0, use this syntax instead:
Dynamic arrays can be re-created at will, each time with a different number of items. When you re-
create a dynamic array, its contents are reset to 0 (or to an empty string) and you lose the data it
contains. If you want to resize an array without losing its contents, use the ReDim Preserve
command:
24
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:
Finally, you can destroy an array using the Erase statement. If the array is dynamic, Visual Basic
releases the memory allocated for its elements (and you can't read or write them any longer); if the
array is static, its elements are set to 0 or to empty strings.
You can use the LBound and UBound functions to retrieve the lower and upper indices. If the array
has two or more dimensions, you need to pass a second argument to these functions to specify the
dimension you need:
UDT structures can include both static and dynamic arrays. Here's a sample structure that contains
both types:
Type MyUDT
StaticArr(100) As Long
DynamicArr() As Long
End Type
...
Dim udt As MyUDT
' You must DIMension the dynamic array before using it.
ReDim [Link](100) As Long
' You don't have to do that with static arrays.
[Link](1) = 1234
The memory needed by a static array is allocated within the UDT structure; for example, the
StaticArr array in the preceding code snippet takes exactly 400 bytes. Conversely, a dynamic array
in a UDT takes only 4 bytes, which form a pointer to the memory area where the actual data is
stored. Dynamic arrays are advantageous when each individual UDT variable might host a different
number of array items. As with all dynamic arrays, if you don't dimension a dynamic array within a
UDT before accessing its items, you get an error 9—"Subscript out of range."
25
User-Defined Data Types in Visual Basic 6
Variables of different data types when combined as a single variable to hold several related
information is called a User-Defined data type.
A Type statement is used to define a user-defined type in the General declaration section of a form
or module. User-defined data types can only be private in form while in standard modules can be
public or private. An example for a user defined data type to hold the product details is as given
below.
The user defined data type can be declared with a variable using the Dim statement as in any other
variable declaration statement. An array of these user-defined data types can also be declared. An
example to consolidate these two features is given below.
A User-Defined data type can be referenced in an application by using the variable name in the
procedure along with the item name in the Type block. Say, for example if the text property of a
TextBox namely text1 is to be assigned the name of the electronic good, the statement can be
written as given below.
[Link] = [Link]
[Link] = ElectronicGoods(i).ProdName
User-defined data types can also be passed to procedures to allow many related items as one
argument.
Constants
Constants are named storage locations in memory, the value of which does not change during
program Execution. They remain the same throughout the program execution. When the user wants
to use a value that never changes, a constant can be declared and created. The Const statement is
26
used to create a constant. Constants can be declared in local, form, module or global scope and can
be public or private as for variables. Constants can be declared as illustrated below.
The predefined constants can be used anywhere in the code in place of the actual numeric values.
This makes the code easier to read and write.
For example consider a statement that will set the window state of a form to be maximized.
[Link] = 2
[Link] = vbMaximized
Visual Basic functions either to convert a string into an integer or vice versa and many more conversion
functions. A complete listing of all the conversion functions offered by Visual Basic is elucidated below.
Conversion To Function
Boolean Cbool
Byte Cbyte
Currency Ccur
Date Cdate
Decimals Cdec
Double CDbl
Integer Cint
Long CLng
Single CSng
String CStr
Variant Cvar
Error CVErr
A conversion function should always be placed at the right hand side of the calculation statement.
Many built-in functions are offered by Visual Basic fall under various categories. These functions
are procedures that return a value. The functions fall into the following basic categories that will be
discussed in the following sections at length.
String Functions
27
Date and Time Functions in Visual Basic 6
Not only does Visual Basic let you store date and time information in the specific Date data type, it
also provides a lot of date- and time-related functions. These functions are very important in all
business 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.
The system's current date and time can be retrieved using the Now, Date and Time functions in
Visual Basic. The Now function retrieves the date and time, while Date function retrieves only date
and Time function retrieves only the time.
To display both the date and time together a message box is displayed use the statement given
below.
MsgBox "The current date and time of the system is" & Now
Here & is used as a concatenation operator to concentrate the string and the Now function. Selective
portions of the date and time value can be extracted using the below listed functions.
The calculation and conversion functions related to date and time functions are listed below.
Function Description
DateAdd ( ) Returns a date to which a specific interval has been added
DateDiff ( ) Returns a Long data type value specifying the interval between
the two values
DatePart ( ) Returns an Integer containing the specified part of a given date
DateValue ( ) Converts a string to a Date
TimeValue ( ) Converts a string to a time
DateSerial ( ) Returns a date for specified year, month and day
DateDiff Function
The DateDiff function returns the intervals between two dates in terms of years, months or days.
The syntax for this is given below.
Format Function
28
The format function accepts a numeric value and converts it to a string in the format specified by
the format argument. The syntax for this is given below.
Part Description
Expression Required any valid expression
format Optional. A valid named or user-defined format expression.
firstdayofweek Optional. A contant that specifies the first day of the week.
firstweekofyear Optional. A contant that specifies the first week of the year
This lesson concentrates on Visual Basic controls and the ways of creating and implementing the. It
also helps us to understand the concept of Control Arrays. Controls are used to recieve user input
and display output and has its own set of properties, methods and events. Let us discuss few of
these controls in this lesson.
A control is an object that can be drawn on a Form object to enable or enhance user interaction with
an application. Controls have properties that define aspects their appearance, such as position, size
and colour, and aspects of their behavior, such as their response to the user input. They can respond
to events initiated by the user or set off by the system. For instance, a code could be written in a
CommandButton control's click event procedure that would load a file or display a result.
In addition to properties and events, methods can also be used to manipulate controls from code.
For instance, the move method can be used with some controls to change their location and size.
Most of the controls provide choices to users that can be in the form of OptionButton or CheckBox
controls, ListBox entries or ScrollBars to select a value. Let us discuss these controls by means of a
few simple applications in the following lessons.
Classification of Controls
Visual Basic cojntrols are broadly classified as standard controls, ActiveX controls and insertable
objects. Standard controls such as CommandButton, Label and Frame controls are contained
inside .EXE file and are always included in the ToolBox which cannot be removed. ActiveX
controls exist as separate files with either .VBX or .OCX extension. They include specialized
controls such as;
MSChart control
29
v. The Multimedia control
vi. The Internet Transfer control
vii. The WinSock control
viii. The TreeView control
ix. The SysInfo control
x. The Picture Clip control
Some of these objects support OLE Automation, which allow programming another application's
object from within Visual Basic application.
I would like to stress that knowing how and when to set the objects' properties is very important as
it can help you to write a good program or you may fail to write a good program. So, I advice you
to spend a lot of time playing with the objects' properties
You should set the Caption Property of a control clearly so that a user knows what to do
with that command. For example, in the calculator program, all the captions of the command
buttons such as +, - , MC, MR are commonly found in an ordinary calculator, a 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
Finally, you must also considering making the control visible or invisible at runtime, or
when should it become visible or invisible
Visual Basic uses the TabIndex property to determine the control that would receive the focus next
when a tab key is pressed. Every time a tab key is pressed, Visual Basic looks at the value of the
TabIndex for the control that has focus and then it scans through the controls searching for the next
highest TabIndex number. When there are no more controls with higher TabIndex value, Visual
Basic starts all over again with 0 and looks for the first control with TabIndex of 0 or higher that
can accept keyboard input.
By default, Visual Basic assigns a tab order to control as we draw the controls on the Form, except
for Menu, Timer, Data, Image, Line and Shape controls, which are not included in tab order. At run
time, invisible or disabled controls also cannot receive the focus although a TabIndex value is
given. Setting the TabIndex property of controls is compulsory in development environment.
TextBox controls offer a natural way for users to enter a value in your program. For this reason,
they tend to be the most frequently used controls in the majority of Windows applications. TextBox
controls, which have a great many properties and events, are also among the most complex intrinsic
30
controls. In this section, I guide you through the most useful properties of TextBox controls and
show how to solve some of the problems that you're likely to encounter.
Text can be entered into the text box by assigning the necessary string to the text property of
the control
If the user needs to display multiple lines of text in a TextBox, set the MultiLine property to
True
To customize the scroll bar combination on a TextBox, set the ScrollBars property.
Scroll bars will always appear on the TextBox when it's MultiLine property is set to True
and its ScrollBars property is set to anything except None(0)
If you set the MultilIne property to True, you can set the alignment using the Alignment
property. The test is left-justified by default. If the MultiLine property is et to False, then
setting the Alignment property has no effect.
The Text property is the one you'll reference most often in code, and conveniently it's the default
property for the TextBox control. Three other frequently used properties are these:
1. The SelStart property sets or returns the position of the blinking caret (the insertion point
where the text you type appears). Note that the blinking cursor inside TextBox and other
controls is named caret, to distinguish it from the cursor (which is implicitly the mouse
cursor). When the caret is at the 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.
2. 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.
3. 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.
When you want to append text to a TextBox control, you should use the following code (instead of
using the concatenation operator) to reduce flickering and improve performance:
[Link] = Len([Link])
[Link] = StringToBeAdded
31
One of the typical operations you could find yourself performing with these properties is selecting
the entire contents of a TextBox control. You often do it when the caret enters the field so that the
user can quickly override the existing value with a new one, or start editing it by pressing any arrow
key:
Always set the SelStart property first and then the SelLength or SelText properties. When you
assign a new value to the SelStart property, the other two are automatically reset to 0 and an empty
string respectively, thus overriding your previous settings.
In the above syntax, text is the text that has to be placed into the Clipboard, and format has three
possible values.
We can get text from the clipboard using the GetText() function this way:
[Link] ([format])
The following Figure summarizes the common TextBox control's properties and methods.
Properties
Enabled specifies whether user can interact with this control or not
Index Specifies the control array index
Locked If this control is set to True user can use it else if this control is set to
false the control cannot be used
MaxLength Specifies the maximum number of characters to be input. Default
value is set to 0 that means user can input any number of characters
MousePointer Using this we can set the shape of the mouse pointer when over a
TextBox
Multiline By setting this property to True user can have more than one line in
the TextBox
PasswordChar This is to specify mask character to be displayed in the TextBox
ScrollBars This to set either the vertical scrollbars or horizontal scrollbars to
make appear in the TextBox. User can also set it to both vertical and
32
horizontal. This property is used with the Multiline property.
Method
SetFocus Transfers focus to the TextBox
Event procedures
Change Action happens when the TextBox changes
Click Action happens when the TextBox is clicked
GotFocus Action happens when the TextBox receives the active focus
LostFocus Action happens when the TextBox loses it focus
KeyDown Called when a key is pressed while the TextBox has the focus
KeyUp Called when a key is released while the TextBox has the focus
TextBox controls support KeyDown, KeyPress, and KeyUp standard events. One thing that you
will often do is prevent the user from entering invalid keys. A typical example of where this
safeguard is needed is a numeric field, for which you need to filter out all nondigit keys:
You should never reject keys whose ANSI code is less than 32, a group that includes important
keys such as Backspace, Escape, Tab, and Enter. Also note that a few control keys will make your
TextBox beep if it doesn't know what to do with them—for example, a single-line TextBox control
doesn't know what to do with an Enter key.
Don't assume that the KeyPress event will trap all control keys under all conditions. For example,
the KeyPress event can process the Enter key only if there's no CommandButton control on the
form whose Default property is set to True. If the form has a default push button, the effect of
pressing the Enter key is clicking on that button. Similarly, no Escape key goes through this event if
there's a Cancel button on the form. Finally, the Tab control key is trapped by a KeyPress event
only if there isn't any other control on the form whose TabStop property is True.
You can use the KeyDown event procedure to allow users to increase and decrease the current
value using Up and Down arrow keys, as you see here:
33
Private Sub Text1_KeyDown(KeyCode As Integer, Shift As Integer)
Select Case KeyCode
Case vbKeyUp
[Link] = CDbl([Link]) + 1
Case vbKeyDown
[Link] = CDbl([Link]) -1
End Select
End Sub
There's a bug in the implementation of TextBox ready-only controls. When the Locked property is
set to True, the Ctrl+C key combination doesn't correctly copy the selected text to the Clipboard,
and you must manually implement this capability by writing code in the KeyPress event procedure
Although trapping invalid keys in the KeyPress or KeyDown event procedures seems a great idea at
first, when you throw your application to inexperienced users you soon realize that there are many
ways for them to enter invalid data. Depending on what you do with this data, your application can
come to an abrupt end with a run-time error or—much worse—it can appear to work correctly
while it delivers bogus results. What you really need is a bullet-proof method to trap invalid values.
Before I offer you a decent solution to the problem, let me explain why you can't rely solely on
trapping invalid keys for your validation chores. What if the user pastes an invalid value from the
clipboard? Well, you might say, let's trap the Ctrl+V and Shift+Ins key combinations to prevent the
user from doing that! Unfortunately, Visual Basic's TextBox controls offer a default edit menu that
lets users perform any clipboard operation by simply right-clicking on them. Fortunately, there's a
way around this problem: Instead of trapping a key before it gets to the TextBox control, you trap
its effect in the Change event and reject it if it doesn't pass your test. But this makes the structure of
the code a little more complex than you might anticipate:
34
saveSelStart = [Link]
Else
' Prepare to handle a nested call.
nestedCall = True
[Link] = saveText
nestedCall = False
[Link] = saveSelStart
End If
End Sub
If the control's value doesn't pass your tests in the Change event procedure, you must restore its
previous valid value; this action recursively fires a Change event, and you must prepare yourself to
neutralize this nested call. You might wonder why you also need to trap the KeyUp, MouseDown,
and MouseMove events: The reason is that you always need to keep track of the last valid position
for the insertion point because the end user could move it using arrow keys or the mouse.
The preceding code snippet uses the IsNumeric function to trap invalid data. You should be aware
that this function isn't robust enough for most real-world applications. For example, the IsNumeric
function incorrectly considers these strings as valid numbers:
123,,,123
345-
$1234 ' What if it isn't a currency field?
2.4E10 ' What if I don't want to support scientific notation?
To cope with this issue, I have prepared an alternative function, which you can modify for your
particular purposes. (For instance, you can add support for a currency symbol or the comma as the
decimal separator.) Note that this function always returns True when it's passed a null string, so you
might need to perform additional tests if the user isn't allowed to leave the field blank:
35
If i > 1 Then Exit Function
Case "."
' Exit if decimal values not allowed.
If Not DecValue Then Exit Function
' Only one decimal separator is allowed.
If InStr(text, ".") < i Then Exit Function
Case Else
' Reject all other characters.
Exit Function
End Select
Next
CheckNumeric = True
End Function
If your TextBox controls are expected to contain other types of data, you might be tempted to reuse
the same validation framework I showed you previously—including all the code in the GotFocus,
Change, KeyUp, MouseDown, and MouseMove event procedures—and replace only the call to
IsNumeric with a call to your custom validation routine. Things aren't as simple as they appear at
first, however. Say that you have a date field: Can you use the IsDate function to validate it from
within the Change event? The answer is, of course, no. In fact, as you enter the first digit of your
date value, IsDate returns False and the routine therefore prevents you from entering the remaining
characters, and so preventing you from entering any value.
This example explains why a key-level validation isn't always the best answer to your validation
needs. For this reason, most Visual Basic programmers prefer to rely on field-level validation and
test the values only when the user moves the input focus to another field in the form. I explain field-
level validation in the next section.
The CausesValidation Property and the Validate Event - Visual Basic 6 TextBox Control
Visual Basic 6 has finally come up with a solution for most of the validation issues that have
afflicted Visual Basic developers for years. As you'll see in a moment, the Visual Basic 6 approach
is simple and clean; it really astonishes me that it took six language versions to deliver such a
lifesaver. The keys to the new validation features are the Validate event and the CausesValidation
property. They work together as follows: When the input focus leaves a control, Visual Basic
checks the CausesValidation property of the control that is about to receive the focus. If this
property is True, Visual Basic fires the Validate event in the control that's about to lose the focus,
thus giving the programmer a chance to validate its contents and, if necessary, cancel the focus
shift.
Let's try a practical example. Imagine that you have five controls on a form: a required field (a
TextBox control, txtRequired, that can't contain an empty string), a numeric field, txtNumeric, that
expects a value in the range 1 through 1000, and three push buttons: OK, Cancel, and Help. (See the
figure below.) You don't want to perform validation if the user presses the Cancel or Help buttons,
so you set their CausesValidation properties to False. The default value for this property is True, so
you don't have to modify it for the other controls. Run the sample program on the companion CD,
type something in the required TextBox, and then move to the second field. Because the second
field's CausesValidation property is True, Visual Basic fires a Validate event in the first TextBox
control:
36
Private Sub txtRequired_Validate(Cancel As Boolean)
' Check that field is not empty.
If [Link] = "" Then
MsgBox "Please enter something here", vbExclamation
Cancel = True
End If
End Sub
If the Cancel parameter is set to True, Visual Basic cancels the user's action and takes the input
focus back on the txtRequired control: No other GotFocus and LostFocus events are generated. On
the other hand, if you typed something in the required field, the focus will now be on the second
field (the numeric text box). Try clicking on the Help or Cancel buttons: No Validate event will fire
this time because you set the CausesValidation property for each of these controls to False. Instead,
click on the OK button to execute the Validate event of the numeric field, where you can check it
for invalid characters and valid range.
A demonstration program that lets you experiment with the new Visual Basic Validate features
In some circumstances, you might want to programmatically validate the control that has the focus
without waiting for the user to move the input focus. You can do it with the form's ValidateControls
method, which forces the Validate event of the control that has the input focus. Typically, you do it
when the user closes the form:
37
On Error Resume Next
ValidateControls
If Err = 380 Then
' The current field failed validation.
Cancel = True
End If
End If
End Sub
Checking the UnloadMode parameter is important; otherwise, your application will mistakenly
execute a ValidateControls method when the user clicks on the Cancel button. Note that
ValidateControls returns an error 380 if Cancel was set in the Validate event procedure of the
control that had the focus.
Visual Basic 6's validation scheme has two flaws, though. If your form has a CommandButton
whose Default property is set to True, pressing the Enter key while the input focus is on another
control results in a click on the CommandButton control but doesn't fire a Validate event, even if
the CausesValidation property of the CommandButton control is set to True. The only way to solve
this problem is to invoke the ValidateControls method from within the default CommandButton
control's Click event procedure.
The second flaw is that the Validate event doesn't fire when you're moving the focus from a control
whose CausesValidation property is False, even if the control that receives the focus has its
CausesValidation property set to True.
The new Visual Basic 6 validation mechanism is simple and can be implemented with little effort.
But it isn't the magic answer to all your validation needs. In fact, this technique can only enforce
field-level validation; it does nothing for record-level validation. In other words, it ensures that one
particular field is correct, not that all fields in the form contain valid data. To see what I mean, run
the demonstration program, enter a string in the first field, and press Alt+F4 to close the form. Your
code won't raise an error, even if the second field doesn't contain a valid number! Fortunately, it
doesn't take much to create a generic routine that forces each control on the form to validate itself:
38
End If
End If
Next
End If
End Sub
The CausesValidation property and the Validate event are shared by all the intrinsic controls that
are able to get the focus as well as by most external ActiveX controls, even those not specifically
written for Visual Basic. This is possible because they are extender features, provided by the Visual
Basic runtime to all the controls placed on a form's surface.
One Visual Basic operator has great potential when it comes time to validate complex strings but is
neglected by most Visual Basic developers. Let's say you have a product code that consists of two
uppercase characters followed by exactly three digits. You might think that you need some complex
string functions to validate such a string until you try the Like operator, as follows:
Although trapping invalid keys in the KeyPress or KeyDown event procedures seems a great idea at
first, when you throw your application to inexperienced users you soon realize that there are many
ways for them to enter invalid data. Depending on what you do with this data, your application can
come to an abrupt end with a run-time error or—much worse—it can appear to work correctly
while it delivers bogus results. What you really need is a bullet-proof method to trap invalid values.
Before I offer you a decent solution to the problem, let me explain why you can't rely solely on
trapping invalid keys for your validation chores. What if the user pastes an invalid value from the
clipboard? Well, you might say, let's trap the Ctrl+V and Shift+Ins key combinations to prevent the
user from doing that! Unfortunately, Visual Basic's TextBox controls offer a default edit menu that
lets users perform any clipboard operation by simply right-clicking on them. Fortunately, there's a
way around this problem: Instead of trapping a key before it gets to the TextBox control, you trap
its effect in the Change event and reject it if it doesn't pass your test. But this makes the structure of
the code a little more complex than you might anticipate:
39
' Test the control's value here.
If IsNumeric([Link]) Then
' If value is OK, save values.
saveText = [Link]
saveSelStart = [Link]
Else
' Prepare to handle a nested call.
nestedCall = True
[Link] = saveText
nestedCall = False
[Link] = saveSelStart
End If
End Sub
If the control's value doesn't pass your tests in the Change event procedure, you must restore its
previous valid value; this action recursively fires a Change event, and you must prepare yourself to
neutralize this nested call. You might wonder why you also need to trap the KeyUp, MouseDown,
and MouseMove events: The reason is that you always need to keep track of the last valid position
for the insertion point because the end user could move it using arrow keys or the mouse.
The preceding code snippet uses the IsNumeric function to trap invalid data. You should be aware
that this function isn't robust enough for most real-world applications. For example, the IsNumeric
function incorrectly considers these strings as valid numbers:
123,,,123
345-
$1234 ' What if it isn't a currency field?
2.4E10 ' What if I don't want to support scientific notation?
To cope with this issue, I have prepared an alternative function, which you can modify for your
particular purposes. (For instance, you can add support for a currency symbol or the comma as the
decimal separator.) Note that this function always returns True when it's passed a null string, so you
might need to perform additional tests if the user isn't allowed to leave the field blank:
40
Select Case Mid$(text, i, 1)
Case "0" To "9"
Case "-", "+"
' Minus/plus signs are only allowed as leading chars.
If i > 1 Then Exit Function
Case "."
' Exit if decimal values not allowed.
If Not DecValue Then Exit Function
' Only one decimal separator is allowed.
If InStr(text, ".") < i Then Exit Function
Case Else
' Reject all other characters.
Exit Function
End Select
Next
CheckNumeric = True
End Function
If your TextBox controls are expected to contain other types of data, you might be tempted to reuse
the same validation framework I showed you previously—including all the code in the GotFocus,
Change, KeyUp, MouseDown, and MouseMove event procedures—and replace only the call to
IsNumeric with a call to your custom validation routine. Things aren't as simple as they appear at
first, however. Say that you have a date field: Can you use the IsDate function to validate it from
within the Change event? The answer is, of course, no. In fact, as you enter the first digit of your
date value, IsDate returns False and the routine therefore prevents you from entering the remaining
characters, and so preventing you from entering any value.
This example explains why a key-level validation isn't always the best answer to your validation
needs. For this reason, most Visual Basic programmers prefer to rely on field-level validation and
test the values only when the user moves the input focus to another field in the form. I explain field-
level validation in the next section.
When compared to TextBox controls, these controls are really simple. Not only do they expose
relatively few properties, they also support a limited number of events, and you don't usually write
much code to manage them.
Using CommandButton controls is trivial. In most cases, you just draw the control on the form's
surface, set its Caption property to a suitable string (adding an & character to associate a hot key
with the control if you so choose), and you're finished, at least with user-interface issues. To make
the button functional, you write code in its Click event procedure, as in this fragment:
41
Unload Me
End Sub
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.
The only relevant CommandButton's run-time property is Value, which sets or returns the state of
the control (True if pressed, False otherwise). Value is also the default property for this type of
control. In most cases, you don't need to query this property because if you're inside a button's Click
event you can be sure that the button is being activated. The Value property is useful only for
programmatically clicking a button:
The CommandButton control supports the usual set of keyboard and mouse events (KeyDown,
KeyPress, KeyUp, MouseDown, MouseMove, MouseUp, but not the DblClick event) and also the
GotFocus and LostFocus events, but you'll rarely have to write code in the corresponding event
procedures.
To set the background colour of the CommandButton, select a colour in the BackColor
property.
Font for the CommandButton control can be selected using the Font property.
To enable or disable the buttons set the Enabled property to True or False
To make visible or invisible the buttons at run time, set the Visible property to True or
False.
Tooltips can be added to a button by setting a text to the Tooltip property of the
CommandButton.
A button click event is handled whenever a command button is clicked. To add a click event
handler, double click the button at design time, which adds a subroutine like the one given below.
42
OptionButton Controls in VB6
OptionButton controls are also known as radio buttons because of their shape. You always use
OptionButton controls in a group of two or more because their purpose is to offer a number of
mutually exclusive choices. Anytime you click on a button in the group, it switches to a selected
state and all the other controls in the group become unselected.
Preliminary operations for an OptionButton control are similar to those already described for
CheckBox controls. You set an OptionButton control's Caption property to a meaningful string, and
if you want you can change its Alignment property to make the control right aligned. If the control
is the one in its group that's in the selected state, you also set its Valueproperty to True. (The
OptionButton's Value property is a Boolean value because only two states are possible.) Value is
the default property for this control.
At run time, you typically query the control's Value property to learn which button in its group has
been selected. Let's say you have three OptionButton controls, named optWeekly, optMonthly, and
optYearly. You can test which one has been selected by the user as follows:
If [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.
A group of OptionButton controls is often hosted in a Frame control. This is necessary when there
are other groups of OptionButton controls on the form. As far as Visual Basic is concerned, all the
OptionButton controls on a form's surface belong to the same group of mutually exclusive
selections, even if the controls are placed at the opposite corners of the window. The only way to
tell Visual Basic which controls belong to which group is by gathering them inside a Frame control.
Actually, you can group your controls within any control that can work as a container—PictureBox,
for example—but Frame controls are often the most reasonable choice.
Example
Open a new Standard EXE project and the save the Form as [Link] and save the project as
[Link].
Name Label1
43
TextBox Text (empty)
Name Text1
CommandButto Caption &Close
n
Name Command1
OptionButton Caption &Octal
Name optOct
OptionButton Caption &Hexadecimal
Name optHex
OptionButton Caption &Decimal
Name optDec
The change event of the TextBox reads the value and stores it in a form-level numeric
variable.
The click event of optOct button returns curretval in octal.
The click event of the optDec button returns the decimal equivalent of the value held
currentval.
The following code is entered in the general declarations section of the Form.
The variable is initialized to 0 by default. The change event procedure checks to ascertain the
number system (Octal, Hexadecimal) that is in effect and then reads in the number.
The Val function is used to translate string to a number and can recognize Octal and Hexadecimal
strings. The LTrim function trims the leading blanks in the text. The following code is entered in
the click events of the OptionButton controls.
44
Private Sub optOct_Click()
[Link] = Oct(currentval)
End Sub
The follwoing code is entered in the click event of teh Close button.
The Application is run by pressing F5 or clicking on the Run icon in the tool bar. By pressing the
Exit button the program is terminated.
Label and Frame controls have a few features in common, so it makes sense to explain them
together. First they're mostly "decorative" controls that contribute to the user interface but are
seldom used as programmable objects. In other words, you often place them on the form and
arrange their properties as your user interface needs dictate, but you rarely write code to serve their
events, generally, or manipulate their properties at run time.
Label Controls
Most people use Label controls to provide a descriptive caption and possibly an associated hot key
for other controls, such as TextBox, ListBox, and ComboBox, that don't expose the Caption
property. In most cases, you just place a Label control where you need it, set its Caption property to
a suitable string (embedding an ampersand character in front of the hot key you want to assign), and
you're done. Caption is the default property for Label controls. Be careful to set the Label's
TabIndex property so that it's 1 minus the TabIndex property of the companion control.
Other useful properties are BorderStyle(if you want the Label control to appear inside a 3D border)
and Alignment (if you want to align the caption to the right or center it on the control). In most
cases, the alignment depends on how the Label control relates to its companion control: for
example, if the Label control is placed to the left of its companion field, you might want to set its
Alignment property to 1-Right Justify. The value 2-Center is especially useful for stand-alone Label
controls.
45
Different settings for the Alignment property of Label controls.
You can insert a literal & character in a Label control's Caption property by doubling it. For
example, to see Research & Development you have to type &Research && Development. Note that
if you have multiple but isolated &s, the one that selects the hot key is the last one and all others are
ignored. This tip applies to all the controls that expose a Caption property. (The & has no special
meaning in forms' Caption properties, however.)
If the caption string is a long one, you might want to set the Label's WordWrap property to True so
that it will extend for multiple lines instead of being truncated by the right border of the control.
Alternatively, you might decide to set the AutoSize property to True and let the control
automatically resize itself to accommodate longer caption strings.
You sometimes need to modify the default value of a Label's BackStyle property. Label controls
usually cover what's already on the form's surface (other lightweight controls, output from graphic
methods, and so on) because their background is considered to be opaque. If you want to show a
character string somewhere on the form but at the same time you don't want to obscure underlying
objects, set the BackStyle property to 0-Transparent.
If you're using the Label control to display data read from elsewhere—for example, a database field
or a text file—you should set its UseMnemonics property to False. In this case, & characters have
no special meaning to the control, and so you indirectly turn off the control's hot key capability. I
mention this property because in older versions of Visual Basic, you had to manually double each &
character to make the ampersand appear in text. I don't think all developers are aware that you can
now treat ampersands like regular characters.
As I said before, you don't usually write code in Label control event procedures. This control
exposes only a subset of the events supported by other controls. For example, because Label
controls can never get the input focus, they don't support GotFocus, LostFocus, or any keyboard-
related events. In practice, you can take advantage only of their mouse events: Click, DblClick,
MouseDown, MouseMove, and MouseUp. If you're using a Label control to display data read from
a database, you might sometimes find it useful to write code in its Change event. A Label control
doesn't expose a specific event that tells programmers when users press its hot keys.
You can do some interesting tricks with Label controls. For example, you can use them to provide
rectangular hot spots for images loaded onto the form. To create that context-sensitive ToolTip, I
loaded the image on the form using the form's Picture property and then I placed a Label control
over the Microsoft BackOffice logo, setting its Caption property to an empty string and the
BackStyle property to 0-Transparent. These properties make the Label invisible, but it correctly
46
shows its ToolTip when necessary. And because it still receives all mouse events, you can use its
Click event to react to users' actions.
Frame Controls
Frame controls are similar to Label controls in that they can serve as captions for those controls that
don't have their own. Moreover, Frame controls can also (and often do) behave as containers and
host other controls. In most cases, you only need to drop a Frame control on a form and set its
Caption property. If you want to create a borderless frame, you can set its BorderStyle property to
0-None.
Controls that are contained in the Frame control are said to be child controls. Moving a control at
design time over a Frame control—or over any other container, for that matter—doesn't
automatically make that control a child of the Frame control. After you create a Frame control, you
can create a child control by selecting the child control's icon in the Toolbox and drawing a new
instance inside the Frame's border. Alternatively, to make an existing control a child of a Frame
control, you must select the control, press Ctrl+X to cut it to the Clipboard, select the Frame
control, and press Ctrl+V to paste the control inside the Frame. If you don't follow this procedure
and you simply move the control over the Frame, the two controls remain completely independent
of each other, even if the other control appears in front of the Frame control.
Frame controls, like all container controls, have two interesting features. If you move a Frame
control, all the child controls go with it. If you make a container control disabled or invisible, all its
child controls also become disabled or invisible. You can exploit these features to quickly change
the state of a group of related controls.
47