4 Advanced Visual Basic
4 Advanced Visual Basic
Tirunelveli
Client / Server
Lecture - 1
Client /Server
Objectives
About Client
About Server
Lecture Unit - 1
1.2 Client
1.3 Server
Any time two computers are involved in the mutual performance of executing an
application, with each performing a different function, you are undoubtedly looking
at a client/server application. Many definitions of client/server are used. A
definition of client/server application is an application that has a client interface and
that accesses data on a remote server. The work is distributed between the client
system and the remote server system, based on the capabilities of the client and the
system and the remote server system, based on the capabilities of the client and
server software applications. Client/server systems usually are efficient because
network traffic is minimized and each portion of the application is optimized for a
particular function.
1.2 Client
A client may be either a device or a user on a network that takes advantages of the
services offered by a server. Client is often used in a loose way to refer to a computer
on the network. It also refers to a user that is running the client slide of a
client/server application. The Client area of a window is where end users enter data.
Formally, the client is the region of a window that doesn’t include the title bar,
menus, toolbars, status bars or window borders. In Visual Basic, the width and
height to the client area can be determined by examining the value of a form’s Scale
width and Scale height properties, respectively.
1.3 Server
You can use VBScript to create Active Server Pages(ASP) in order to create logic that
enables IIS to respond to various input from client computers. Also, you can use
Visual Basic to create custom ActiveX components designed to work as extensions
and enhancements to the IIS environment. These components are called server –side
components.
and sharing the processing load between two. The client requests services, and the
server provides the requested services.
If you write a program that resides and executes on a client computer, that program
is called a client-side program. If you create a program that runs on a Internet server,
that program is called a server-side program. Microsoft Word is considered a client-
side program. Yahoo Search, a program that searches for articles on the Web, is a
sever-side program.
Architecture that splits an application into a front-end client component and a back-
end server component. The client component running on a workstation gathers data
from the user, prepares it for the server, and issues a request to the server. On the
back end, the server waits for requests from its clients. When it receives a request, the
server processes it and returns the requested information to the client. The client then
presents the data to the user through its own user interface.
The client communicates directly with the server with no intermediary. The
limitation of this model is not easily scalable. If the server becomes over taxed by
client traffic, the usual solution is to upgrade the server hardware to a fast processor
with more memory. However, there is an upper limit to how fast the processor can
be
There are other uses of the three-tiered client/server model, including the following
two very useful designs. The first design has a middle tier that provides an Online
Analysis Processing data warehouse that is extracted from the base layer of
operational databases. The second design makes use of a middle tier to enforce
business rules. This separate layer for business rules makes the maintenance of the
business rules much easier and less disruptive.
To use Remote Data Service technology, you must understand the three-tiered
client/server model. This model separates the various components of a client/server
system into three "tiers":
• Client tier—a local computer on which either a Web browser displays a Web
page that can display and manipulate data from a remote data source, or (in non–
Web-based applications) a stand-alone compiled front-end application.
These tiers don't necessarily correspond to physical locations on the network. For
example, all three tiers may exist on only two computers. One computer could be a
Microsoft Windows 95 computer running Microsoft Internet Explorer 4.0 as its
browser. The second computer could be a Windows NT Server computer running
both Internet Information Server and Microsoft SQL Server. Designing applications
this way gives you greater flexibility when deploying processes and data on the
network for maximum performance and ease of maintenance.
Lecture - 2
Lecture unit - 2
Visual Basic is the fastest and easiest way to create applications for Microsoft
Windows. Visual Basic provides complete set of tools to simplify rapid
application development both for the experienced professional and new
Windows programmers.
In the name Visual Basic - the "Visual" part refers to the method used to create the
graphical user interface (GUI). Unlike many languages which requires numerous
lines of coding to describe the appearance and location of interface elements, Visual
Basic provides pre-built objects that can be used to form the Graphical User Interface
(GUI).
Note : The elements that can respond to the user actions such as mouse click, double
click, drag, drop etc. are called interface elements.
The "Basic" part refers to the BASIC language as its basic syntax of statements is
retained by Visual Basic. But Visual Basic now contains several hundred statements,
functions, and keywords, many of which relate directly to the Windows GUI.
The Visual Basic programming language is not unique to Visual Basic. The Visual
Basic programming system, Applications Edition included in Microsoft Excel,
Microsoft Access, and many other Windows applications uses the same language.
The Visual Basic Scripting Edition (VBScript) is a widely used scripting language and
a subset of the Visual Basic language. So mastering Visual Basic also helps to master
these other areas.
The Visual Basic Learning Edition is the introductory edition that lets to easily create
windows applications. It comes with all the tools needed to build main stream
windows applications.
The Visual Basic Professional Edition is for computer professionals and includes
advanced features such as tools to develop ActiveX and Internet controls.
The Visual Basic Enterprise Edition is the most advanced edition and is aimed at
programmers who build distributed applications in a team environment. It includes
all the features of the Professional Edition, plus tools such Visual SourceSafe.
VB6 has a long list of minor changes, ranging from new language features to a re-
vamping of the Setup Wizard (now called the Package and Deployment Wizard).
General Features
The compiler in Visual Basic gives many different options for optimizing the
compiled code, such as Optimization for Fast Code, Optimization for Small Code
and Favor of Pentium Pro etc.
The Visual Basic is a very open environment that supports the Client/Server
architecture, ActiveX, Component Object Model (COM), Distributed Component
Object Model (DCOM). It also supports Open Database Connectivity (ODBC).
IntelliSense
A new feature that Microsoft calls IntelliSense enables the system to react in real time
during coding. There are five basic IntelliSense features:
QuickInfo
Complete Word
Data Tips
List members
List Constants
QuickInfo is a feature that presents the syntax of the procedure, which is being
typed, in a ToolTip like window. It even goes one step further in that it will bold the
specific parameter which is being coded in real time.
Complete Word is a feature that automatically completes the word which is typed in
real time, after enough characters that make the word distinct within the list of
available words, has been typed.
Datatips is a very useful feature that simply shows the value of the variable in a
yellow tooltip format at run time.
List Members is a feature that is used to simply list all of the properties or methods
available to a given object.
List Constants is a feature that works the same as the List Members feature, except
that with this feature available constant values for a given property are listed.
Other features
Multiple projects can be loaded into the IDE - Integrated Development Environment
(explained shortly) and treated as one. For example, a standard project and an
ActiveX project can be loaded at the same time. This saves tremendous amount of
time for coding and debugging. Here's a list of some other enhancements:
This section briefs what are newly added in Visual Basic 6.0 in various categories.
It combines and supersedes the prior version's DAO and RDO technologies. ADO
can be used to connect to a database on a local desktop or to a remote database
server. Also, ADO allows to access more types of data - e-mail, for example.
Data Environment
Data Report
It allows to use drag and drop to quickly create reports from any recordset, including
hierarchical recordset.
It is an updated version of the FlexGrid control that, in addition to supporting all the
functionality of the FlexGrid control, can display a hierarchy of ADO Recordsets.
Each Recordset returned is displayed as a separate band within the grid and can be
formatted independently.
These controls are OLE DB versions of the DBList and DBCombo controls. They also
support the new ADO Data control.
IIS Applications
This feature enables to write server-side Internet applications that use Visual Basic
code to respond to user requests from a browser.
DHTML Applications
New in Controls
A new OLEDB-aware data source control that functions much like the intrinsic Data
and Remote Data controls, in that it allows to create a database application with
minimum code.
Coolbar Control
DataGrid Control
These controls are OLE DB versions of the DBList and DBCombo controls. They also
support the new ADO Data control.
DateTimePicker Control
An updated version of the FlexGrid control that, in addition to supporting all the
functionality of the FlexGrid control, can display a hierarchy of ADO Recordsets.
Each Recordset returned is displayed as a separate band within the grid and can be
formatted independently.
ImageCombo Control
Behaves like the standard ComboBox control with one addition: each items in the list
can now have images.
MonthView Control
Allows the end user to pick dates and contiguous ranges of dates from a graphic
representation of a calendar.
Visual Basic 6.0 provides number of new functions for working with strings. They
are:
Function Description
Most application include extensive data validation routines. Depending on the type
of data being entered by the user, data validation ranges form a single VBA
statement to extensive modules containing dozens or hundreds of lines of coed. By
using Visual Basic’s object oriented programming features, it’s possible to wrap all
data validation routines into a single object that can be used by setting its properties
and invoking its methods.
Click the Start button in Windows Taskbar, choose Microsoft Visual Basic 6.0 group
and click the Microsoft Visual Basic 6.0 item.
-- Or --
Simply double click the Microsoft Visual Basic 6.0 icon on the Desktop.
Standard EXE It is a typical project type and used to create standard executable files.
ActiveX EXE, ActiveX DLL These types of projects are used to created ActiveX code
components which are OLE automation servers. These two types are of projects are
identical in functionality, but are packaged differently (as executable files or
Dynamic Link Libraries).
ActiveX Control This type of project is used to create new ActiveX controls.
Data Project It creates a project that automatically includes Data Report and Data
Environment.
ActiveX Document EXE, ActiveX Document DLL These project types are used to
ActiveX documents, which are in essence Visual Basic applications that can run in
the Web browser such as Internet Explorer.
IIS Application, DHTML application These projects are used to create Internet
Applications for both Server-side and Client-side.
The New Project dialog box as in Figure 2.1 has three tabs:
• New
• Existing
• Recent
The New tab allows to select the type of a new project, as explained already.
Switching to the Existing tab will enable to select an existing project and open it.
Switching to the Recent will enable to select and open the most recently worked
projects during the last few days.
Select the Standard EXE icon in the New Project window, and click the OK button.
This will open the Integrated Development Environment (IDE) as in Figure 2.2
The menu bar contains the commands needed to work with the Visual Basic. The
basic menus are:
File Contains the commands for opening and saving projects and creating
executable files and list of recent projects.
Edit Contains editing commands (Undo, Copy, Paste, and so on) plus a
number of commands for formatting and editing code (Find, Replace).
Run Contains the commands that start, break, and end execution of the
current
application.
The Toolbars
from the Toolbars command on the View menu. For example, to view the Debug
Toolbar, choose View | Toolbar and check the Debug option. Likewise to hide the
Debug follow the same procedure, but this time uncheck the Debug option.
Toolbars can be docked beneath the menu bar or can "float" if the vertical bar on the
left edge is selected and dragged away from the menu bar. Each Toolbar and its brief
description are given below.
Standard toolbar is just below the menu bar and is displayed by default.
The Form Editor menu contains the commands of the Format menu.
Lists the forms and modules in current project. A project is the collection of files that
is used to build an application.
The project components are organized in folders, and the Project Window is called
Project Explorer because it resembles the look of the Windows Explorer.
The Toolbox
The Toolbox contains the icons of the controls that can be placed on a form to create
the application's user interface. By default, the Toolbox contains the pointer icon and
the icons of 20 intrinsic controls.
The Properties Window contains the property settings for the selected control.
Properties are attributes of an object, such as its size, font, background color and so
on. By setting these properties the appearance of the selected control can be adjusted
easily. For example to change the caption and appearance of a command button
follow the steps given below:
¾ Select the command button icon on the Toolbar and draw the button on the
Form. The button will appear with its default name as its caption, as in
Figure 2.3 Command button with its default name as its caption.
¾ Make sure that the command button is selected and press F4 or click the
Properties window to make it as active.
¾ In the Properties Window (Figure 2.4) locate the Caption property and change its
value as Click &Me.
¾ Placing ampersand before the letter M will make the caption of the command
button to appear as Click Me. It meaning is that this button can be pressed by
using keyboard characters Alt and M (Alt+M).
¾ Select the Inactive Title Bar color. Now the command button will appear as in
Figure 2.6
Note: When the color selection box is displayed, its Palette tab might be
active by default. This tab will show the colors alone. To view each
color’s description switch to the System tab.
The Form Designer enables to add controls, graphics, and pictures to a Form to
define the interfaces in the desired look. Each Form in an application has its own
Form designer. The Form Designer displays two windows for each Form.
Double clicking on a Form will bring its code window front. Double clicking on a
Form name in the Project Explorer window will bring the Form to the front. Or to
switch between these window easily, the View Code and View Form at the top of the
Project Explorer window (Figure 2.7) can be used.
Figure 2.7 Icons at the top of the Project Explorer to switch between Code and Form
window.
The Form Layout window helps to position the forms of an application using a small
graphical representation of the screen. This window is very useful in the application
that uses multiple forms, because each form's position can easily be specified with
respect to the main form. For example, assume that an application contains three
forms. The Form Layout window will show the layouts of the all the three forms.
Mouse can be used to drag these layouts to the desired location as in Figure 2.8
When the application shows all the Forms, they will appear in the screen as in Figure
2.9
Figure 2.9 Forms – appearing on the Desktop as positioned in the Form Layout
window.
Context Menus
environment where the mouse is right clicked. For example context menu displays
items namely Components..., Add Tab..., Dockable, and Hide, when the mouse is
right clicked on the Toolbox (Figure 2.10).
Figure 2.10 Context menu that appears when the right mouse Button is clicked on the
Toolbox.
Microsoft Visual Basic Scripting Edition, the newest member of the Visual Basic
family of programming languages, brings active scripting to a wide variety of
environments, including Web client scripting in Microsoft Internet Explorer and Web
server scripting in Microsoft Internet Information Server. No scripting language
including VBScript has disc-accessing features and so it is accepted to be a safe
language to deploy in the web.
Easy to Use and Learn
If you already know Visual Basic or Visual Basic for Applications, VBScript will be
very familiar. Even if you don't know Visual Basic, once you learn VBScript, you're
on your way to programming with the whole family of Visual Basic languages.
It is a free language and so it can be used anywhere. We can write our VBSCRIPT
program in notepad and execute it using Internet Explorer. You can use the SCRIPT
element to add VBScript code to an HTML page.
Any scripting language can be enclosed within a script tag in an ordinary HTML file.
The script tag can be placed anywhere in the HTML page and it is better to place it in
the head tag. We should mention the language as an attribute. It is a container tag.
</script>
) IDE describes the Interface and environment that we use to create our
application
) VBScript has disc-accessing features and so it is accepted to be a safe
language
Lecture - 3
Program Constructs
Objectives
About Variable
About constant
Lecture unit - 3
3.2 Variables
3.3 Constants
3.4 Operators
3.6 Arrays
3.9 Functions
Visual Basic is only a basic element of the application. The code for this interface
must be written to define the application’s behavior. As with any modern
programming language, Visual Basic supports a number of common programming
constructs and language elements. This chapter introduces the programming
fundamental of Visual Basic.
3.2 Variables
In Visual Basic, as in any other programming language, variables store values during
a program's execution. A variable is a named storage location that can contain a
value, which can be modified during the program execution or if the value of a
specified memory location changes at run time then it is defined to be a variable. The
name with which we assign or manipulate the memory location at runtime is called a
variable [Link] variable has a name (which uniquely identifies it), value and
type. For example, the variable Name can have the value "Ram", and the variable
Age can have the value 24. Here Name and Age are variable names and "Ram" and
24 are their values, and String and Integer are types of variables Name and Age
respectively.
Declaring Variables
Note: The Compiler is a translator that translates the programming code into the
machine’s understandable form in order to make it ready for execution.
A variable name:
Explicit Declarations
To declare variables and to allocate storage space the Dim statement is used as in the
following:
The first variable, meters will store an integer value such as 10 or 388, and the second
variable, greetings, will store a text such as "Happy BirthDay". When the compiler
finds a Dim statement, it creates placeholder by reserving some space in memory and
assigning a name to it. Each time this name is used in subsequent statements, Visual
basic uses this area in memory to read or set its value. For instance, when the
following statement is used:
meters = 143
Visual Basic places the value 143 in the placeholder reserved for the variable meters.
When the program asks for the value of this variable, Visual Basic reads it from the
same area of memory. The following statement:
[Link] meters
Causes Visual Basic to retrieve the value from the area of memory named meters and
prints it the immediate window Form.
Note: The Print method with Debug prefix sends output to the Immediate window.
Using the Print method in this way is helpful to examine the values of the
variables in much easier way.
A single statement can both read and set the value of a variable. The following
statement increases the value of the meters variable:
meters = meters + 1
Visual Basic reads the value (say 143), adds 1 to it, and then stores the new value
(144) in the same memory location.
Implicit Declarations
Variables can also be used with out declaring them. When Visual Basic meets an
undeclared variable name, it creates a new variable on the spot and uses it. The new
variable's type is Variant, the generic data type that can accommodate all the data
types. Visual basic adjusts the undeclared variable’s type according the value
assigned to it. For example when an undeclared variable is used as follows:
var1 = 1000
Visual basic creates a variable named var1 of Variant type and adjusts its type to
Integer and an integer value (in this case 1000) is assigned to it.
Types of Variables
The type of a variable determines how to allocate storage space in the computer's
memory to their values. All variables have a type that determines what kind of data
they can store.
Numeric
String
Variant
Date
Object
Visual Basic supplies several numeric data types — Integer, Long (long integer),
Single (single-precision floating point), Double (double-precision floating point), and
Currency. Using a numeric data type generally uses less storage space than a variant.
If it is known that a variable will store whole numbers (such as 12,388,62, etc.) rather
than numbers with a fractional amount (such as 3.57, 0.7876, etc.) then it is better to
declare it as an Interger or Long type variable. Operations are faster with integers,
and these types consume less memory than other data types.
Different type of variables can be declared in a single Dim statement. For example,
the following declaration statements
Single and Double are two basic data types for storing floating-point numbers
(numbers that have a fractional part), and the Double type can represent these
numbers more accurately than the Single type. The following statements
a=1/3
[Link] a
0.3333333
a = a * 100000
The above result is not accurate, as it is not rounded properly. If this result is divided by 100000, its result will be
0.3333334, which is different from the initial result (0.3333333). This is an important point in numeric calculations, and it is
called error propagation. In long sequences of numeric calculations, errors propagate. If the above same operation is
performed with the variable b, which is declared as Double as in the following;
b=1/3
[Link] b
B = b * 100000
[Link] b
0.333333333333333
33333.3333333333
The choice of data types for variables can make a difference in the results of
the calculations. The proper variable types are determined by the nature of the
values they present. The choice of data types is frequently a tradeoff between
precision and speed of execution (less precise data types are manipulated faster).
The following table shows range and storage space allocated for each type of
numeric variable.
Data type
Storage Range
size
Integer 2 bytes -32,768 to 32,767
Long
4 bytes -2,147,483,648 to 2,147,483,647
(long integer)
Single -3.402823E38 to -1.401298E-45 for
(single-precision 4 bytes negative values; 1.401298E-45 to
floating-point) 3.402823E38 for positive values
-1.79769313486232E308 to
Double -4.94065645841247E-324 for negative
(double-precision 8 bytes values; 4.94065645841247E-324 to
floating-point) 1.79769313486232E308 for positive
values
Currency -922,337,203,685,477.5808 to
8 bytes
(scaled integer) 922,337,203,685,477.5807
The Byte type holds basically an integer in the range 0 to 225 and they are declared
with the following statement.
As the name implies bytes allocated in the memory for Byte data type is one. Bytes
variables are frequently used to access binary files, image and sound files, and so on.
All operators that work on integers work with the Byte data type except unary
minus. Since Byte is an unsigned type with the range 0-255, it cannot represent a
negative number.
String Variables
The String data type stores only text, and string variables are declared with the
following statement:
Dim varname as string
By default, a string variable is a variable-length string; the string grows or shrinks as
new data is assigned to it. String variables can also be declared with fixed length as
in below:
Syntax
For example, to declare a string that is always 50 characters long, the following
statement is used:
If a string variable's size will change drastically during the course of an application, it
is better to declare it as fixed-length to prevent Visual Basic from having to resize it
constantly, which slows down the execution speed.
The Boolean data type stores True/False values. Although a single bit would be
adequate, for efficiency reasons Visual Basic allocates two bytes to this data type.
Boolean variables are in essence integers that take the value -1(for True) and 0 (for
False). Boolean variables are declared as
These variables are combined with the logical operators AND, OR and NOT. The
NOT operator toggles the value of a Boolean variable. The following statement:
Running = NOT Running
is a toggle. If the variable Running is True, it's reset to False, and vice versa. This
statement is a shorter way of coding the following:
running = False
Else
Running = True
End If
Date and time values are stored internally as in a special way. A variable declared as
Date:
Can store both date and time values. The following are all valid assignments:
expiration = "01/01/1999"
expiration = "01/23/1999"
expiration = "13:03:05 AM"
expiration = "02/23/1999 13:03:05 AM"
Two date variables can be subtracted know the difference as in the following:
Integer values can be added to a Date variable to add days. For example, if Date1
holds the date "01/01/1999" the following line
[Link] Date1 + 10
Will print the value "01/11/1999"
Note: To add an hour to a Date variable, add 1/24 of a day; to add a minute add
1/(24*60) of a day.
Object Variables
Object variables are stored as 32-bit (4-byte) addresses that refer to objects within an
application or within some other application. A variable declared as Object is one
that can subsequently be assigned (using the Set statement) to refer to any actual
object recognized by the application.
For example, it has been assumed that a Form in a Visual Basic application has two
command buttons namely Command1 and Command2. And two object variables
are declared as follows:
Set a = Command1
Set b = Command2
From now on the command buttons’ properties can be manipulated through the
variables a and b. To change the Caption property of the first command button, the
following statement is used:
[Link] = True
This section just briefed about object variables. Objects and Object variables are
explained in detail in the chapter “Object Programming in Visual Basic”
Dim var
Or for cleaner code it can be declared as Dim var as Variant. Variant variable can be
used in both numeric and string calculations. There is no need to perform any type
conversions. Visual Basic automatically performs any necessary conversion. For
Example
'two-character string)
In some situation variables has to be converted from one type to another. For
example, an automatically generated number may have to be concatenated with a
prefix to produce an another string say Employee Id (something like AAA1001).
Concatenation can take place only on strings. So, first the number has to be
converted into a string, and then it can be concatenated with the prefix. The CStr
function converts an expression into a sting. The following example explains this
process.
Dim EmployeeId as String
Dim AutoNum as Integer
CBool Boolean
CByte Byte
CCur Currency
CDate Date
CDbl Double
CInt Integer
CLng Long
CSng Single
CStr String
CVar Variant
Special Values
Generally variables have value. Before any value is assigned to them, numeric
variables are zero, and string variables are zero length (""). There are, however, two
special values: Empty and Null.
If a variant variable is declared but not initialized then its value is Empty. The
Empty value is different from a zero-length string. The IsEmpty() function can be
used to find out whether a variant variable, say someVariable, is initialized or not as
in the following:
The IsEmpty function will return a Boolean value. That is, it will return True, if the
variable is not initialized or False, if the variable is initialized.
Besides setting the types of the various variables and converting between types, the
type of a variable can be examined by using the VarType and TypeName functions.
For example, a variable might be declared of variant type. But it will be converted to
a specific type automatically by Visual Basic according to its current value. In this
sense to know the new type either VarType or TypeName functions can be used.
Both functions accept as argument the name of a variable, and they return a number
(the VarType() function) or a string (the TypeName() function) indicating the type of
the variable.
The VarType() function returns one of the numbers shown in Table3.2, depending on
the type of the argument.
Example
This example uses the VarType function to determine the type of a variable.
Note: The single quote (‘) in the above statements indicates the beginning of
comment, which will be ignored by Visual Basic.
While checking the type of the variables, it is hard to remember the return value that
corresponds to a specific type. So instead of numeric values constants (listed in Table
3.2) can be used as in the following:
This function returns the type of a variable as a string as the following example
shows:
There is another set of functions that returns variables’ data types, but not the exact
type. They are:
Visual Basic doesn't enforce variable declaration. However, declaring all variables
will help to write clean code and will simplify debugging. So, to enforce Visual Basic
for variable declarations, the following statement has to be placed in the declaration
section of a Form or Module.
Option Explicit
This statement tells the compiler to check each variable and issue an error message if
it is used without declaration. If this statement is omitted, then Visual Basic creates
variables as needed.
If the Require Variable Declaration check box is checked in the Options dialog box’s
Editor tab (Figure 3.1), which appears when Tools | Option is chosen, Visual Basic
automatically inserts the Option Explicit statement in any new modules, but not in
existing modules. To enforce the variable declaration in the existing module Option
Explicit statement must manually be typed.
Figure 3.1 Editor tab of Options dialog box in which Require Variable
Declaration checkbox is checked.
A variable's scope
If a variable is declared within a procedure, only the code in the specific procedure
has access to that variable. This variable doesn't exit for the rest of the application.
This variable's scope is limited to a procedure, and it's called local.
Example
Sub Command1_Click()
Dim i as Integer, j as Integer
----------------------------
----------------------------
End Sub
The variables i and j are declared inside the Command1_Click() procedure and so,
they are local variables and accessible only within this procedure. If a variable has
to be accessed by all procedures then it has to be declared in the declaration section.
Finally, in some situations the entire application must access a certain variable. In
this case, the variable must be declared as Public. Public variables have a global
scope (they are visible to any part of variable). To declare a Public variable, Public
statement is used instead of Dim statement as follows:
Public a as Integer
Moreover, Public variables may not appear inside procedures. They must be
declared in a standard module.
In addition to type and scope, variables have a lifetime, the period during which they
retain their value. Variables declared as Public exist for the lifetime of the
application. Local variables, declared within procedures with the Dim or Private
statement, live for as long as the procedure in which they are declared. When the
procedure finishes, the local variables cease to exist, and the allocated memory is
returned to the system. The same procedure can be called again, of course. In this
case, the local variables are recreated and initialized again.
However, a local variable can be forced to preserve its value, with the Static
keyword. Static keyword is used to declare variables inside a procedure, exactly in
the same way as Dim statement as in the following:
Static Depth
For example, the following function calculates a running total by adding a new value
Function RunningTotal(num)
Static ApplesSold
ApplesSold = ApplesSold + num
RunningTotal = ApplesSold
End Function
If ApplesSold was declared with Dim instead of Static, the previous accumulated
values would not be preserved across calls to the function, and the function would
simply return the same value with which it was called.
The same result can be produced by declaring ApplesSold in the Declarations section
of the module, making it a module-level variable. However, the procedure no longer
has exclusive access to it. Because other procedures can access and change the value
of the variable, the running totals might be unreliable and the code would be more
difficult to maintain.
3.3 Constants
Some variables don't change value during the execution of a program. These are
constants that appear many times in the program code. For example if a program
does math calculations, the value of pi ( 3.14159.... ) may appear many times in the
program code.
These values are best represented by constants. Instead of typing the value 3.14159
over and over again, a constant can be defined with a constant name, say pi , and it
can be used in the program code as follows:
Area = pi * Radius ^ 2
Pi could be declared as a variable, but constants are preferred for two reasons:
1. Constants can't change value: This is a safety feature. Once a constant has been
declared, its value can not be changed in subsequent statements, it can be assured
that the value specified in the constant's declaration will take effect in the rest of
the program.
2. Constants are processed faster than variables: When the program is running, the
values of constants don't have to be looked up. The compiler substitutes constant
names with their values, and the program executes faster.
Often you'll find that your code contains constant values that reappear over and
over. Or you may find that the code depends on certain numbers that are difficult to
remember — numbers that, in and of themselves, have no obvious meaning.
In these cases, you can greatly improve the readability of your code — and make it
easier to maintain — by using constants. A constant is a meaningful name that takes
the place of a number or string that does not change. Although a constant somewhat
resembles a variable, you can't modify a constant or assign a new value to it as you
can to a variable. There are two sources for constants:
In Visual Basic, constant names are in a mixed-case format, with a prefix indicating
the object library that defines the constant. Constants from the Visual Basic and
Visual Basic for applications object libraries are prefaced with "vb" — for instance,
vbTileHorizontal.
The prefixes are intended to prevent accidental collisions in cases where constants
have identical names and represent different values. Even with prefixes, it's still
possible that two bject libraries may contain identical constants representing
different values. Which constant is referenced in this case depends on which object
library has the higher priority.
To be absolutely sure you avoid constant name collisions, you can qualify references
to constants with the following syntax:
[libname.][modulename.]constname
Libname is usually the class name of the control or library. Modulename is the name
of the module that defines the constant. Constname is the name of the constant. Each
of these elements is defined in the object library, and can be viewed in the Object
Browser.
The argument constantname is a valid symbolic name (the rules are the same as
those for creating variable names), and expression is composed of numeric or string
constants and operators; however, you can't use function calls in expression.
You can place more than one constant declaration on a single line if you separate
them with commas:
The expression on the right side of the equal sign ( = ) is often a number or literal
string, but it can also be an expression that results in a number or string (although
that expression can't contain calls to functions). You can even define constants in
terms of previously defined constants:
Once you define constants, you can place them in your code to make it more
readable. For example:
A Const statement has scope like a variable declaration, and the same rules apply:
• To create a constant that exists only within a procedure, declare it within that
procedure.
• To create a constant available to all procedures within a module, but not to any
code outside that module, declare it in the Declarations section of the module.
Because constants can be defined in terms of other constants, you must be careful not
to set up a cycle, or circular reference between two or more constants. A cycle occurs
when you have two or more public constants, each of which is defined in terms of
the other.
For example:
' In Module 1:
Public Const conA = conB * 2 ' Available throughout
' application.
' In Module 2:
Public Const conB = conA / 2 ' Available throughout
' application.
If a cycle occurs, Visual Basic generates an error when you attempt to run your
application. You cannot run your code until you resolve the circular reference. To
avoid creating a cycle, restrict all your public constants to a single module or, at
most, a small number of modules.
3.4 Operators
1. Arithmetic Operators
The table lists the operators available in vbscript and most of them are self-explanatory.
Arithmetic operators
Logical Operators
Logical Operators follows a set of rules, which can be used with comparison
statements.
A B Y
0 0 0
0 1 0
1 0 0
1 1 1
Y refers output
0 considered False
1 considered True
Most programs store sets of data of different types. For example, a program for
maintaining a company's system information must store several pieces of
information for each system; the system brand, its cost, and its purchase date etc. All
these information should be stored together. To achieve this user defined data types
are used. They are useful to create a single variable that records several related
pieces of information.
User-defined data types are created with the Type statement, which must be placed
in the Declarations section of a module.
Syntax
Type varType
variable1 as varType
variable2 as varType
--------------------
--------------------
End Type
After this declaration, variables can be created of this type and manipulated as all
other variable (with a little extra typing).
Example
This example shows how to create a user defined data type SystemInfo that holds the
System Information.
Type SystemInfo
Brand as String
Cost as Currency
PurchaseDate as Date
End Type
From now onwards variables can be declared of the SystemInfo type in the same way
as regular variables are declared. To define variables of this type, the following
statement is used.
To assign value to these variable, values to each one of its components (called as
fields) must separately be assigned, which can be accessed by combining the name of
the variable and the name of a field separated by a period, as in the following:
3.6 Arrays
Salary(0) = 1000
All elements in an array have the same data type. Of course, when the data type is
Variant, the individual elements can contain different kinds of data. By default, the
first element of an array has index 0 (lower - bound) and the number that appears in
parentheses in the Dim statement is the array's upper limit (upper - bound).
However, the array's first element need not be zero. Lower limit (lower - bound) can
explicitly be specified as in the following:
Suppose if the array Salary contains salaries of all the employees, one thing that is to
be remembered is which person corresponds to each salary. This can be avoided by
declaring an another array Names as in the following:
Now values to the elements of both arrays can be assigned as in the following:
Names(0) = “Ekambaram”
Salary(0) = 20000
Names(1) = “Prema”
Salary(1) = 15000
Names(2) = “Gayathri”
Salary(2) = 50000
----------------------
----------------------
Note: If the index value that is used to access a element of an array, is not between
the array’s lower limit and upper limit, Visual Basic will generate an error
“Subscript out of range” at run time.
Multi-Dimentional Arrays
Sometimes when storing values in an array, its related information has also to be
stored. For example, to keep track of each pixel on a computer screen, both X and Y
coordinates are to be referred. This can be done using a multidimensional array to
store the values.
The above statement declares a two-dimensional 10-by-10 array. But arrays can be
extended for more dimensions as in the following:
This declaration creates an array that has three dimensions with sizes 4 by 10 by 15.
The total number of elements is the product of these three dimensions, or 600.
The benefit of using multidimensional arrays is that they are conceptually easier to
manage. The following example demonstrates this.
Example
In a game board, positions of certain pieces are to be tracked. Each square on the
board is identified by two numbers, its horizontal and vertical coordinates. The
obvious structure for tracking the broad’s squares is a two-dimensional array, in
which first index corresponds to the row number and the second index corresponds
to the column number. The array could be declared as follows:
Board(1,1) = 0
Board(3,5) = 1
To find out whether a piece on the bottom right squae the following statements are
used:
If Board(10,10) = 1 then
{ Piece found }
Else
{ Empty Square }
End if
Dynamic Arrays
Sometimes when declaring arrays its required size may not be known. Instead of
making it large enough to hold the maximum number of data (which means the most
of the array may be empty), arrays can be declared dynamically.
A dynamic array can be resized at any time. Dynamic arrays are among the most
flexible and convenient features in Visual Basic, and they help to manage memory
efficiently. For example, a large array can be used for a short time and then can be --
freed up memory to the system when that array is no longer used.
Dynamic arrays are crearted in the same way as normal arrays, but without
specifying it dimensions as in the following:
Dim DynArray()
Later in the program, when the number of elements to be stored in the array is
known, the Redim statement is used to redimension the array with the required size
as follows:
The ReDim statement can appear only in a procedure. Unlike the Dim statement,
Redim is executable and so, can appear only inside a procedure. An array can be
redimensioned to multiple dimensions as follows:
ReDim Matrix(9,9,9)
Note: The ReDim statement can't change the type of the array. Moreover,
subsequent ReDim statements can change the bounds of a array and number
of its dimensions.
Whenever the ReDim statement is executed, all the values currently stored in the
array are lost. Visual Basic resets the values to the Empty value (for Variant arrays),
to zero (for numeric arrays), to a zero-length string (for string arrays), or to Nothing
(for arrays of objects). The Preserve Keyword is used to resize an array without
losing its contents. For example if an array is having 15 elements and have to be
resized to hold 25 elements, without losing its contents, then the preserve keyword is
used at redimension as in the following:
Rem comments
Syntax
Rem comment
or
' comment
The comment argument is the text of any comment you want to include. After the
Rem keyword, a space is required before comment.
Note : If you use line numbers or line labels, you can branch from a GoTo or
GoSub statement to a line containing a Rem statement. Execution
continues with the first executable statement following the Rem
statement. If the Rem keyword follows other statements on a line, it must
be separated from the statements by a colon (:).
You can use an apostrophe (') instead of the Rem keyword. When you use an
apostrophe, the colon is not required after other statements.
Statement Description
End Terminates execution immediately. Never required by itself
but may be placed anywhere in a procedure to end code
execution, close files opened with the Open statement and to
clear variables.
End Function Required to end a Function statement.
End If Required to end a block If…Then…Else statement.
When executed, the End statement resets all module-level variables and all
static local variables in all modules. To preserve the value of these variables,
use the Stop statement instead. You can then resume execution while
preserving the value of those variables.
Note The End statement stops code execution abruptly, without invoking the Unload,
QueryUnload, or Terminate event, or any other Visual Basic code. Code you have
placed in the Unload, QueryUnload, and Terminate events of forms and class
modules is not executed. Objects created from class modules are destroyed, files
opened using the Open statement are closed, and memory used by your program
is freed. Object references held by other programs are invalidated.
The End statement provides a way to force your program to halt. For normal
termination of a Visual Basic program, you should unload all forms. Your
program closes as soon as there are no other programs holding references to
objects created from your public class modules and no code executing.
3.9 Functions
The NextDay() function returns tomorrow's date by adding 1 day to the current date.
Because it must report the result to the calling program, the NextDay() function has a
type, as do variables, and the result is assigned to its name (Which can’t be done with
subroutines).
The Exit Function statement causes an immediate exit from a Function procedure, as
the Exit Sub statement does in the subroutine. Program execution continues with the
statement following the statement that called the function.
Displays a prompt in a dialog box, waits for the user to input text or click a button,
and returns the content entered by the user.
Syntax
Argument Description
Required. String expression displayed as the message in the dialog
Prompt
box.
Optional. String expression displayed in the title bar of the dialog
Title
box. If omitted, the application name is placed in the title bar.
Optional. String expression displayed in the text box as the default
Default response if no other input is provided. If omitted, the text box is
displayed empty.
Optional. Numeric expression that specifies, in twips, the horizontal
Xpos distance of the left edge of the dialog box from the left edge of the
screen. If omitted, the dialog box is horizontally centered.
Optional. Numeric expression that specifies, in twips, the vertical
distance of the upper edge of the dialog box from the top of the
Ypos
screen. If is omitted, the dialog box is vertically positioned
approximately one-third of the way down the screen.
Table 3.3 Arguments of InputBox function.
Example 1
The above statement will display the Input box as in Figure 1.13
Figure 3.2 Inputbox with Project’s title and without default value.
When the user enters his name and clicks OK, the InputBox returns his name to the
variable Name.
Example 2
The above statement will display the Input box as in Figure 1.14
If the user clicks OK without entering anything the default value 25 will be returned
by the InputBox to the variable Age.
Note: Though InputBox returns only strings, when they are assigned variables of
other types, Visual Basic makes necessary type conversions automatically.
Displays a message in a dialog box, waits for the user to click a button, and returns
an Integer indicating which button the user clicked.
Syntax
The prompt and title arguments are same as in InputBox function. The buttons
argument is a numeric expression that is the sum of values specifying the number
and type of buttons to display, the icon style to use, the identity of the default button,
and the modality of the message box. If omitted, the default value for buttons is 0. It
settings are given in the following table 1.4
Example 1
End If
The MsgBox function in this example, displays a message box with Yes and No
button as in Figure 1.16
When the user clicks one the buttons, the MsgBox function returns either vbYes or
vbNo, which is subsequently checked in the code for further execution.
Example 3
More than one option can be specified in the buttons argument by using the plus (+)
operator as in the following:
This statement displays the message box with critical icon and No button (2nd button)
as the default button, as in the Figure1.17.
Figure 3.7 Msgbox with critical icon and 2nd button as default.
Programs are not monolithic sets of commands that carry out the same calculations
every time they are executed. Instead, they adjust their behavior depending on the
data supplied or based on the result of a test condition. Visual Basic provides three-
control flow, or decision, structures to take a course of action depending on the
If..Then
If...Then...Else
Select Case
If...Then...End If
The If structure test the condition specified and, if it it's True, executes the
statements(s) that follow. The If structure can have a single-line or multiple-line
syntax.
This statement can be broken into Multiple lines, as it will be easier to read as
follows:
When a statements that is to be executed, are placed next to the If statement’s line, to
mark the end of If block End If statement is used as in the above example.
If...Then...Else...End If
A variation of the If...Then is the If...Then...Else statement, which executes one block
of statements if the condition is true and another if the condition is false.
Syntax
If condition Then
statementblock - 1
Else
statementblock - 2
End If
Visual Basic evaluates the condition. If it's True, it executes the first block of
statements and then jumps to the statement following the End If statement. If the
condition is False, Visual Basic ignores the first block of statements and executes the
block following the Else keyword.
Example
If Salary > 5000 Then
DaPercent = 100
HraPercent = 80
Else
DaPercent = 80
HraPercent = 60
End If
Another variation of the If...Then...Else statement uses several conditions, with the
Elseif keyword:
Syntax
If condition1 Then
statementblock - 1
Elseif condition2 Then
statementblock - 2
Elseif condition3 Then
statementblock - 3
Else
statementblock - 4
End If
A If statement can have any number of Elseif clauses. The conditions are evaluated
from the top, and if one of them is True, the corresponding block of statements is
executed. The Else clause will be executed if none of the previous expressions is
True.
Example
If score > 90 Then
Result = "Excellent"
Elseif score > 75 Then
Result = "Very Good"
Elseif score > 50 Then
Result = "Good"
Else
Result = "Failed"
End If
This statement is easier to read, but not as efficient in terms of execution time
because Visual Basic evaluates all conditions, even if the first one is True. This
inefficiency is overcome with Select Case statement.
Select Case
The select case structure compares the same expression to a different value. The
advantage of the select case statement over multiple [Link] statements is that it
makes the code easier to read and maintain.
Syntax
Loop statements allow to execute one or more lines of code repetitively. Many tasks
consist of trivial operations that must be repeated over and over again, can be done
using loop statements. Visual Basic supports the following loop statements:
Do...Loop
For...Next
For Each...Next
Do...Loop
Do While condition
statements
Loop
When Visual Basic executes this Do loop, it first tests condition. If condition is False
(zero), it skips past all the statements. If it's True (nonzero), Visual Basic executes the
statements and then goes back to the Do While statement and tests the condition
again.
Consequently, the loop can execute any number of times, as long as condition is
nonzero or True. The statements never execute if condition is initially False.
Example
In this example the loop block is executed while the variable I is equal to 10.
Dim I as Integer
I = 10
Do While I=10
-------------
I = {someExpression} ‘ SomeExpression may return 10 or
‘other value
Loop
When the condition I=10 is tested, the result will be True as I holds the value 10. So
the execution of the loop block will begin. If someExpression returns 10, the loop
block will be executed again. Otherwise the execution will jump to the next
statement of the loop block.
Another variation of the Do...Loop statement executes the statements first and then
tests condition after each execution. This variation guarantees at least one execution of
statements:
Do
Statements
Loop While condition
There are two more variations of Do..Loop statements, which uses Until instead of
While. They are analogous to the previous two except that they loop as long as
condition is False rather than True.
Do Until condition Do
statements statements
Loop Loop Until condition
Example
This example prints the value of the variable I until it becomes equal 10.
Dim I as Integer
I=0
Do Until I = 10
[Link] I
I=I+1
End If
In this example when the condition I = 10 is tested, the result will be False and the
loop block will be executed. When the I becomes equal to 10 the condition will
return True, the execution will jump to the next statement of the loop block. So the
output of the above code will be 0 to 9.
For...Next
Syntax
The arguments counter, start, end, and increment are all numeric.
The following code prints the names of all the available Screen fonts:
Dim I As Integer
For i = 0 To [Link]
Print [Link](i)
Next
For Each...Next
Syntax
statements
Next element
Example
----------------------------
----------------------------
For Each Item In Age()
Print Item
Next
WITH ... ENDWITH provides a convenient way to specify a number of properties for
a single object. Note that you can also execute methods from within a
WITH ... ENDWITH [Link] multiple properties for an object.
Syntax
WITH ObjectName
Statements
ENDWITH
ObjectName Specifies the name of the object. ObjectName can be the name
of the object or a reference to the object.
The following example creates a custom class name Employee. After the
Employee class has been created with CREATEOBJECT( ),
WITH ... ENDWITH is used to set multiple properties for the class. The
properties values are then displayed.
moemployee = CREATEOBJECT('employee')
WITH moemployee
.First_Name = 'John'
.Last_Name = 'Smith'
.Address = '16 Maple Lane'
.HireDate = {^1998-02-16}
ENDWITH
CLEAR
? moemployee.First_Name + ' '
?? moemployee.Last_Name
? [Link]
? [Link]
) Constant is an entity whose value does not change during the program
execution.
) Arrays are nothing but user defined datatypes used to keep a set of values in it
) Loops are used to execute a single (or) set of statements at ‘n’ time.
Exercise 1
1. (Declaring Variable)
2. Open a new standard EXE project
3. Add four text boxes and a command button to the form
4. Open the code window of the form
5. Place the code Option Explicit as the first line of the declarations section of
the form. This forces the variables to be declared before they are used.
6. Open the event procedure for the Click event of the command button.
You can do this by selecting the name of the command button from the
object list on the left of the code window.
7. Use the following statements to create the variables for calculating area
and perimeter. These statements should be place at the top of the event
procedure
8. Dim sngRoomLength As Single, sngRoomWidth As Single
9. Dim sngRoomArea As Single, sngRoomPerimeter As Single
10. Place the following code in the event procedure to perform the
calculation. (Note, on of the variable names is intentionally misspelled to
illustrate how forced declaration helps you.)
sngRoomLength = Val([Link])
sngRoomWidth = Val([Link])
sngRoomArea = sngRoomLength * sngRoomWidth
sngRoomPerimeter = 2 * ( sngRoomLength + sng RoomWidth)
[Link] = val(sngRoomArea)
[Link] = val(sngRoomPerimeter)
Exercise 2
1. (Use If..Then..Else statement )
2. Open a new standard EXE project
Exercise 3
1. (Use Select ...Case statement )
2. Open a new standard EXE project
3. Place a text box , label and a command button in the form
4. Enter a number ( 0 or 1 or 2 )in the text box
5. On clicking the command button, the messages
6. God’s delays are not denials ( for 0)
7. A Single drop makes an Ocean ( for 1)
8. Hardwork and success go hand-in-hand ( for 2)
Lecture – 4
Controls
Objectives
Lecture unit - 4
4.2 Controls
In the previous chapter we have discussed about Variables, constants, loops and
control statements. This chapter will give the ways of creating and implementing the
Controls. It also helps us to understand the concept of Control Arrays. Controls are
used to receive user input and display ourput and has its own set of properties,
methods and events. Let us discuss few of these controls in this chapter.
4.2 Controls
Custom controls are the building blocks of a Visual Basic application. Controls are
used to add significant functionality to your programs, and they are easy to work. in
Visual Basic, forms are the foundations and are generally used to build programs. A
form is where you put all the things that people interact with as they use your
program. Those things you put on the form are controls, which enable the people
who use your program to do things, such as enter text and click buttons. That is,
controls are also interfaces between the user and the application. Every control has
got its own properties, events and methods. You can set the properties and write the
code to make the control active.
For example if you build a house, you start with a foundation – think of this as the
form. On top of the foundation, you add all the things that allow you use the house:
a floor, walls and doors. These things are the controls.
The Toolbox is the containing window that holds the custom controls for your
applications (see Figure 4.1). There are also several advanced controls that come with
Visual Basic. Some controls work with multimedia, and others utilize the Internet.
Best of all, you can now create your own ActiveX custom controls and add them to
your Toolbox.
You can add controls to a form in two ways: by double- clicking and by drawing.
Whenever you double-click an icon on the toolbar, the associated control appears on
your form. When you do this, though, you can’t control where the control goes;
you’re at the mercy of Visual Basic. When you draw a control on your form, you can
put it wherever you want it.
1. Select the control you want to delete by clicking it. The control you selected
will appear with a box at each corner and side
2. Press the Delete key.
You can also remove a control by right-clicking it. from the context menu that
appears and selecting Delete.
When you’re drawing controls on a form, you don’t have to be exact. It’s very easy to
make them bigger or smaller, and to put them in a different spot on the form.
In the Toolbox, select the Pointer tool (if it isn’t already selected). On your form,
select the control you want to resize. Grab a sizing handle with the mouse by moving
the pointer over it and then holding down the left mouse button. You know when
you’re over the sizing handle because the mouse pointer turns into a double-sided
arrow. While holding down the mouse button, notice that a box appears. The box
shows you what the size of the control will be. When it’s the right size, release the
mouse button. Changing the position of a control is also easy. Just click it to select it,
and drag it to its new position.
Intrinsic controls are automatically displayed in the tool box when a form is loaded.
When you program in Visual Program you’ll use a relatively small set of controls.
However, these controls are very powerful. With them, you can add buttons, check
boxes, labels and text boxes to your programs. You can use them to see files on your
hard drive right from your program. You can even read a database! These basic
controls are intrinsic controls.
Visual Basic Forms and controls are the basic elements in the user interface of any
Windows application. They are called as objects and they have their own properties,
methods and they react to external events. Properties can be thought of as an object's
attributes methods as its actions, and events as its responses.
An everyday objects like a child's helium balloon also has properties, methods and
events. A balloon's properties include visible attributes such as its height, diameter
and color. Other properties describe its state (inflated or not inflated), or attributes
that aren't visible such as its age. By definition, all balloons have these properties; the
settings of these properties may differ from one balloon to another.
A balloon also has inherent methods or actions that it might perform. It has an inflate
method (the action of filling it with helium), a deflate method (expelling its contents)
and a rise method (if you were to let go of it). Again, all balloons are capable of these
methods.
Figure 4.1 Objects have properties, respond to events, and perform methods.
Balloons also have predefined responses to certain external events. For instance, a
balloon would respond to the event of being punctured by deflating itself, or to the
event of being released by rising into the air.
If a balloon can be programmed, the Visual Basic code might look like the following.
To set the balloon's properties:
[Link] = Red
[Link] = 10
[Link] = True
In this code the object (Balloon) is followed by the property (.Color) followed by the
assignment
statement and substituting a different value. Properties can also be set in the
Properties window while the application is being designed.
[Link]
[Link]
[Link] 5
The syntax is similar to the property — the object (a noun) is followed by the method
(a verb). In the third example, there is an additional item, called an argument, which
denotes the distance to rise. Some methods will have one or more arguments to
further describe the action to be performed.
Sub Balloon_Puncture()
[Link]
[Link] "Bang"
[Link] = False
[Link] = 1
End Sub
In this case, the code describes the balloon's behavior when a puncture event occurs:
invoke the Deflate method, then invoke the MakeNoise method with an argument of
"Bang" (the type of noise to make). Since the balloon is no longer inflated, the Inflated
property is set to False and the Diameter property is set to a new value.
While developing a Visual Basic application the programmer has to decide which
properties should be changed, methods invoked or events responded to, in order to
achieve his goal.
Common Properties
• Appearance Its value can be either 0 for a flat look or 1 for a 3-D
look.
• Left, Top They set the coordinates of the object's upper left
corner. Using these properties, the location of an
object can be changed both at design time and run time.
The most basic object you will be working with in Visual Basic is the form object,
which is the visual foundation for building an application. It is basically a window
that you can add different elements to in order to create a complete application.
Every application you can see on the screen is based on some type of form. Before
going into the details of application development, let’s take a look at the most basic
form object that you will probably use the most often in your projects: the single
form.
As you learn Visual Basic, most of your applications will only have one interface,
which is the single form. When you become more experienced and start writing
letter, editor-styled applications, you may want to use multiple forms, called
documents.
The main characteristic of a form is the title bar, on which the form's caption is
displayed. On the left end of the title bar is the control menu icon. Clicking
on this icon opens the control menu. On the right side of the title bar are three
buttons-Minimize, Maximize, and Close. Clicking on these buttons
minimizes, maximizes and closes the Form. When a form is maximized, the
Maximize button is replaced by the Normal button, which restores the form to
its size and position before it was maximized.
Control Menu
Control Menu is a simple menu that allows you to restore, move, resize, minimize,
maximize and close the form. To enable this button on your form, set the form’s
ControlBox property to True in the form’s properties window or determines whether
the control-menu box is displayed on the form at run time. That is, if it is set to False
the control box won’t appear at left corner of the title bar of the Form.
The form’s border is what gives the form its elasticity. Depending on the type of form
you want to display, you can program the border to be fixed, sizable or even
nonexistent. These features can be set with the BorderStyle property.
The Caption
The form’s caption is the text you see in the form’s title bar. It can be used to identify
the name of the application, the current function of the form, or as a status bar. What
you put in the caption depends on what your program is trying to achieve. If you set
a form’s BorderStyle property to None, then caption (along with the whole title bar) is
hidden. You can modify the caption by setting the form’s caption property in the
Properties window to the text your want to display.
The title bar is the colored bar on the top of most forms. If your desktop color scheme
is set to the Windows default scheme, this bar will be blue. You can use the title bar
to drag the window around the screen. In addition, double-clicking on it will
alternately maximize and restore the form.
Maximize/Restore Button (Boolean)
The Maximize button has two purposes. If the form is in its normal state, that is its
normal size, you can click the Maximize button to stretch the current form to the size
of the screen or container of the form. A form’s container is also know as multiple
document interface (MDI) form. If the form is maximized, you can click this button
on your form, set the form’s MaxButton property to True in the Properties window.
MinButton (Boolean)
The Minimize button is used to minimize the current form, that is, move it out of the
way. To enable this button on your form, set the form’s Minbutton property to True
in the form’s Properties window.
The Close button’s sole purpose is to close the current window. In Visual Basic, you
can control whether the Close button is visible to the user with the ControlBox
property. The Close button will not be visible if the Control box, is not visible. If you
decide not to enable the Close button or the Control box, they you must use a menu
or a button to close the form.
Moveable (Boolean)
Determines whether the Form can be moved. That is, if it is set to False, the Form
will remain in it initial startup position. User can’t move it around screen. But it can
be resized.
StartUpPosition
Specifies the position of the Form when it first appears with one the values given in
the following table.
Value Description
0-Manual No initial is setting specified.
1-CenterOwner Center on the item to which the UserForm belongs.
2-CenterScreen Center on the whole screen.
3-WindowsDefault Position in upper-left corner of screen.
Set the visual state such as Maximized, Minimized or Normal of the Form at run time
with one the value given in the following table.
Value Description
0-Normal (Default) Normal.
1-Minimized Minimized (minimized to an icon)
2-Maximized Maximized (enlarged to maximum size)
Form Properties
Only few of the proprieties are used frequently, these are boldface in the above list-
the rest you’ll probably only use occasionally. You won’t see all these proprieties in
the Properties window. If you can’t see a certain property, it means it’s a run-time-
only property and can’t be set at design time.
Methods
Before listing the two important methods of the Form – Show, Hide, this section
briefs the possible states of a Form and two important statements – Load and
Unload.
Not loaded – The Form lives on a disk file and doesn’t take up any resources.
Loaded but not shown – The Form is loaded into memory, takes up the
required resources, and is ready to be displayed.
Loaded and shown – The Form is shown, and the user can interact with it.
The Load and Unload to load and unload the Forms. The Load statement has the
following syntax:
Load formName
And the Unload statement has this syntax:
Unload formName
The formName is the name of the Form to be loaded or unloaded. When Visual Basic
starts, it loads the default Form, say Form1, and displays it. To load other Forms, say
Form2, the load statement is to be issued as in below:
Load Form2
This statement will load the Form2 into the memory. But the Form2 will not be
visible immediately. To make it visible its Show method (explained shortly) must be
called. Once a Form is loaded, it takes over the required resources, so when the
Form is not needed it must be unloaded as in below:
Unload Form2
When a Form is unloaded, the resources it occupies are returned to the system and
can be used by other Forms and/or applications.
Show
This method is used to show a Form. If the Form is loaded but invisible, the Show
method brings the specified Form to the top. If the Form isn’t loaded, the Show
method loads it first, and then displays it.
Syntax
[Link] mode
The FormName is the Form’s name, and the optional argument mode determines
whether the Form will be modal or modeless. It can have one of the following
values:
• 0 - Modeless (Default)
• 1 - Modal
A modal Form takes total control of the application and won’t let the application
proceed unless the Form is closed. A modal Form, therefore, must have a Close
button or some means for the user to close it so that he can return to the Form from
which the Form was loaded.
Modeless Forms are the norm. They interact with the user, and they allow the user
to switch to any other Form of the application.
For example, in a text editor, say MS-Word, dialog box that appears when File |
Open is chosen is a Modal dialog. It won’t let user to go to the editing area unless
the dialog box is closed. On the other hand, the dialog box that appears for the Find
and Replace operation is a modeless dialog. It will let the user to go to the editing
Hide
This method removes a Form from the screen, but doesn’t unload it.
[Link]
When a Form is hidden, the user can’t interact with it. But application’s code can
manipulate the Form like the one in the following:
Note : Instead of calling the Show or Hide methods to show or hide a Form its Visible
Events
Activate
This event occurs when the Form becomes the active window either by user’s action
such as Clicking it, or by using the Show or SetFocus methods in code.
Deactivate
This event occurs when the Form is no longer the active window. A Form will be
become inactive, when the user switches his focus to some other Form, or by the
Hide method in code.
Load
This event occurs when the Form is loaded. Typically, this event procedure includes
initialization code for a Form – for example, code that specifies default settings for
controls, indicates contents to be loaded into ComboBox or Listbox etc.
Unload
This event occurs when the Form is unloaded. Generally, code for resetting
properties to their original values or for clean up operation is placed here, if
required.
using. You resize a form just as you resize a control: Grab one of its sizing handles with the
mouse and drag it to the proper size.
This section shows how to develop a simple Form application that contains three
Forms. The first Form (Form1) has command buttons to show and hide the other
Forms. It also accepts Captions to change the caption of all the Forms.
Arrange the controls so that the Form1 resemble the Figure 1.21
Option Explicit
Controls are elements that provide the User Interface. The User Interface is
what appears in the application's window when it runs. It enables the user to
work with the application such as entering text and clicking buttons. The
elements of the User Interface are common to all Windows applications and
they are called as Intrinsic Controls. They are all shown as icons in the Visual
Basic ToolBox.
The image control is similar to the Picturebox control and it can also display
images, but it supports only a few features of the Picture box control and requires
fewer resources.
The Shape control
The shape control is used to draw graphical elements, such as boxes and
circles on the surface of a Form.
This control is used to draw boxes on the form and to group other elements.
This section shows how to create an simple application with intrinsic controls.
Functioning of this application is explained shortly.
The above Form contains three Frames namely View, Explorer and Animation.
The View Frame has two check boxes whose checking and unchecking makes the
respective Frames Visible and invisible at run time. The second Frame contains
Drive, Directory and File list boxes, which behave like a mini Windows Explorer.
The label (lblPath) displays the full path of the selected file in the File list box. The
third frame contains a combo box, a list box and two corresponding option buttons.
Either the combo box or the list box will be visible at the run time. Selecting one of
the option buttons will make its corresponding control (combo box or list box)
visible and another invisible (Note that both List box and combo box are placed at
a same location). Both List box and combo box contains three items namely Taxi,
Tempo, and Auto whose selection will replace its corresponding picture in the
image control (imgVehicle). This control will move in forward and reverse
direction by adjusting its Left property according to the value set by the Horizontal
scroll bar in the Animation frame.
Option Explicit
Private Sub chkAnimation_Click()
' Displaying and Hiding Animation Frame and Image
' control
If [Link] = 1 Then
[Link] = True
[Link] = True
Else
[Link] = False
[Link] = False
End If
End Sub
LoadPicture([Link] + ".gif")
End Sub
It is an art to choose suitable names to controls. The name of a control should reveal
its purpose and also its type. The name of a control should be chosen, in such a way
that it should give appropriate meaning about the usage of that control and one of
the following abbreviations should be prefixed with its name according to its type.
Common methods
TabIndex Determines the tab order of most objects within their parent
form.
Common Events
If a subroutine is specified for the control’s click event, this subroutine executes each
time the control is clicked. The subroutine that determines how a control reacts to an
event is called an event handler.
Switch to the Code widow, or double click on the control, which requires the
event handler. The top of the Code window contains two drop down lists
(Figure 1.23). The first list contains the names of the all the controls on the
Form.
Select the control, which requires the event handler. The second list contains all
the events the selected control can recognize.
Select the event, which requires the event handler.
Figure 4.4 Drop lists – listing controls and event in the Code Window
The combination of the control’s name and the event’ s name is unique and is the
name of the event handler. For example, the event handler name for the
Command1’s click event will be Command1_Click. Each time an event’s takes place,
Visual Basic looks for the subroutine made up of name of the control and on which
the event took place and the name of the event. If such a handler exists, it’s executed.
If not, the application won’t react to the event.
The following is the list of common events:
DblClick The user double clicks the primary (left) mouse button
on an object.
MouseDown The user presses any mouse button while the mouse
pointer is over an object.
MouseUp The user releases any mouse button while the mouse
pointer is over an object.
A command button control is one of the most common controls found in Windows
applications. Visual Basic is no exception. You can use a command button to elicit
sample response form the user or to invoke special functions on forms. Surely you
have encountered command buttons before. Every time you click the OK button on a
dialog box you are clicking a command button.
Below is the list of the properties of a command button. The most commonly used
properties appear in boldface.
Caption Determines the text that appears on the command button. Placing an
ampersand character (&) in the caption gives a keyboard access key alternative to a
mouse-click. You access these controls by holding the Alt key down while you press
the underlined letter of the control you wish to access. The user could also tab to the
command button and press the spacebar to simulate a mouse-click on the button.
Default (Boolean) Determines whether the command button is the default button or
not. That is, if a command button's Default property setting is True and its parent
Form is active, the user can choose the command button (invoking its Click event) by
pressing ENTER. Any other control with the focus doesn't receive a keyboard event
(KeyDown, KeyPress, or KeyUp) for the ENTER key unless the user has moved the
focus to another command button on the same form. In this case, pressing ENTER
chooses the command button that has the focus instead of the default command
button.
Cancel (Boolean) Determines whether the command button is the cancel button or
not. That is, if a command button's Cancel property setting is True and it parent
Form is active, the user can choose the CommandButton by clicking it, pressing the
ESC key, or pressing ENTER when the button has the focus.
Note:Only one Command Button control on a Form can be the Cancel button.
When the Cancel property is set to True for one Command Button, it's
automatically set to False for all other Command Button controls on the form.
Likewise only one Command button can be the Default button.
Name The Name property is used to give the control its own identity. This name is
used by your code and Visual Basic to distinguish it from the rest of the controls.
Style Indicates the display type of the control. It can have any one of the two values
as in the following table.
Value Description
0-Standard Default. Displays the command button as a standard
button without any associated graphic.
1-Graphical Displays the standard button that can also have an
associated graphic.
BackColor This property’s value of a command button will take effect, only when
the Style property is set to Graphical. More over, the command button can display a
picture by using the Picture property (explained next).
Enable This property can stop the user from accessing a command button. If either
is set to false, the command button will be unusable. Disabling a command button is
a handy technique if you want to force the end user to complete certain actions( such
as filling in text boxes) before clicking the next button in the process.
TabIndex A control with a TabIndex of 0(zero) is the first to receive the focus on a
form, provided it’s not disabled or [Link] you alter the TabIndex of the one
control, the other controls’ orders adjust to accommodate the new order.
TabStop Determines the user to prevent from tabbing to a control, set it to False,
though this does not prevent a mouse-click on the control – to stop that, use the
Enable or Visible properties described previously.
Note: The Picture also available to Form, Check box, Option button, Picture Box
and Image control.
Without a doubt, the most frequently coded event procedure for a command button
corresponds to the Click event; the other events for a command button are listed
here:
In your first programs, the Clickevent is probably the only event in which you’d be
interested. It’s the most commonly used event on a command button. You won’t use
many of the other events until you become more proficient in Visual Basic. You can
also use the MouseUp event in place of the Clickevent. Many Windows applications
use this event so it gives the user a chance to back out without causing a Click event.
Listed below are the methods for the command button. The most commonly used
method is Setfocus.
The Setfocus method is sometimes used to place the focus on a particular button.
This comes in handy if you want the user to return to a default button after editing a
text box on a form. If that were so, the code for the focus button looks like this:
[Link]
and it might be placed in the Change event procedure for a text box.
The Frame Control is not particularly useful. The controls normally placed in a frame
are option buttons and check boxes. This has the effect of grouping them together so
when the frame is moved, the other controls move, too. For this to work you can’t
double-click a control (say, an option button) to add it to the form, and then drag it
into position within the frame. Instead, you must single-click the control in the
Toolbox and drag a location for it inside the frame. Then all the controls move
together.
In addition, the option buttons function as a group-that is, if you select one at run
time, the others become deselected. If you simply scatter option buttons randomly,
on a form, then they all function as one large group. To create separate groupings of
option buttons, you place them in frames. The button items within each frame act as
a self-contained group and have no effect on the option buttons in other frame
groups.
Although a frame is often used as a container for check box groups too, each check
box is completely independent. Thus the setting for one check box has no effect on
the setting for the others in the same group. This is the behavior you would expect of
check boxes. Checkboxes are not mutually exclusive. This contrasts with option
buttons, where the buttons within a single group should be mutually exclusive. The
reason then for placing check boxes in a frame is to enable you to move the group as
a whole, when you reposition the frame at the design time. The frame also serves as a
visual grouping for the check boxes. For example, the check boxes relating to a
particular feature can be in one frame and those pertinent to another feature in
another frame.
A frame is usually given an fra prefix. You place the frame on the form before you
place the controls it’s going to contain.
Frame Properties
After the Name property, perhaps the single most important property is the Caption.
You use this to give a meaningful title to the frame on the form. Then it’s clear to the
end user which feature the option buttons (or Check boxes) in the frame refer to. The
provide a clue as to how each option button affects the feature, you use the Caption
property of the buttons. For example, in order dispatch system you might have a
frame with the caption Delivery. And within that frame you might have two option
buttons, with the captions Normal and Express.
Frame Events
The frame control events are only rarely used. In an application the uses drag-and-
drop, however, the DragDrop event is sometimes used to initiate actions when the
user drops an object into a frame area.
Frame Methods
A frame object supports only a few methods. None are verry helpful and they’re
hardly ever seen in Visual Basic projects:
Option button controls(shown here) are used to allow the user to select one ,and only
one, option from a group of options. Usually option buttons are grouped together
within a frame control , but they can also be grouped on a plain form, if there is to be
only one group of option buttons. Thus,if you had a frame specifying a delivery
method, you might have one button for UPS(United Parcel Service) and another for
Courier delivery. Products can only be shipped by one of these methods (not both-
and not none). In contrast, option buttons representing, say bold and italic settings
for text would not make sense. Text can be both bold and italic,or neither(none).
The option button supports many properties which are shown in the table below:
Once again the Name property is the one to set first; option buttons have an opt
prefix by convention. The Caption property helps the user determine the purpose of
an option button. The other popular property is Value. This is invaluable at both
design time and run time. At run time you test the Value property to see if the user
has turned on (or off) the option button. The property has two settings, True or False.
At design time you can set the Value property to True for one of the buttons if you
wish – the default setting is False. This means that the option button ( and only that
option button in a group) is pre-selected when the form opens. If you try to make
Value for another button in the group True, then the previous one reverts to a False
setting.
The option button control has a few events, but only the click event is really used:
The typical way of dealing with option buttons is to test the Value property at run
time to see if they’re selected. Your code then initiates actions accordingly. It’s
common to test for the Value property in the Click event procedure for a command
button that’s clicked after the user has select the option button of interest. This allows
you to check for a condition before the next procedure is called. You test the Value
property in an If…End If or Select Case…..End Select construct. But there may be
occasions when you want to initiate an action immediately after the user makes a
choice. Then you may want to trap the option button’s Click event.
Example
The methods for the option button are of little use in the Visual Basic environment.
100 Centre for Information Technology and Engineering, Manonmaniam Sundaranar University
Controls
A Check Box control is rather similar to an option button. Both often partake in
groups, and the Value property is tested to see if a check box is on or off. But there
are two fundamental differences between check boxes and option buttons: Check
boxes are valid as single controls – a single option button is probably counter-
intuitive. Check boxes ( even when a group ) are not mutually exclusive. Finally ,
check boxes have three possible settings for the Value property.
Centre for Information Technology and Engineering, Manonmaniam Sundaranar University 101
Advanced Visual Basic
An option button is either on or it’s off. Therefore, Value can be either True or False.
Check boxes can be in one of three states – on, off, or grayed. Grayed(dimmed) does
not mean the same as disabled in this context- a grayed check box is neither on nor
off, though the user can change its setting. If the check box were disabled, the user
wouldn’t be able to turn it on or off. A grayed check box is used to signify that some,
but not all, option on another dialog box are selected. If you look at the dialog box in
Figure 1.26, you will notice two of the check boxes are grayed. The Accessories check
box is gray because it was installed.
The following table lists the properties for the check box control:
Alignment Enabled HelpContextID TabIndex
Appearance Font hWnd TabStop
Backcolor FontBold Index Tag
Caption FontItalic Left ToolTipText
Container FontName MousePointer Top
DisabledPicture FontSize Name UseMaskColor
DownPicture FontStrikethru Parent Value
DragIcon FontUnderline Picture WhatsThisHelp
Dragmode Forecolor Style Width
DataChanged Height
DataField
Value Indicates the state of the control. It can have any one of the values – 0-
Unckecked, 1-Checked, and 2-Grayed.
Style Indicates the appearance of the control, whether standard or graphical. If it has
the value Graphical then the check box will appear as a command button as in Figure
1.27
Figure 4.7 Check boxes whose Style property has the Graphical value.
DisabledPicture Sets the graphic to be displayed when the button is in the disabled,
if the Style is set to Graphical.
DownPicture Sets the graphic to be displayed when the button is in down position, if
the Style is set to Graphical.
102 Centre for Information Technology and Engineering, Manonmaniam Sundaranar University
Controls
Note: The above four properties are same for the Option button also.
The following table shows you that the check box has similar events to the option
button control:
Click DragDrop DragOver GotFocus
KeyDown KeyPress KeyUp LostFocus
MouseDown MouseMove MouseUp
To carry out further processing as soon as the user has clicked the check box, use the
click event. Normally, though, if you do not put code directly within the click event,
you will have another procedure that will ascertain the value of a check box by
retrieving its Value property.
Like option buttons, the methods for the check box control are non-vital to the
operation of the control.
As you might expect, picture boxes often graphics (for example, bitmaps, icons,
JPEGs and GIFs). In this role, picture boxes are similar to image controls. However,
picture boxes and images have slightly different properties and therefore behave
differently. If you just want to show a picture, then a image control is usually a better
choice tan a picture box. Images take up less memory and are a lightweight version
of picture boxes. However, if you wan to move the graphic around the form, a
picture box produces a smoother display. In addition, you can create text and use
graphics methods in a picture box at run time. The graphics methods enable you to
draw lines, circles and rectangles at run time. But most importantly for this
application, picture boxes can act as containers for other controls. Thus you can place
a command button within a picture box. In this respect, picture boxes function as
“forms within forms”
Centre for Information Technology and Engineering, Manonmaniam Sundaranar University 103
Advanced Visual Basic
Picture Sets the graphic to be displayed in the control. At design time a graphic file
name can easily be specified through the Properties Window. But to assign a picture
at run time the LoadPicture statement is used as in the following:
[Link] = LoadPicture(“C:\Windows\[Link]”)
The LoadPicture statement loads the [Link] file from the disk to memory and
assigns it to the picture property of the Picture1 control.
Figure 4.8 Different appearance of a same picture due to different values of the
AutoSize property of the Picture box Control.
In the above Figure1.28 the first Picture box control has the value False in its
AutoSize property. So only portion of a picture that can fit into the current
coordinates of the first Picture box is displayed. The second Picture box has the
value True in its AutoSize property. So, it is automatically resized to accommodate
the entire picture.
The Picture box control supports more methods than its counterpart, the image box.
The most important once are listed in boldface in the following table:
104 Centre for Information Technology and Engineering, Manonmaniam Sundaranar University
Controls
The Circle, Cls, Line, Print and Pset methods are all concerned with drawing
graphics or text in the picture box at run time – Cls(like the old DOS command for
“clear screen”) is actually used to erase entries. The Zorder method is the run-time
equivalent of Format Order Bring to Front or Format Order Send to Back. You
can use ZOrder to determine which controls overlap other controls. However, you
should be aware that there are three layers on a form- ZOrder only works within the
layer that contains the control. All the nongraphical controls except labels(foe
example, command buttons///0 belong to the top layer. Picture boxes and other
graphical controls (labels) belong to the middle layer. The bottom layer contains the
results of the graphics methods- for instance, a circle drawn with the circle method is
on the bottom layer. This contrasts with a circle drawn with the shape control, which
is in the middle layer. What all this means is that you can’t position a picture box
over a command button with ZOrder- the picture box is permanently relegated to the
layer behind. The ZOrder method is for rearranging objects within one layer.
PaintPicture Draws the contents of a Picture box control in the another picture box
control.
Syntax
[Link] picture, x1, y1, width1, height1, x2, y2, width2, height2 Each
argument is described in the following table.
Part Description
Required. The source of the graphic to be drawn onto object.
Picture
Must be the Picture property of a PictureBox.
Required. Single-precision values indicating the destination
X1, y1 coordinates (x-axis and y-axis) on object for picture to be
drawn.
Optional. Single-precision value indicating the destination
Width1
width of picture. If omitted, the source width is used.
Optional. Single-precision value indicating the destination
Height1
height of picture. If omitted, the source height is used.
Optional. Single-precision values indicating the coordinates
x2, y2 (x-axis and y-axis) of a clipping region within picture. If
omitted, 0 is assumed.
Optional. Single-precision value indicating the source
Width2 width of a clipping region within picture. If omitted, the
entire source width is used.
Centre for Information Technology and Engineering, Manonmaniam Sundaranar University 105
Advanced Visual Basic
The following line shows how to copy the contents of the Picture1 control to the
Picture2 control.
[Link] [Link], 0, 0
As optional arguments are omitted, their default values will be [Link] following
line shows how to display mirror images of the Picture1 control in the Picture2
control.
Here, destination X’s origin is not 0, but the picture’s width and the destination with
are the negative of the actual width. So the contents of the Picture1 will be displayed
in the reverse order to produce the mirror image.
The image control(Prefix –img) is a lightweight equivalent of the picture box control.
But unlike the picture control, the image control can’t act as a container for other
objects. In some of its other properties it’s not as versatile, but it’s a good choice if
you simply want to display a picture on a form. Image controls consume far less
memory than picture controls.
The image control that comes with Visual Basic can now display
bitmap(.BMP),icon(.ICO),metafile(.WMF),JPEG(>JPG) and GIF(.GIF) files. This
makes it easier to display graphics from the WorldWideWeb, as well as graphics
from other popular graphics program.
106 Centre for Information Technology and Engineering, Manonmaniam Sundaranar University
Controls
Stretch (Boolean) Indicates whether the picture has to be resized to fit the size of the
control. This property is totally different from the Picture box control’s AutoSize.
When the AutoSize is set to False, only portion of the picture that fits into the current
coordinates of the Picture box is displayed. But when Stretch is set to False the
Image control is resized to the coordinates of the picture. That is, it behaves in the
similar manner of the Picture box control when its AutoSize is set to True. But when
the Stretch is set to True the picture will be enlarged or compressed to the current
coordinates of the Image Control.
Figure 4.8 Different appearance of a same picture due to different values of the
Stretch property of the Image Control.
Note: The Image control will not display border around its contents as like the
Picture box.
In the Figure 1.29 the first image control (left-top) has the value False in its Stretch
property. So this control is resized to accommodate the entire contents of the picture.
But the other two image controls are resized to difference coordinates- One less than
and another greater than the original size of the picture, and their Stretch property is
set to True. So the picture is shrunk and enlarged accordingly.
Note: When the Image control’s Stretch property is set to True, resizing the control
also resizes the picture it contains. But in contrast to this, resizing a Picture
box control will not resize its picture, even though its AutoSize property is set
to True.
Centre for Information Technology and Engineering, Manonmaniam Sundaranar University 107
Advanced Visual Basic
The timer control is one of the few controls always hidden at run time. This means
you don’t have to find room for it on a form-it can go anywhere,even on top of
existing controls. The timer basically dows just one thing: It checks the system clock
and acts accordingly.
Timer Properties
Interval Sets the number of milliseconds between calls to the control's Timer event.
That is, if this property is set to the value 1000, the control’s Timer event will be
executed at every second (1000 milliseconds = 1 Second).
Tag Returns or sets an expression that stores any extra data needed for the
application. Unlike other properties, the value of the Tag property isn't used by
Visual Basic; the application use this property for its own purpose. For example,
when the timer Event finishes execution it may store a value in the Tag property,
which may be used at the next occurrence of the Timer event.
Timer Event
The timer control has only one event called, appropriately, a Timer event. As already
stated, this event takes place every time an interval elapses. The interval is
determined by Interval property. To stop the Timer event from occurring you can set
the timer’s Enabled property to False at run time. Timer occurs when a preset
interval (using Interval property) has elapsed.
Example
The following code shows how to change the shape of a Shape control at the interval
of one second. It is assumed that the Timer1control’s properties are set through
Properties window as in below:
• Interval = 1000
• Tag = 1
108 Centre for Information Technology and Engineering, Manonmaniam Sundaranar University
Controls
[Link] = 0
Else
‘ Increasing the Tag value to display the next shape
‘ at the next display
[Link] = [Link] + 1
End If
End Sub
Timer Methods
A list box is an ideal way of presenting users with al list of data. Users can browse
the data in the list box or select one or more items as the basis for further processing.
The user can’t edit the data in a list box directly- one way around that is to have a
combo box instead; combo boxes are discussed next. When the list of data is too long
for the list box then VB will add a vertical scroll bar.
Many of the list box properties are shared by a combo box control, and some of them
are essential for getting the best from the control:
List Sets the items for the list. To set the items click the down arrow in this
property’s value space in the Properties window. It will bring a drop list as in Figure
1.30. Type the items in it delimiting them by typing Ctrl+Enter.
Centre for Information Technology and Engineering, Manonmaniam Sundaranar University 109
Advanced Visual Basic
This property can also be used to return a particular item. For example, to print the
third item of a list, say List1, the following statement is used.
Print [Link](2)
ListCount Returns the number of items in the list portion of a control. (Not available
at design time).
ListIndex Returns the index of the currently selected item in the control. (Not
available at design time).
MultiSelect Indicates whether a user can make multiple selections. This can have one
of the values given in the following table.
Value Description
0-None (Default) Multiple selection isn't allowed.
1-Simple Simple multiple selection. A mouse click or pressing the
SPACEBAR selects or deselects an item in the list.
2-Extended Extended multiple selection. Pressing SHIFT and clicking
the mouse or pressing SHIFT and one of the arrow keys
110 Centre for Information Technology and Engineering, Manonmaniam Sundaranar University
Controls
SelCount Returns number of selected items in the List Box control. If the MultiSelect
property is set to value 0, this property will return either 0 (no selection) or 1 (only
one item can be selected). If the MultiSelect property is set to value 1 or 2, the user
may select more than one items in the List box control. In this case the SelCount
property will return the value greater than 1.
Selected Returns the selection status of an item in the ListBox control. This property
is an array of Boolean values with the same number of items as the List property.
(Not available at design time). For example to know whether the second item is
selected in a list, say List1, the following statements are used.
If [Link](1) = True then
----------------------
End if
To print the selected items of a List, say List1, loop (explained in detail in the next
Chapter) can be used as in below:
For i = 1 to [Link]
If [Link](i) = True Then
Print [Link](i)
End If
Next
The above loop will execute for the total number of items of the list List1. Each time
the current item is checked whether it is selected by using the Selected property. If
so, it is printed.
Style Determines whether checkboxes are displayed inside the List box control. It
can have the value either 0-Standard (default) or 1-Checkbox. If this property is set
to Checkbox the list will appear as in Figure 1.31
Centre for Information Technology and Engineering, Manonmaniam Sundaranar University 111
Advanced Visual Basic
When an item is selected in this style, the item’s check box will be checked.
Note: The Style property can have the value Checkbox, only when the MultiSelect
property has the value 0-None.
AddItem Adds an item to a ListBox at run time. For example, if the text in a text box
entered by the user is to be added to a list box this method can be used to do the
same.
Syntax
The item argument specifies the text to be added to the List box. The index argument
(optional) specifies the position whether the new item is to be placed. For example, if
the new item is to be inserted at the top of the list the index argument will have the
value 0. If this argument is omitted, the new item will be placed at the bottom of the
list.
Example
The following line is used to add the text, entered in the text box Text1, at the top of
the list box List1.
[Link] [Link], 0
Syntax
[Link] index
The index argument specifies the item to be removed. For example, to remove the
third item from the list box List1 the following line is used:
[Link] 2
112 Centre for Information Technology and Engineering, Manonmaniam Sundaranar University
Controls
Clear Clears the content of the list box. For example, to clear the List1 the following
line is used:
[Link]
Note: The properties List, ListCout, ListIndex, Sorted, and Text, and all the three
methods are also available for the Combo Box control also.
The MonthView control makes it easy for users to view and set date information via
a calendar-like interface. Users can select a single date or a range of dates.
The control can be navigated using either the keyboard or mouse. Buttons at the top
of the control are used to scroll months in and out of view.
MonthView Properties
Property Description
Day, Month, Week, and Year Specifies the current Day, Month, Week and Year
number.
Centre for Information Technology and Engineering, Manonmaniam Sundaranar University 113
Advanced Visual Basic
SelStart and SelEnd Return the start and end dates of a selection when
the MultiSelect property is set to True.
MonthView Methods
The MonthView control has two unique methods that need to be noted,
ComputeControlSize and HitTest.
The Compute ControlSize method enables you determine the height and width of a
MonthView control,given its number of rows and columns. MonthView controls can
get pretty large when displaying multiple months. By using the ComputeControlSize
method before changing the MonthColumns and MonthRows properties,you can
ensure that the control will fit on your form. The syntax of the ComputeControlSize
method is:
ComputeControlSize (rows,columns,width,height )
You specify the rows and columns arguments before calling the method, then
examine the variables passed as the width and height arguments. The rows and
columns arguments are of type Integer, and width and height are of type Single.
ctrlpart = HitTest(x,y,date)
114 Centre for Information Technology and Engineering, Manonmaniam Sundaranar University
Controls
The value returned by the HitTest method(ctrlpart) specifies the part of the control in
which the mouse cursor is positioned. This value corresponds to the
MonthViewHitTestAreas Enum (see the table). The x and y arguments are the mouse
pointer’s coordinates,and the Date variable specified by t0he date argument will
contain the date that is under the mouse pointer,if any.
mvwCalendarBack 0
mvwCalendarDate 1
mvwCalendarDateNext 2
mvwCalendarDatePrev 3
mvwCalendarDay 4
mvwCalendarWeekNum 5
mvwNoWhere 6
mvwTitleBack 7
mvwTitleBtnNext 8
mvwTitleBtnPrev 9
mvwTitleMonth 10
mvwTitleYear 11
mvwTitleTodayLink 12
MonthView Events
Event Description
Possible Uses
Centre for Information Technology and Engineering, Manonmaniam Sundaranar University 115
Advanced Visual Basic
To give users the ability to choose a date with the click of a mouse rather than
typing a date value.
To enable users to view multiple months as part of an advanced booking
system such as those used by hotels and airlines.
The DateTimePicker control displays date and/or time information and acts
as the interface through which users can modify date and time information.
The control's display consists of fields that are defined by the control's format
string. When the DateTimePicker is dropped down, a MonthView calendar is
displayed.
Note : To display the Date time picker control in the Time Format Mode check the
Updown check box in the general tab of its property page.
DTPicker Properties
This control also has the properties Value, Year, Month, Week, Day, DayOfWeek
which are same as in the Monthview control. This control’s other important
properties are given below:
116 Centre for Information Technology and Engineering, Manonmaniam Sundaranar University
Controls
DTPicker Formats
It determines the format type used to display text on the control. It can have one of
the values given in the following table.
If the Format Property is set to dtpCustom the format set in the CustomFormat
property (explained next) is used.
DTPicker CustomFormat
It specifies the format used by the control when displaying date/time information.
The string fragment given in the following table can be used to specify the custom
format.
Centre for Information Technology and Engineering, Manonmaniam Sundaranar University 117
Advanced Visual Basic
Examples
To display the date in the format 12-Nov-1976 the following format string
used.
“dd-MMM-yyyy”
Body text can also be added to the format string. For example, if string has to appear
as "Today is: 05:30:31 Friday Nov 14, 1997", then the required format string is
118 Centre for Information Technology and Engineering, Manonmaniam Sundaranar University
Controls
1. Do all controls receive the focus? If not, specify those controls that don’t and
the reason(s)?
2. Do we Dbclick event for a command button?
3. How can you make difference choices using option buttons? Why?
4. Can we have more than one command button as cancel button on a single
form
5. How do you make a text box control a read – only control?
6. Specify few significant differences between an option button and a check
box?
7. Can the user stretch the image to the size of the picture box?
8. List out the difference between Timer Control and Date Time Picker Control?
9. How can you place a Month View Control on a form?
10. Specify few differences between the picture box and image box?
Centre for Information Technology and Engineering, Manonmaniam Sundaranar University 119
Advanced Visual Basic
1
1. Open a new standard EXE project
2. Design your form as shown below
2
1. Open a new standard EXE project
120 Centre for Information Technology and Engineering, Manonmaniam Sundaranar University
Controls
Centre for Information Technology and Engineering, Manonmaniam Sundaranar University 121
Advanced Visual Basic
Lecture - 5
Control Arrays
Objectives
122 Centre for Information Technology and Engineering, Manonmaniam Sundaranar University
Control Arrays
Lecture unit - 5
Centre for Information Technology and Engineering, Manonmaniam Sundaranar University 123
Advanced Visual Basic
In the previous unit we have seen about the types of statements , controls and how
we can placed it in the form. This unit helps to understand the concept of control
arrays, why we are using Controls arrays and how the control arrays can be created
during at run and design time.
A control array is an array of controls, in the same way that an integer is an array of
integers. A group of controls that share common names, types, and event
procedures. Each control has a unique index. When a control in the array recognizes
an event, it calls the event procedure for the group and passes the index as an
argument, allowing your code to determine which control recognized the event.
When you add a second control of the same type of the form, visual Basic presents
you a message asking ‘Do you want to create a control array’ .Choose Yes to create a
control array.
By grouping similar controls into an array(much like arrays that hold strings or
some other data type), you can down on the amount of code in your program.
Because all of the controls in the array share event handlers ( for example, there is
only one Click event for an array of Command Button controls no matter how many
controls are in the array), you do not have to duplicate event code for each individual
control.
Combining dynamic controls with control arrays offers the best of both worlds.
Dynamic controls enable your program to do a little jig in step with your end user’s
needs: the control array enables you to easily manage the pool of dynamically
created controls.
There are many benefits to using control arrays instead of several individual
controls. First, control arrays use fewer resources than individual controls. Second,
controls arrays share common events. For example, if you have an array of
command buttons, the same Click event procedure is called no matter which button
is pressed.
If you start with a text box named Text1 and elect to create a control array,
Visual Basic assignsText1 an index number of 0 and creates a new member of
the Text1 array, with an index number of 0 and creates a new member of the
Text1 array, with an index number of 1. If you make additional copies of
Text1 or Text2, their index properties are set to 3,4 and so on.
124 Centre for Information Technology and Engineering, Manonmaniam Sundaranar University
Control Arrays
Notice in this code fragment that the Index property of the control array member that
received the event is passed as an argument to the event. However, instead of using
index numbers directly in the Select statement, it is more maintainable to assign
these to constants. That way, if for any reason control indexes change, you only need
to change the constant declaration to fix all the code referencing those indexes.
A control array is a group of controls that share the same name and type. They also
share the same event procedures. A control array has at least one element and can
grow to as many elements as your system resources and memory permit; its size also
depends on how much memory and Windows resources each control requires. The
maximum index you can use in a control array is 32767. Elements of the same control
array have their own property settings. Common uses for control arrays include
menu controls and option button groupings.
Adding controls with control arrays uses fewer resources than simply adding
multiple controls of the same type to a form at design time. Control arrays are also
useful if you want several controls to share code. For example, if three option buttons
are created as a control array, the same code is executed regardless of which button
was clicked.
Centre for Information Technology and Engineering, Manonmaniam Sundaranar University 125
Advanced Visual Basic
If you want to create a new instance of a control at run time, that control must be a
member of a control array. With a control array, each new element inherits the
common event procedures of the array.
Using the control array mechanism, each new control inherits the common event
procedures already written for the array. For example, if your form has several text
boxes that each receive a date value, a control array can be set up so that all of the
text boxes share the same validation code.
Note - You must create menu control arrays in the Menu Editor.
1. Draw the controls you want to be in the control array. (The controls must all
be of the same type.) Decide which control will become the first element in
the array.
2. Select one of the controls and change its Name setting to the Name setting for
the first element in the array.
3. When you type an existing name for a control in the array, Visual Basic
displays a dialog box asking you to confirm that you want to create a control
array. Choose Yes to confirm the action.
For example, if the name of the first element in a control array is cmdCtlArr, you
would choose a command button to add to the array and then set its name to
cmdCtlArr. The message "You already have a control named 'cmdCtlArr.' Do you
want to create a control array?" is displayed. Choose Yes to confirm the operation.
126 Centre for Information Technology and Engineering, Manonmaniam Sundaranar University
Control Arrays
Controls added this way share only their Name property and control type; all other
properties remain the same as when the control was originally drawn.
2. While the control has the focus, choose Copy from the Edit menu.
3. From the Edit menu, choose Paste. Visual Basic displays a dialog box asking you
to confirm that you want to create a control array. Choose Yes to confirm the
action.
This control is assigned an index value of 1. The first control you drew has a value of
0. The index value of each new array element corresponds to the order in which the
element was added to the control array. When controls are added this way, most of
the visual properties, such as height, width, and color, are copied from the first
control in the control array to the new controls.
You can add and remove controls in a control array at run time using the Load and
Unload statements. However, the control to be added must be an element of an
existing control array. You must have created a control at design time with the Index
property set, in most cases, to 0. Then, at run time, use this syntax:
Load object(index%)
Unload object(index%)
When you load a new element of a control array, most of the property settings are
copied from the lowest existing element in the array — in this example, the element
with the 0 index value. The Visible, Index, and TabIndex property settings are not
automatically copied to new elements of a control array, so to make the newly added
control visible, you must set its Visible property to True.
Note Visual Basic generates an error if you attempt to use the Load
statement with an index number already in use in the array.
Centre for Information Technology and Engineering, Manonmaniam Sundaranar University 127
Advanced Visual Basic
You can use the Unload statement to remove any control created with Load.
However, you cannot use Unload to remove controls created at design time,
regardless of whether or not they are part of a control array.
The control array example demonstrates how controls — in this case, option buttons
— are added and deleted at run time. The example allows the user to add option
buttons that change the background color of a picture box.
Start with a form, and then draw a picture box, a label, two option buttons, and three
command buttons, as shown in Figure 5.1
The following table lists the property settings for the objects in the
application.
128 Centre for Information Technology and Engineering, Manonmaniam Sundaranar University
Control Arrays
Next, you need to add the event procedures for the option buttons and command
buttons. Start by adding the form declaration:
New option buttons are added by the Click event procedure for the Add command
button. In this example, the code checks that no more than ten option buttons are
loaded before the Load statement is executed. Once a control is loaded, its Visible
property must be set to True.
Option buttons are removed by the Click event procedure for the Delete command
button:
Centre for Information Technology and Engineering, Manonmaniam Sundaranar University 129
Advanced Visual Basic
End Sub
The Close button Click event ends the application:
Private Sub cmdClose_Click ()
Unload Me
End Sub
) Control arrays is a group of controls that share the same name and type.
) Control arrays can be created during design time by assigning the same name
in the name property for more than one control
) During Design time set the index property to a value is not null
) Control arrays can be create at run time using the statements [Load object
(index % ) and Unload object (index %) ]
5.5 Brain Storm
1. What are the salient features of the control arrays?
2. When a Control array can be used?
3. What is the need of control arrays
4. How a control arrays can be created at run time
2. Design your form as shown below ( 19 Command Button & A Text box) and
perform a Calculator Project , which can able to work as like as Windows
Calculator.
130 Centre for Information Technology and Engineering, Manonmaniam Sundaranar University
Procedures
Lecture - 6
Procedures
Objectives
About Procedures
Centre for Information Technology and Engineering, Manonmaniam Sundaranar University 131
Advanced Visual Basic
Lecture Unit - 6
132 Centre for Information Technology and Engineering, Manonmaniam Sundaranar University
Procedures
When we write a lengthy program some times we may have to write a set of
statements repeatedly. It will be a time consuming one. So, to avoid that we can
write the code and keep in a separate file and when ever we need to execute the
statements we can call it. The advantages of using procedures in programming are
(a) It is easier to debug a program with a procedures, which breaks a program into
discrete logical limits. (b) Procedures used in one program can act as building
blocks for other programs with slight modifications.
A general procedure tells the application how to perform a specific task. Once a
general procedure is defined, it must be specifically invoked by the application. By
contrast, an event procedure remains idle until called upon to respond to events
caused by the user or triggered by the system.
Why create general procedures? One reason is that several different event
procedures might need the same actions performed. A good programming strategy
is to put common statements in a separate procedure (a general procedure) and have
your event procedures call it. This eliminates the need to duplicate code and also
makes the application easier to maintain. For example, the VCR sample application
uses a general procedure called by the click events for several different scroll buttons.
Figure 2.3 illustrates the use of a general procedure. Code in the Click events calls the
ButtonManager Sub procedure, which runs its own code, and then returns control to
the Click event procedure.
Centre for Information Technology and Engineering, Manonmaniam Sundaranar University 133
Advanced Visual Basic
• An event procedure for a control combines the control's actual name (specified in
the Name property), an underscore (_), and the event name. For instance, if you
want a command button named cmdPlay to invoke an event procedure when it is
clicked, use the procedure cmdPlay_Click.
• An event procedure for a form combines the word "Form," an underscore, and
the event name. If you want a form to invoke an event procedure when it is
clicked, use the procedure Form_Click. (Like controls, forms do have unique
names, but they are not used in the names of event procedures.) If you are using
the MDI form, the event procedure combines the word "MDIForm," an
underscore, and the event name, as in MDIForm_Load.
Although you can write event procedures from scratch, it's easier to use the code
procedures provided by Visual Basic, which automatically include the correct
procedure names. You can select a template in the Code Editor window by selecting
an object from the Object box and then selecting a procedure from the Procedure box.
It's also a good idea to set the Name property of your controls before you start
writing event procedures for them. If you change the name of a control after
attaching a procedure to it, you must also change the name of the procedure to match
the new name of the control. Otherwise, Visual Basic won't be able to match the
control to the procedure. When a procedure name does not match a control name, it
becomes a general procedure.
134 Centre for Information Technology and Engineering, Manonmaniam Sundaranar University
Procedures
You’ve now met two types of Sub procedures. The first type (Private by
default) is the event Sub procedure behind forms and controls. These event
procedures are already defined for you. The second type the ones you add
yourself are called general Sub procedures. There are also Function
procedures. These you must create yourself, and they can be Private or
Public. Function procedures return a value to the procedures that call them.
The best way to understand Function procedures is to try one out. Here’s one
that calculates the cube root of a number:
The math involved here isn’t important. But a few other things are:
• The Function ends with an End Function rather than an End Sub
• You can jump out of a Function with Exit Function.
• The Function must return a value- the line Cube Root = 0 is one of the three
possible lines that do that.
• You can specify the type of value returned- here it’s a Double ( a numeric
variable that can handle very large and small values as well as decimals) by
adding the statements As followed by the date type of the returned value.
Centre for Information Technology and Engineering, Manonmaniam Sundaranar University 135
Advanced Visual Basic
4. To call this function, you must assign its return value to another variable.
Try the following code in a click event for a form
Dim Y As Double
Y= CubeRoot(27)
Print Y
This code prints the return value straight onto the form
Normally, you may want to assign the return value to a control on the form, such
as a text box control
[Link] = Y
The result is
[Link] = CubeRoot(27)
Note: When you all a Function procedure, you must enclose the
parameter(s) in parentheses. This contrast with calling a Sub
procedure.
Usually the code in a procedure needs some information about the state of the
program to do its job. This information consists of variables passed to the procedure
when it is called. When a variable is passed to a procedure, it is called an argument.
The arguments for procedures you write have the Variant data type by default.
However, you can declare other data types for arguments. For example, the
following function accepts a string and an integer:
136 Centre for Information Technology and Engineering, Manonmaniam Sundaranar University
Procedures
For example:
Passing arguments by reference gives the procedure access to the actual variable
contents in its memory address location. As a result, the variable's value can be
permanently changed by the procedure to which it is passed. Passing by reference is
the default in Visual Basic.
If you specify a data type for an argument passed by reference, you must pass a
value of that type for the argument. You can work around this by passing an
expression, rather than a data type, for an argument. Visual Basic evaluates an
expression and passes it as the required type if it can.
Sub CallingProcedure()
Dim intX As Integer
intX = 12 * 3
Centre for Information Technology and Engineering, Manonmaniam Sundaranar University 137
Advanced Visual Basic
Foo(intX)
End Sub
138 Centre for Information Technology and Engineering, Manonmaniam Sundaranar University
Procedures
End Sub
In the case where an optional argument is not provided, the argument is actually
assigned as a variant with the value of Empty. The example above shows how to test
for missing optional arguments using the IsMissing function.
It's also possible to specify a default value for an optional argument. The following
example returns a default value if the optional argument isn't passed to the function
procedure:
Generally, the number of arguments in the procedure call must be the same as in the
procedure specification. Using the ParamArray keyword allows you to specify that a
procedure will accept an arbitrary number of arguments. This allows you to write
functions like Sum:
Dim x As Integer
Dim y As Integer
Dim intSum As Integer
Centre for Information Technology and Engineering, Manonmaniam Sundaranar University 139
Advanced Visual Basic
The arguments for procedures you write have the Variant data type by default.
However, you can declare other data types for arguments. For example, the
following function accepts a string and an integer:
1. What is a Procedure?
2. What are the difference between General procedure and Event procedures.
3. What is a Function?
4. What are the difference between Functions and Procedures?
140 Centre for Information Technology and Engineering, Manonmaniam Sundaranar University
Procedures
Centre for Information Technology and Engineering, Manonmaniam Sundaranar University 141
Advanced Visual Basic
Lecture - 7
Debugging
Objectives
About Debugging
Handling Windows
142 Centre for Information Technology and Engineering, Manonmaniam Sundaranar University
Debugging
Lecture unit 7
7.5 Modules
Centre for Information Technology and Engineering, Manonmaniam Sundaranar University 143
Advanced Visual Basic
When errors occur in the application code, it is referred as bugs. Minor bugs — for
example, execution of some statements may never occur due the fault in the
conditional statements — can be frustrating or inconvenient. More severe bugs can
cause an application to stop responding to commands, possibly requiring the user to
restart the application, and losing whatever work hasn't been saved.
The process of locating and fixing bugs in the application is known as debugging.
Visual Basic provides several tools to help to analyze the operation of the
application. These debugging tools are particularly useful in locating the source of
the bugs.
The following sections show how to use the debugging tools included in Visual Basic
and explains how to handle run-time errors.
Understanding the three modes of operations of the Visual Basic will ease the
debugging process. Applications are built in Design-time mode and run in run-time
mode. This chapter introduces break mode, which suspends the execution of the
program so that data can be examined and altered.
The Visual Basic title bar always shows the current mode. The following Figures 7.1
show the title bar for design time, run time, and break mode.
144 Centre for Information Technology and Engineering, Manonmaniam Sundaranar University
Debugging
In the suspend mode, it is possible to view and edit code (choosing Code from the
View menu, or pressing F7), examine or modify data, restart the application, end
execution, or continue execution from the same point.
The toolbar provides three buttons that lets to change quickly from one mode to
another. These buttons appear as in Figure 7.2.
Whether any of these buttons is available depends on whether Visual Basic is in run-
time mode, design-time mode, or break mode. The following table lists the buttons
available for different modes.
As said earlier, the Break mode enables to modify the code and to continue
the execution of an application. For example, if a run time error occurs, while
an application is running, the Visual Basic displays a dialog box with error
message. Clicking the Debug button of that dialog box will cause the
Centre for Information Technology and Engineering, Manonmaniam Sundaranar University 145
Advanced Visual Basic
application to switch to the break mode. Here, the cursor will wait with
highlighted background at the statement that caused the error (Figure 7.3).
Now that statement can be corrected and the execution can be continued.
The Frequent run time errors include misspelled names and mismatched
properties or methods with objects — for example, trying to use the Clear
method on a text box, or assigning a Text to an integer variable. The
following example shows a typical situation.
Figure 7.3 Cursor with highlighted background at the statement that caused the error.
In this example the value of the txtRestRate text box, which is a string, is attempted
for the assignment to the integer variable intRestRate. So Visual Basic displays the
Error Dialog box, with the message Runtime error 13 – Type mismatch. When the
mode is switched to the break mode, by clicking the Debug button, the current line
that caused the error, can be corrected as
146 Centre for Information Technology and Engineering, Manonmaniam Sundaranar University
Debugging
Note: Though changes can be made in the Break Mode, some changes (most
commonly, changing variable declarations or adding new variables or
procedures) require to restart the application.
Among its many debugging tools, Visual Basic provides several buttons on the optional Debug
toolbar that are very helpful. Figure 7.4 shows these tools. Right clicking on the Visual Basic
toolbar and selecting the Debug option will display the Debug toolbar.
This section discusses the components in the second block of the Debug tool
bar such as Toggle break point, Step into etc. Third block components are
discussed in the next section.
The Toggle Breakpoint option simply toggles a break point on and off at the
current line. If a break point is set for a line, then that line will appear with
red background and a red circle in the code window’s left margin as in Figure
7.5
Centre for Information Technology and Engineering, Manonmaniam Sundaranar University 147
Advanced Visual Basic
If a breakpoint is set for a line, then the application will switch automatically to break
mode, when the execution reaches that line. This enables to trace the execution of the
code.
Place the cursor in the line where the break point is to be set.
Choose Break point option from Debug menu or Press F9
--- Or ---
Step Into executes the current line of code. However, If the statement is a call to a
procedure, the next statement displayed is the first statement in the procedure.
Step Over executes each line of code in the current procedure, but steps over any
subsequent procedure that is called. Even though the cursor does not stop anywhere
within subsequent procedures, they are actually executed.
StepOut executes all lines remaining in the current procedure and stops executing on
the line after the line that called the current procedure.
148 Centre for Information Technology and Engineering, Manonmaniam Sundaranar University
Debugging
Analyzing the values of variables and properties, while the application is running
will be useful for debugging. Because some times the problem may be due to the
assignment of incorrect values to the variables and properties. Monitoring the data
will enable to detect, why those incorrect values are assigned to the variables or
properties.
The debugging windows help to monitor the values of variables, properties and
expressions while the application is running. The debugging windows are the
Immediate window, the Watch window, the Locals window, the quick watch
window and the Call stack window. They can be activated either by choosing their
respective menu option from the view menu or icons from the debug toolbar.
Immediate Window
The print method with Debug object prefix sends output to the Immediate
window.
[Link] [items][;]
For example, the following statement prints the value of Salary to the Immediate
window every time it is executed:
Centre for Information Technology and Engineering, Manonmaniam Sundaranar University 149
Advanced Visual Basic
This technique works best when there is a particular place in the application code at
which the variable (in this case, Salary) is known to change. For example, the
previous statement might be put in a loop that repeatedly alters Salary.
Note: When the application is compiled into an .exe file, [Link] statements are
not included in the .exe file.
In the break mode the print statements can directly be used in the Immediate
window to examine the data.
Type a print statement into the Immediate window, and then press ENTER.
The Immediate window responds by carrying out the statement, as shown as in the
Figure 7.7
Figure 7.7 Using the Print method to print to the Immediate window.
150 Centre for Information Technology and Engineering, Manonmaniam Sundaranar University
Debugging
A question mark (?) is useful shorthand for the Print method. The question
mark means the same as Print, and can be used in any context where Print is
used. For example, the statements in Figure 7.8 could be entered as shown in
the following figure.
Print 5*10/2
? [Link]
Testing the application with different data will be much useful to find out the
behavior of the application in all possible cases. The immediate window allows to
assign new values to the variables and properties of objects in the break mode.
The values of variables and properties can be set with statements like these in the
Immediate window:
BackColor = 255
[Link] = 100
MaxRows = 50
The first statement alters a property of the currently active form, the second alters a
property of VScroll1, and the third assigns a value to a variable.
Centre for Information Technology and Engineering, Manonmaniam Sundaranar University 151
Advanced Visual Basic
After values are set to one or more variables and properties the execution can be
continued to test the its behavior with the new values.
The Immediate window can be used to display the error message associated with a
specific error number. For example to know about the error no 58, the following
statement can be used in the Immediate window.
error 58
This statement will cause the appearance of the appropriate error message,
corresponding to the mentioned number as in the Figure 7.9
The watch window also helps to monitor the data (in the break mode), in more
detailed fashion than the immediate window.
Expressions
Lists the watch expression with the Watch icon, on the left.
152 Centre for Information Technology and Engineering, Manonmaniam Sundaranar University
Debugging
Value
List the value of the expression at the break mode. The value can be edited and then
pressing Enter key, the UP ARROW key, the DOWN ARROW key, TAB will cause
the validation of the change. If the value is illegal, the Edit field remains active and
the value is highlighted. A message box describing the error will also appear. The
change can be cancelled by pressing the ESC key.
Context -Lists the context of the watch expression. If the context of the expression
isn't in the current scope the current value isn't displayed.
For example in an application there are two procedures namely Proce1 and Proce2.
A variable Proce1Var of integer type is declared in Proce1. And Proce2Var of type
variant is declared in Proce2. Assuming the application enters into the Break mode
when Proce2 is executing, then the watch window will appear as Figure 7.11,
provided Proce1Var and Proce2Var should be added to the Watch Window(Adding
watches are explained in the next section):
Centre for Information Technology and Engineering, Manonmaniam Sundaranar University 153
Advanced Visual Basic
The following table describes the components of the Add Watch dialog box.
Component Description
Accepts expression which to be evaluated by the watch
Expression box expression. The expression is a variable, a property, a
function call, or any other valid expression.
Sets the scope of variables watched in the expression. It is
Context option
used if the application has variables of the same name with
group
different scope.
Sets how Visual Basic responds to the watch expression.
Visual Basic can watch the expression and display its value
in the Watch window when the application enters break
Watch Type option
mode. Or the application can be made to enter into break
group
mode automatically when the expression evaluates to a true
(nonzero) statement or each time the value of the expression
changes.
The current expression (if any) in the Code Editor will appear in the
Expression box on the Add Watch dialog box. If this isn't the expression to
watch, enter the expression to evaluate in the Expression box.
Choose OK.
Note:An expression can be added by dragging it from the Code Editor and
dropping at the Watch window.
154 Centre for Information Technology and Engineering, Manonmaniam Sundaranar University
Debugging
In the Watch window, double click the watch expression, which is to be edited.
--or--
Select the watch expression which is to be edited and choose Edit Watch from the
Debug menu.
The Edit Watch dialog box is displayed and is identical to the Add Watch dialog
box except for the title bar and the addition of a Delete button.
Make any changes to the expression, the scope for evaluating variables, or the
watch type.
Choose OK.
At the left edge of each watch expression in the Watch window is an icon identifying
the watch type of that expression. Figure 7.14 defines the icon for each of the three
watch types.
Centre for Information Technology and Engineering, Manonmaniam Sundaranar University 155
Advanced Visual Basic
This window helps to check the value of a property, variable, or expression for which
the watch expression is not defined. The following figure 7.15 shows a typical quick
watch window.
The Quick Watch window shows the value of the expression that is selected from the
Code window. The displayed expression can be added to the watch window by
simply clicking the Add button. If the current expression is invalid, then the Visual
Basic will flash the error message “Invalid Expression”.
This window shows the value of any variables within the scope of the current
procedure. As the execution switches from procedure to procedure, the contents of
the Locals window change to reflect only the variables applicable to the current
procedure. Figure 7.16 shows the Locals window.
156 Centre for Information Technology and Engineering, Manonmaniam Sundaranar University
Debugging
The Call Stack window shows a list of all active procedure calls. Active procedure calls
are the procedures in the application that were started but not completed.
The Call Stack dialog box helps to trace the operation of an application as it executes
a series of nested procedures. For example, an event procedure can call a second
procedure, which can call a third procedure and so on — all before the event
procedure that started this chain is completed. Such nested procedure calls can be
difficult to follow and can complicate the debugging process. Figure 7.17 shows the
Call Stack dialog box.
Centre for Information Technology and Engineering, Manonmaniam Sundaranar University 157
Advanced Visual Basic
-or-
Press CTRL+L.
-or-
Click the button next to the Procedure box in the Locals
window.
The Call Stack window lists all the active procedure calls in a series of nested calls. It
places the earliest active procedure call at the bottom of the list and adds subsequent
procedure calls to the top of the list. The information given for each procedure begins
with the project name, followed by module or form name, followed by the name of
the called procedure.
This window can be used to display the statement in a procedure that passes control
of the application to the next procedure in the list.
To display the statement that calls another procedure in the Calls Stack dialog
box
In the Call Stack dialog box, select the procedure call that is to be display.
Choose the Show button.
The dialog box is closed and the procedure appears in the Code window. The cursor
location in the Code window indicates the statement that calls the next procedure in
the Call Stack window. For example if the ProcedureB is chosen and the Show button
is clicked in the Call stack Window (Figure 7.17 ) code window will appear
indication the line that that calls the next procedure as in Figure 7.18
Figure 7.18 Statement indicator in a procedure that calls the next procedure.
158 Centre for Information Technology and Engineering, Manonmaniam Sundaranar University
Debugging
Note:If the current procedure (top most procedure) in the Call stack window is
chosen, the cursor will appear at the current statement.
7.5 Modules
Code in Visual Basic is stored in modules. There are three kinds of modules: form,
standard, and class.
Simple applications can consist of just a single form, and all of the code in the
application resides in that form module. As your applications get larger and more
sophisticated, you add additional forms. Eventually you might find that there is
common code you want to execute in several forms. You don't want to duplicate the
code in both forms, so you create a separate module containing a procedure that
implements the common code. This separate module should be a standard module.
Over time, you can build up a library of modules containing shared procedures.
• Declarations. You can place constant, type, variable, and dynamic-link library
(DLL) procedure declarations at the module level of form, class or standard
modules.
Form Modules
Form modules (.FRM file name extension) are the foundation of most Visual Basic
applications. They can contain procedures that handle events, general procedures,
and form-level declarations of variables, constants, types, and external procedures. If
you were to look at a form module in a text editor, you would also see descriptions
of the form and its controls, including their property settings. The code that you
write in a form module is specific to the particular application to which the form
belongs; it might also reference other forms or objects within that application.
Standard Modules
Standard modules (.BAS file name extension) are containers for procedures and
declarations commonly accessed by other modules within the application. They can
contain global (available to the whole application) or module-level declarations of
variables, constants, types, external procedures, and global procedures. The code that
you write in a standard module isn't necessarily tied to a particular application; if
Centre for Information Technology and Engineering, Manonmaniam Sundaranar University 159
Advanced Visual Basic
you're careful not to reference forms or controls by name, a standard module can be
reused in many different applications.
Class Modules
Class modules (.CLS file name extension) are the foundation of object-oriented
programming in Visual Basic. You can write code in class modules to create new
objects. These new objects can include your own customized properties and
methods. Actually, forms are just class modules that can have controls placed on
them and can display form windows.
Enumeration provide a convenient way to work with sets of related constants and to
associate constant values with names. For example, you can declare an enumeration
for a set of integer constants associated with the days of the week, then use the
names of the days in code rather than their integer values.
160 Centre for Information Technology and Engineering, Manonmaniam Sundaranar University
Debugging
End Enum
In the following enumeration, the constant Invalid is explicitly assigned the value –1,
and the constant Sunday is assigned the value 0. Because it is the first constant in the
enumeration, Saturday is also initialized to the value 0. Monday's value is 1 (one
more than the value of Sunday), Tuesday's value is 2, and so on.
By organizing sets of related constants in enumerations, you can use the same
constant names in different contexts. For example, you can use the same names for
the weekday constants in the Days and WorkDays enumerations.
To avoid ambiguous references when you refer to an individual constant, qualify the
constant name with its enumeration. The following code refers to the Saturday
constants in the Days and WorkDays enumerations, displaying their different values
in the Immediate window.
[Link] "[Link] = " & [Link]
[Link] "[Link] = " & [Link]
You can also use the value of a constant in one enumeration when you assign the
value of a constant in a second enumeration. For example, the following declaration
for the WorkDays enumeration is equivalent to the previous declaration.
Centre for Information Technology and Engineering, Manonmaniam Sundaranar University 161
Advanced Visual Basic
Wednesday
Thursday
Friday
Saturday = [Link] - 6
Invalid = -1
End Enum
After you declare an enumeration type, you can declare a variable of that type, then
use the variable to store the values of enumeration's constants. The following code
uses a variable of the WorkDays type to store integer values associated with the
constants in the WorkDays enumeration.
) Debugging is process by which errors are identified and resolved in the code.
Typically, debugging occurs at serveral levels.
162 Centre for Information Technology and Engineering, Manonmaniam Sundaranar University
Debugging
) In visual Basic errors could occur anywhere during the entire development
cycle such as Design time, Compile Time, Run time.
) Errors that occur in the IDE and before the program is compiled are called
design-time bugs.
) Compile time bugs are those that occur when we attempt to create the
program executable file (EXE) or run the project.
) The Debug Window has two parts – the Watch Window and Immediate
Window
) Visual Basic treats constant values in an enumeration as long integers. If you
assign a floating-point value to a constant in an enumeration, Visual Basic
rounds the value to the nearest long integer.
) Visual Basic provides a built-in enumeration, vbDayOfWeek, containing
constants for the days of the week. To view the enumeration's predefined
constants, type vbDayOfWeek in the code window, followed by a period.
Visual Basic automatically displays a list of the enumeration's constants
) When you type the second line of code in the example in the code window,
Visual Basic automatically displays the WorkDays enumeration's constants in
the Auto List Members list.
) Although you normally assign only enumeration constant values to a variable
declared as an enumeration type, you can assign any long integer value to the
variable. Visual Basic will not generate an error if you assign a value to the
variable that isn't associated with one of the enumeration's
Centre for Information Technology and Engineering, Manonmaniam Sundaranar University 163
Advanced Visual Basic
Lecture - 8
Error Handling
Objectives
164 Centre for Information Technology and Engineering, Manonmaniam Sundaranar University
Error Handling
Lecture unit - 8
Centre for Information Technology and Engineering, Manonmaniam Sundaranar University 165
Advanced Visual Basic
The On Error statement enables the trap and directs the application to the label,
marking the beginning of the error-handling routine.
Example
On Error Goto ErrHandler
Example
Some statements
Branching if error
occurs
ErrHandler: occurs
3. Exit the error-handling routine. When the error handling routine corrects the
encountered error it must exit itself to resume the execution of the temporarily
halted application. The exit from the error-handler is done using one of the
Resume statements (Explained shortly).
166 Centre for Information Technology and Engineering, Manonmaniam Sundaranar University
Error Handling
4. Example
Branching to
Statement that causes error ErrHandler
ErrHandler:
Resuming the
disturbed Statements to correct the errors
work Resume
All the above steps are explained in detail in the following sections.
An error trap is enabled when Visual Basic executes the On Error statement, which
specifies an error handler. The error trap remains enabled while the procedure
containing it, is active — that is, until an Exit Sub, Exit Function, End Sub, or End
Function statement is executed for that procedure.
The On Error GoTo line statement sets an error trap that jump to an error-handling
routine. The line in that statement indicates the label identifying the error-handling
code. In a procedure only one error trap can be enabled at a time. But the procedure can
have more than one-error traps and different ones can be enabled at different times.
Example
Sub ProcedureA()
If Some-condition then
On Error Goto ErrHandler_One
Else
On Error Goto ErrHandler_Two
End if
-----------------------------------
-----------------------------------
ErrorHandler_One:
-----------------------
-----------------------
ErrorHandler_Two:
-----------------------
-----------------------
Centre for Information Technology and Engineering, Manonmaniam Sundaranar University 167
Advanced Visual Basic
The first step in writing an error-handling routine is adding a line label to mark the
beginning of the error handling routine. The line label should have a descriptive
name and must be followed by a colon. A common convention is to place the error-
handling code at the end of the procedure with an Exit Sub, or Exit Function
statement immediately before the line label. This allows the procedure to avoid
executing the error-handling code if no error occurs.
Example
Sub SomeProcedure( )
ErrHandler:
The body of the error handling routine contains the code that actually handles the
error, usually in the form of a Case or If…Then…Else statement. These statements
determines which error has occurred and provide course action for each error, for
example, prompting the user to insert a disk in the case of a "Disk not ready" error.
An option should always be provided to handle any unanticipated errors by using
the Else or Case Else clause. For example a typical error handler may be as follow:
Err_Hanlder:
168 Centre for Information Technology and Engineering, Manonmaniam Sundaranar University
Error Handling
There are three kinds of Resume statements and one of them can be used to exit from
an Error –Handling routine, based on the circumstances. They are explained in the
following table 2.1.
Statement Description
Program execution resumes with the statement that
Resume caused the error. It is used, to repeat an operation after
correcting the condition that caused the error.
Resumes program execution at the statement
immediately following the one that caused the error. It
Resume Next
is used when the error handler is not able to correct the
error.
Resumes program execution at the label specified by line,
Resume line where line is a label that must be in the same procedure
as the error handler.
Centre for Information Technology and Engineering, Manonmaniam Sundaranar University 169
Advanced Visual Basic
The Figure 2.1 shows the execution flow when the Resume or Resume Next
statement is used.
Figure 8.1 The program flow with Resume and Resume Next statements.
Sub SomeProcedure( )
-----------------------------
‘ If denominator is equals to 0 -- branching to
‘ ErrHandler
‘ After error-correction execution resumes here
divide = number / denominator
-----------------------------
Exit Sub
ErrHandler:
If [Link] = 11 then ‘ Division by zero
‘ Changing the denominator to its default value,
‘ say 10
denominator = 10
Resume
Else
‘ Some unknown error
[Link] “Unknown error – Exiting”
Exit Sub
170 Centre for Information Technology and Engineering, Manonmaniam Sundaranar University
Error Handling
End if
End Sub
Sub SomeProcedure( )
-----------------------------
‘ If inVar gets value greater than its max
‘ range(32767) – error occurs – branching to ErrHandler
intVar = some expression
Some times, after correcting the error, it may be desirable to resume the execution at
some specific point. The Resume line statement is handy for it. The line specifies a
label name, which should be written in the same procedure as the error handler.
Here is an example for Resume line statement.
Sub SomeProcedure( )
Centre for Information Technology and Engineering, Manonmaniam Sundaranar University 171
Advanced Visual Basic
-----------------------------
‘ assuming error occurs here and resumption of
‘ execution is desirable at the place marked with
‘ label ResumeHere.
-----------------------------
Exit Sub
ErrHandler:
End Sub
To see the error handling routines work well, the expected errors can be generated in
the code. The Raise method of Err object is used to generated errors.
Syntax
[Link] errnumber
The Err object is Visual Basic's globally defined error object. Programmers need not
to declare them. The errnumber specifies the error that is to be simulated. For
example the number 71 is associated with the error “Disk Not Ready”. To simulate
this error the following statement is used.
[Link] 71
When this statement is executed, Visual Basic will generate the error 71 and the error
handler (if provided) will catch the error and will handle it. After it is assured that
error handler, handles the error well, the statements that raises errors must be
removed, before the application is compiled.
172 Centre for Information Technology and Engineering, Manonmaniam Sundaranar University
Error Handling
Error Object
As soon as an error occurs in Visual Basic code, the special built-in Err Object
becomes active.
The Err Object includes properties that report the number of error,the error’s
description , as well as other useful information.
The [Link] property return the default description of the error that has
occurred.
The most important property of the Err object is the number associated with the error
that occurred.
) The Err object contains information about run – time errors. Its number
property returns a numeric value specifying the occurred error
) On Error statement included in you error – handling code does not take effect
until the end of the error – handling code
Centre for Information Technology and Engineering, Manonmaniam Sundaranar University 173
Advanced Visual Basic
1. Place an On Error GoTo procedure statement as the first line of your program
and write an error procedure
2. Have the error handling code in each procedure call a function that identifies the
error and indicates the appropriate action
3. Create a project using On Error Resume Next Statement , get a number and
divide that number by zero so that an error message should be displayed
(Division by zero).
174 Centre for Information Technology and Engineering, Manonmaniam Sundaranar University
Handling Database
Lecture - 9
Objectives
Centre for Information Technology and Engineering, Manonmaniam Sundaranar University 175
Advanced Visual Basic
Lecture Unit - 9
176 Centre for Information Technology and Engineering, Manonmaniam Sundaranar University
Handling Database
Computers are mainly used for keep track of information. In this unit the will
go on creating files by using Visual Data Manager and adding, deleting the
records and so on…
VisData is an application that was created using Visual Basic itself. A built
version of VisData is used as an add-in, accessible from the Add-Ins menu in
the Visual Basic Figure 2.4.
Figure 9.1 Visual Data Manager option in Visual Basic Add-Ins menu, which is used
to activate the Visual Data Manager.
It is used to create databases, tables, queries, and indexes and to modify them.
When an existing database is opened the Visual Data manager displays the
contents and properties of that database in “Database Window”. The
following figure 2.5 shows the visual data manager window with the BIBLIO
database open in design mode.
Centre for Information Technology and Engineering, Manonmaniam Sundaranar University 177
Advanced Visual Basic
To create a new database, choose File | New | Microsoft Access | Version 7.0
MDB. A dialog box will appear asking path and filename to store the database
being created. Give a filename and choose desired location to save the
database.
There is one more option in the Microsoft Access submenu, Version 2.0 MDB,
which is used to create databases in version 2.0 format. Still many concerns
use applications, which are built using earlier versions of Visual Basic. They
may require databases in older format. In this case alone, the required
database can be created using Version 2.0 MDB option. Otherwise databases
can be created in latest version format (why to look back the Stone Age
world).
Note: To open an already existing access database choose File | Open Database |
Microsoft Access. And select the database name in the Open Microsoft
Access database dialog box.
This section shows how to create a simple database Students with a table
StudentsDtl (Students’ Details), which contains fields StudentId,
StudentName and TotalMarks. It will be useful for rest of this chapter.
178 Centre for Information Technology and Engineering, Manonmaniam Sundaranar University
Handling Database
Click OK to add the field Name. The Field Dialog box will still remain to
accept another field. Proceed for the field StudentName with the values
given below:
Name StydentName
Type Text
Size 30
Validation Text Student Name is not specified.
Validation Rule <> “”
Now click OK and proceed for the field TotalMarks with the values given in
the following:
Name TotalMarks
Type Integer
Validation Text TotalMarks is not specified or negative.
Validation Rule >= 0
Click OK and the Close to close the Add Field Dialog box.
Click Build Table button in the Table Structure dialog box to complete the creation of
table Students.
Creating a Table
Choosing the above option will bring a dialog box called Table Structure
dialog box. Enter the name of the table being created in the table name text
box. And to add fields to the table follow the steps given in the next section.
Centre for Information Technology and Engineering, Manonmaniam Sundaranar University 179
Advanced Visual Basic
Adding Fields
In the table structure dialog box click the Add Field button to display the Add
Field dialog box. It appears as in Figure 9.4
The options of the Add Field dialog box are given below.
Name
Allows to type the name of the field being added.
Ordinalposition
Allows to determine the relative position of the field.
Type
Lets to determine the operational or data type of the field such integer, text
etc.
Validationtext
Lets to add a text of the message that the application displays if a user tries to
enter an invalid value for a field.
Size
Lets to determine the maximum size, in bytes, of the field.
180 Centre for Information Technology and Engineering, Manonmaniam Sundaranar University
Handling Database
Default value
Autoincrfield
Automatically gets value that is incremented by one from the last record
when a new record is added.
Allowzerolength
Required
Indicates if the field requires a non-NULL value.
Ok
Appends the current Field definition to the current table.
Close
Closes the form when you are finished adding fields.
Centre for Information Technology and Engineering, Manonmaniam Sundaranar University 181
Advanced Visual Basic
This will open the table in a separate form (can be termed as table form) as
shown in the following figure 9.5.
In this form records can be added, deleted and updated. The following steps
show how to add, delete and Edit the records to the StudentDtls table.
Double click on the table name StudentDtls in the database window to open it.
As no record is added to the table, the StudentDtl table form will appear in ready
state to accept values for new record as given below Figure 9.6.
182 Centre for Information Technology and Engineering, Manonmaniam Sundaranar University
Handling Database
From now onwards to add records, Add button is to be clicked first, values to be
entered next and finally Update button is to be clicked. By following these steps
enter the data given below to add five more records.
Note: While entering records instead of clicking update button, cancel button can be
clicked to cancel the record addition process.
To edit a record, use data control to move to the required record, modify the record
and either click Update or any one of navigation button. VisData will ask whether
to commit changes as shown below Figure 9.11
Centre for Information Technology and Engineering, Manonmaniam Sundaranar University 183
Advanced Visual Basic
Many modern applications are concerned with the storage, organization and
retrieval of data. To address the needs of the software developers creating
these products, Visual Basic provides a rich set of data access [Link]
provides many standard controls, such as text boxes and labels, that can be
bound to the Data control, in addition to the DBCombo, DBGrid and
[Link] controls are provided specifically for binding to a data control.
The following figure 9.12 shows the data control and DAO with bound
controls.
The intrinsic Data control on the Visual Basic Toolbox, implements data
access by using the Microsoft Jet Database engine –the same database engine
that powers Microsoft Access. This technology gives seamless access to many
standard database formats and allows to create data-aware applications
without writing any code. The intrinsic Data control is best suited to smaller
(desktop) databases, such as Access and ISAM databases.
184 Centre for Information Technology and Engineering, Manonmaniam Sundaranar University
Handling Database
The intrinsic Data control can be used to create applications that display, edit,
and update information from many types of existing databases, including
Microsoft Access, Btrieve, dBase, Microsoft FoxPro, and Paradox.
Centre for Information Technology and Engineering, Manonmaniam Sundaranar University 185
Advanced Visual Basic
The Data form Wizard is designed to automatically generate that contain individual
bound controls and procedures used to mange the data obtained from the database.
You can use the Data form Wizard to create single-query forms to access data from a
single table or query, master/detail-type forms to manage more complex one –to-
many data relationships, or grid forms to manage data from a data control.
As It takes you through several steps, the Wizard will prompt you for the
information it needs to build the data forms properly. However, because the forms
the Wizard builds are fairly generic, you will probably modify them to more closely
resemble the remaining forms in your application. To see how this Wizard works,
start anew project, and open the Data Form Wizard form the Add-Ins menu.
The first dialog to be displayed is the Introduction dialog, which allows you to select
a data form profile you have previously [Link] this demo, click Next to choose
the database type with which you are working. At this time, there are only two
database types to choose from: Microsoft Access and open database connectivity
(ODBC). Choose Access and click Next to continue. After you’ve selected your
database type, you must specify the actual database location or connection
information. For Access, you are prompted for the database location as shown in
Figure 9.13, however, if you are using ODBC, you will be prompted for the
appropriate connection information as shown in Figure 9.14
186 Centre for Information Technology and Engineering, Manonmaniam Sundaranar University
Handling Database
Locate and select the North Wind database ([Link]) in the Visual Basic
directory and then click Next to continue. As you move to the next dialog, the
Wizard actually connects to and opens the specified database. The form dialog
(Figure 9.15)asks you for the name of the new form, the form layout you want t o
create, and the type of data access connection to use.
Centre for Information Technology and Engineering, Manonmaniam Sundaranar University 187
Advanced Visual Basic
Because each of the form layouts requires slightly different information, the
remaining steps will vary depending on the form layout you have chosen. For this
example choose the Master/Detail form layout and leave the default Binding type of
ADO Data Control. Finally, name the new form “CH16Demo” and click the Next
Button. Because you selected the Master/Details layout, you will now be prompted
for the record source and fields for both the master and detail queries. The first
dialog, Master Record Source ( see Figure 9.16) requests the master query source.
Figure 9. 16– Selecting the master record source for the Wizard to use
From the record source drop-down, select the Customers table; then select the fields
shown in fig. Finally, set the sort column to City and click the next button to define
the detail query information. As you see form figure 9.17, the Detail Record Source
dialog looks exactly like the Master dialog.
Figure 9.17 – Defining the join relationship between the two queries
On this form, select the Orders table from the Record Source drop-down, and then
select the fields shown in figure. Again, set the sort column to OrderDate and click
188 Centre for Information Technology and Engineering, Manonmaniam Sundaranar University
Handling Database
Next to continue. The Record Source Relation dialog( see figure 9.18) requires you to
set the relationship or “join” between the Master and Detail queries.
Figure 9.18 – Defining the join relationship between the two queries
Set the CustomerID as the fields that links the two sources and click Next. The
Control Selection dialog (see fig 9.19) lets you choose the data navigation and
manipulation controls you want to appear on the form and enables the Wizard to
create the associated code for each selected control. The available controls to choose
from are the following :
• Add – Places an Add button on the form with the associated code to add new
records to the database
• Update – Adds the Update button and its associated code to update the database
from the form. This button is available only if you are using the Data Control
Binding Type.
• Refresh – Will add the code and command button to allow the user to request a
database refresh.
• Close – Includes the code and command button to close the data form
• Show Data Control – If this checkbox is clicked, the Data Control will be
displayed on the form.
Centre for Information Technology and Engineering, Manonmaniam Sundaranar University 189
Advanced Visual Basic
Figure 9.19 Choosing the data command buttons to place on the form
For this example, leave the defaults and click Next. You can now save all of the
settings you have selected as part of a profile. Then click the Finish button to allow
the Wizard to perform its magic. The form shown in figure 9.20 is the end result of all
of the options you selected.
Try running this program to see how the Master/Detail form works. Basically, you
will see one customer at a time with all of the customer’s orders listed in the grid, as
shown in figure 9.21
Figure 9. 20 – The finished data form crated by the Data Form Wizard
190 Centre for Information Technology and Engineering, Manonmaniam Sundaranar University
Handling Database
Figure 9.21– Using the Finished form to display information from the database
Using the data Control, switch to a new customer and you will see the order
information change as well. By using the Data form Wizard, you can create data-
aware applications with very little effort. However, after the Wizard has created the
forms, you must maintain the form layout and its associated code. Finally,
remember that each of the different layouts will require slightly different information
to create its associated form.
) Visual Data Manager is used to create databases tables, queries and indexes and
to modify them.
) Intrinsic Data control can be used to create applications that display, edit, and
update information from many types of existing databases, including Microsoft
Access, Btrieve, dBase, Microsoft FoxPro, and Paradox.
) To open already existing access database choose File/Open Database/Microsoft
Access. And Select the database name in the Open Microsoft Access database
dialog box
1. Create a Data base with the following given fields using Data Visual Manager
Student number, name, tamil, english, maths, physics, chemistry marks.
Centre for Information Technology and Engineering, Manonmaniam Sundaranar University 191
Advanced Visual Basic
Lecture - 10
Objectives
192 Centre for Information Technology and Engineering, Manonmaniam Sundaranar University
Data Access Object
Lecture Unit - 10
Centre for Information Technology and Engineering, Manonmaniam Sundaranar University 193
Advanced Visual Basic
Data Access Objects (DAO) communicate with Microsoft Access and other
ODBC- complaint data sources through the JET engine. They provide
properties and methods that allow to perform all the operations necessary to
manage such a system, including the ability to do the following figure 10.1
Create databases
Define tables, fields, and indexes.
Establish relations between tables.
Navigate and query the database, and so on.
Figure 10.1 A typical remote data access using DAO and the JET engine.
The Data Access Objects (DAO) model is a collection of object classes that
provide properties and methods for database programming. This model
furnishes facilities for creating databases, defining tables, fields and indexes,
establishing relations between tables, navigating and querying the database,
and so on.
The Microsoft Jet database engine translates operations on data access objects
into physical operations on the database files, handling all the mechanics of
interfacing with the different supported databases. This approach simplifies
access to the database and insulates from the underlying mechanics of
retrieving and updating data. It affords great flexibility because the same
objects, properties and methods can be used with a wide variety of supported
database formats.
194 Centre for Information Technology and Engineering, Manonmaniam Sundaranar University
Data Access Object
Through DAO and the JET engine, Visual Basic recognizes three categories of
databases, and these are summarized below:
Category Description
Visual Basic Databases Also called native databases, these database files use
the
(Native MS Jet Databases) same format as Microsoft Access. These databases are
created and manipulated directly by the Jet engine and
provide maximum flexibility and speed.
ODBC Databases These include client/server databases that conform to the ODBC standard,
such as Microsoft SQL Server and Oracle.
DAO is the only data access technology that supports 16-bit operations. If an
application must run within a 16-bit environment, then DAO is the only choice.
If the application must access both native Microsoft Jet and ODBC resources,
DAO provides a consistent programming model.
Centre for Information Technology and Engineering, Manonmaniam Sundaranar University 195
Advanced Visual Basic
DAO Library
Visual basic includes DAO version 3.51. To access any of these objects, a reference to the
DAO object library must be included. To include this reference choose Project | References.
This will display References dialog box that resembles Figure 10.2
Select Microsoft DAO 3.51 object library and click OK. This will
include a reference to DAO library to the current project.
Note : The Database engine is what actually reads, writes, and modifies the
database, and handles all the housekeeping chores like indexing, and
security etc.
The Figure 10.3 shows the DAO object model.
196 Centre for Information Technology and Engineering, Manonmaniam Sundaranar University
Data Access Object
The DAO objects and their important method(s) are briefed below:
DBEngine object This base DAO object holds all other objects and maintains
engine options.
Method Description
Workspace object Defines and manages the current user session. This object
contains information on open databases and provides mechanisms for
simultaneous transactions.
Method Description
Centre for Information Technology and Engineering, Manonmaniam Sundaranar University 197
Advanced Visual Basic
Database object Represents a database with at least one open connection. This
can be a Microsoft Jet database or an external data source.
Method Description
TableDef object Contains both Field and Index objects to describe the database
tables.
Method Description
CreateIndex Creates a new Index object (Microsoft Jet
workspaces only).
QueryDef object Represents a stored SQL query statement, with zero or more
parameters, maintained in a Microsoft Jet database.
Method Description
198 Centre for Information Technology and Engineering, Manonmaniam Sundaranar University
Data Access Object
Recordset object Represents a query result set with a cursor. DAO has five types
of Recordset objects: table, dynaset, snapshot, forward-only, and dynamic.
Centre for Information Technology and Engineering, Manonmaniam Sundaranar University 199
Advanced Visual Basic
Method Description
CreateField Creates a new Field object
Method Description
CreateField Creates a new Field object
Error object Contains information about an error that occurred during a DAO
operation. When more than one error occurs during a single DAO operation,
each individual error is represented by a separate Error object.
Create the workspace Defines the user session, including user identification,
password, and database type (such as Microsoft Jet or ODBC).
200 Centre for Information Technology and Engineering, Manonmaniam Sundaranar University
Data Access Object
Open the recordset Runs an SQL query (with or without parameters) and
populates the recordset.
Use the recordset The query result set is now available to the application.
Depending on the cursor type, the row data can be browsed and changed.
Close the recordset Drops the query results and closes the recordset.
Close the database Closes the database and releases the connection.
The following code shows how to open the database Students and to close it.
Dim ws as Workspace
Dim db as database
‘ Closing workspace
[Link]
The example in the previous section showed that a Database object represents
an open database. This object helps to:
Centre for Information Technology and Engineering, Manonmaniam Sundaranar University 201
Advanced Visual Basic
Syntax :
The argument type is a constant that indicates the type of Recordset to open,
which can have any one of the following values.
Constant Description
Opens a table-type Recordset object (Microsoft
DbOpenTable
Jet workspaces only).
Opens a dynaset-type Recordset object. I.e, it
DbOpenDynaset specifies recordset type that can contain fields
from more than one table.
Opens a snapshot-type Recordset object. It
DbOpenSnapshot similar to dynaset-type, except that it gives
read-only records.
Opens a forward-only-type Recordset object. It
DbOpenForwardOnly specifies recordset in which navigation can take
place in forward direction only.
Dim db as Database
Dim rs a Recordset
--- or ----
‘ Opening the StudentsDtls table with selected records
Set rs = [Link](“Select * from StudendDtls where_
202 Centre for Information Technology and Engineering, Manonmaniam Sundaranar University
Data Access Object
The Microsoft jet database engine provides page level locking. Pages are blocks of
records that are 2048 bytes (2k) in size. Visual basic stores as many records as will fit
on each page. When Visual Basic locks the page containing a record you’re editing,
all the other records on that page will also be locked .
The value of the LockEdits peoperty of the Recordset object determines when a lock
isplaced on the records in a recordset.
Pessimistic locking
The default locking strategy locks records for a longer period of time, but ensures
that once the Edit method has been executed another user cannot change the data.
Optimistic locking:
If the lockEdit property is False, optimist locking is in effect. The page containing
the record is locked only while the record is being updated.
Locks are in place for a shorter period of time, and multiple users can use the Edit
method without locking the page. However when you use optimistic locking, you’ll
need to handle possible errors when the user executes the update method.
If you do not expect users to attempt to modify the same record very often, consider
setting LockEdits to False.
Centre for Information Technology and Engineering, Manonmaniam Sundaranar University 203
Advanced Visual Basic
Unlocking
The Microsoft jet database engine marks a page to be unlocked as soon as the update.
Completes. However, Locks are not removed until other actions are complete.
You can use the Idle method of the DBengine object with the dbFreelocks options
to suspend processing and allow the Microsoft jet database engine to release locks
and catch up on other background tasks, as shown in the following code.
When multiple users are updating a database, you’ll need to add code that traps for
the following errors.
Occurs on the Edit method when the record is locked. Your code should wait for a
short interval, and then call Edit again, or inform the user of the error.
Occurs on the Update method when the record is locked. Your code should wait for
a short interval, and then call Update again or inform the user of the error.
Occurs on the Edit or Update method if another user has changed data since you last
accessed it. Your code should refresh the form with the latest data or inform the user
of the error.
For a complete list of errors available I Visual Basic, see Trappable Errors in Visual
Basic.
204 Centre for Information Technology and Engineering, Manonmaniam Sundaranar University
Data Access Object
) When you access databases through ODBC, the locking mechanism is handled by
the database management
) DAO is the only data access technology that supports 16-bit operations
1. What is the difference between connecting a database through DAO and data
control
2. When DAO concept is introduced and state the features
3. Through DAO can we connect non database objects
• File
Open database
Open recordset
Open qryrecset
• Manipulation
Addnew
Edit
Update
Delete
Centre for Information Technology and Engineering, Manonmaniam Sundaranar University 205
Advanced Visual Basic
4. Write code for each of the above mentioned sub menus to perform its
corresponding task accordingly with the below given details:
5. In the Command Button named “View”, Open a record set to fetch only
the “Eno” and add it on to “Combo 1”. Once when an “Eno” is selected
from the Combo1, the corresponding Eno’s information should be shown
in the text boxes.
206 Centre for Information Technology and Engineering, Manonmaniam Sundaranar University
Remote Data Control
Lecture - 11
Objectives
Centre for Information Technology and Engineering, Manonmaniam Sundaranar University 207
Advanced Visual Basic
Lecture unit - 11
208 Centre for Information Technology and Engineering, Manonmaniam Sundaranar University
Remote Data Control
The Remote Data Control is another way for accessing remote data in visual
basic application. the user can interact data through the user interface controls
like browsing the data, performing updates and adding records remote data
control binds data-aware controls to an ODBC remote database, and the
remote data object.
The Remote Data Control (RDC) binds controls to an ODBC remote database.
The Remote Data Control is similar to the data control, except that it creates
and manipulates RDO objects. RDO and RDC helps to access ODBC data
sources through data –aware, or bound controls without going through the
JET engine, resulting in significantly higher performance and greater
flexibility when accessing remote data sources.
Figure 11.1 The Remote Data control, RDO and bound controls.
The Remote Data control performs all operations on the current row. The
Remote Data Control automatically handles a number of contingencies,
including empty resultsets, adding new rows, editing and updating existing
rows, converting and displaying complex data types, and handling some
types of errors.
Centre for Information Technology and Engineering, Manonmaniam Sundaranar University 209
Advanced Visual Basic
210 Centre for Information Technology and Engineering, Manonmaniam Sundaranar University
Remote Data Control
However, most applications rely on additional RDO code to perform most data
access operations, as RDO provides more flexibility and additional options not
exposed by the RemoteData Control alone. In most respects, the RemoteData Control
behaves very much like the Data control.
If the RemoteData control is instructed to move to a different row, all bound controls
automatically pass any changes to the RemoteData control to be saved by the ODBC
data source. The RemoteData control then moves to the requested row and passes
data back from the current row to the bound controls, where it is displayed.
) The Data control supports the ability to use the RDO DLLs via the ODBCDirect
option. In this case, your code uses Data Access Objects (DAO) instead of RDO to
manage the Data control and its result sets.
) RDC property can be set as an alternative to the Connect property
) The remote data control behaves like the Jet-driven data control and RDC is
efficient than DC when dealing with the Remote Databases
) The Remote Data control's SQL property is like the Data control's Record Source
property except that it cannot accept the name of a table
Centre for Information Technology and Engineering, Manonmaniam Sundaranar University 211
Advanced Visual Basic
4. Link the data source( Trading Company) to this form. The data source can be got
from the file [Link] in your VB folder
4. Link the data source( Authors ) to this form. The data source can be got from
the file [Link] in your VB folder
"SELECT * FROM AUTHORS"
212 Centre for Information Technology and Engineering, Manonmaniam Sundaranar University
Remote Data Objects
Lecture - 12
Objectives
Centre for Information Technology and Engineering, Manonmaniam Sundaranar University 213
Advanced Visual Basic
Lecture Unit - 12
214 Centre for Information Technology and Engineering, Manonmaniam Sundaranar University
Remote Data Objects
Remote Data Objects (RDO) and collections provide a framework for using
code to create and manipulate components of a remote ODBC database
system. RDO is Visual Basic’s flagship interface to relational ODBC data
sources.
RDO is specifically designed to deal with remote intelligent data sources such
as SQL server and Oracle. RDO can execute ordinary table-based queries, but
it is especially good at building and executing queries against stored
procedures.
The following advantages are associated with the RDO programming model:
• All remote databases such as SQL Server and Oracle can virtually be
accessed.
Centre for Information Technology and Engineering, Manonmaniam Sundaranar University 215
Advanced Visual Basic
RDO is a very thin(less than 250K) object layer on the top of the ODBC API.
This makes it very fast but still easy to use. RDO does not have its own query
processor, so all work is done by the ODBC datasource. This means no
heterogeneous operations. RDO cannot connect to ISAM datasources; the
Access ODBC driver must be used to connect to an Access or ISAM database.
This approach is slower and does not have access to all the functionality
provided by using DAO to access these types of datasources.
RDO does not have its own version of the data control called the remote data
control, with abilities similar to the data control based on DAO. The remote
date control can be used to generate applications fast without a lot of code.
RDO does require that its datasources have 32-bit Level II- complaint driver.
Since RDO is a layer on top of the ODBC API, you can often use RDO in
conjunction with the ODBC API for even more flexibility and power. Mixing
and matching data access methods this way is considered risky, and Microsoft
warns that general protection faults and data loss may result.
Though Remote Data Objects (RDO) are designed to work with ODBC, they
can be used in similarly as DAO. Using the RDO
Using RDO is very much like using DAO. However, there are some
differences. These differences and similarities are given in below.
Remote Data Objects refer to table rows instead of records and columns instead
of fields — the generally accepted terminology for relational databases. The
data returned from a query is in the form of result sets, which can contain
zero or more data rows composed of one or more columns.
216 Centre for Information Technology and Engineering, Manonmaniam Sundaranar University
Remote Data Objects
The following table lists RDO 2.0 objects and their equivalent DAO/Jet
objects.
Remote Data Objects (RDO) is a thin layer over the ODBC application-programming
interface (API). RDO depends on the ODBC driver and the database engine for much
of its functionality. Data access using RDO is intended for only ODBC relational
databases.
Centre for Information Technology and Engineering, Manonmaniam Sundaranar University 217
Advanced Visual Basic
The RDO objects and their important method(s) are briefed below:
rdoEngine object The base RDO object. This object is created automatically.
Method Description
rdoError object Handles all ODBC errors and messages generated by RDO. This
object is created automatically.
rdoEnvironment object Defines a logical set of connections and transaction scope for
a particular user name. This object contains both open and allocated (but unopened)
connections. This object is created automatically.
Method Description
OpenConnection Opens a connection to an ODBC data source and
returns a reference to the rdoConnection object that
represents a specific database.
218 Centre for Information Technology and Engineering, Manonmaniam Sundaranar University
Remote Data Objects
Method Description
Method Description
rdoColumn object Represents a column of data, including data type and common
properties.
Method Description
Other methods such as AddNew, Update, and Move etc. are same as their
counterparts in DAO.
Records
Examples
Centre for Information Technology and Engineering, Manonmaniam Sundaranar University 219
Advanced Visual Basic
Dim s as string
s = “select * from emp1”
set rs = [Link] (Name:=s, Type:=rdOpenDynamic,_LockType:=
rdConcrRowVer)
If [Link] <> True Then
Call Displayrecord
Else
MsgBox “ No record found”
End If
End sub
When the user click the Add commandbutton, it clears the form and allows
the entry of new information by the user.
[Link]
[Link]
End sub
The Update routine is used to save the changes that are made to the current
record
Private Sub Update_Click ()
[Link]
rs(“dept_no”) = [Link]
220 Centre for Information Technology and Engineering, Manonmaniam Sundaranar University
Remote Data Objects
rs(“dept_name”) = [Link]
[Link]
end sub
When the user click the Delete command Button, the current record must be
deleted from the table.
Centre for Information Technology and Engineering, Manonmaniam Sundaranar University 221
Advanced Visual Basic
8. Use the Open Resultset method to display the records from the
respective table in the textboxes.
9. Perform the manipulations such as addnew, edit & update with the respective
coding addnew, update & edit methods.
11. Find a record based on the Empno using the RDO Query.
12. Write a code segment to call a procedure (Remote Procedure) that returns the
summation of two numbers.
222 Centre for Information Technology and Engineering, Manonmaniam Sundaranar University
ActiveX Data Objects
Lecture - 13
Objectives
Centre for Information Technology and Engineering, Manonmaniam Sundaranar University 223
Advanced Visual Basic
224 Centre for Information Technology and Engineering, Manonmaniam Sundaranar University
ActiveX Data Objects
In the Cyber world new and new things are being invented to replace the already
existing one. The Active X Data Objects provides very easy access to any data source
with high speed via the OLE DB. And the ADO Data control allows to quickly
create a connection to a database using ActiveX Data Object (ADO).By using a DAO
–like approach, developers can now access an even border variety of data sources
using both OLE DB service providers and existing ODBC drivers through its OLE DB
for ODBC intermediate interface.
It is emerging as another data access alternative, which may replace the need
for other interfaces. ADO enables to write a client application to access and
manipulate data in a database server through a provider. ADO’s primary
benefits are ease of use, high speed, low memory overhead, and a small disk
footprint.
ADO is designed to eventually negate the need for all other interfaces. ADO
is not specifically designed for ISAM or relational database access, but as an
object interface to any data source. ADO is built around a set of core
functions that all data sources are expected to implement.
Centre for Information Technology and Engineering, Manonmaniam Sundaranar University 225
Advanced Visual Basic
Support for stored procedures with in/out parameters and return values.
Support for limits on the number of returned rows and other query goals.
Visual basic also includes ADO Data Control (ADODC), which works in the
similar manner to the Remote Data control, except that it uses OLE DB
provider instead of ODBC Driver.
Flat objects Model: ADO does not impose hierarchical object creation. That is to
create a Recordset object in DAO, a Workspace object and a Database object are to be
created first. Then alone Recordset object can be created. In ADO either this kind of
hierarchical creation can be followed or its objects can be created independently.
Less number of objects: ADO does not have large amount of objects like DAO and
RDO, which leads difficulty in coding. ADO objects set is lesser than DAO and
RDO, but more powerful.
Direct assignment to Data bound controls: To fill data bound controls its data
source property can be set to a Recordset object instead of setting to a data control
(explained later in this chapter).
Recordset persistence: Recordset data can be saved in a file. Later this persisted file
can be used to recreate the RecordSet object.
The ADO works with OLE DB data providers to provide a mechanism for
manipulating the data they contain. The ADO can be thought of as a
specialized OLE DB data consumer. The relationship between the ADO and
OLE DB is just like the relationship between RDO and ODBC. The ADO
accesses OLE DB data sources, and when using the OLE DB ODBC data
provider, the ADO can access ODBC data sources also.
Visual Basic 6.0, includes ADO version 2.0. To access any of these objects, a
reference to the ADO object library must be included. To include this
reference, Choose Project | References to display References dialog box.
226 Centre for Information Technology and Engineering, Manonmaniam Sundaranar University
ActiveX Data Objects
Select Microsoft ActiveX Data Objects 2.0 Library in the Available References list and
click OK.
Each of the Connection, Command, Recordset, and Field objects also has a
Properties collection.
Centre for Information Technology and Engineering, Manonmaniam Sundaranar University 227
Advanced Visual Basic
á Define the executable text of the command (for example, an SQL statement)
with the CommandText property.
á Execute a command and return a Recordset object if appropriate with the
Execute method.
228 Centre for Information Technology and Engineering, Manonmaniam Sundaranar University
ActiveX Data Objects
The Number property, which contains the Long integer value of the error constant.
The Source property, which identifies the object that raised the error. This is
particularly useful when there are several Error objects in the Errors collection.
Each error object in the Errors collection can be accessed separately. The
following example shows how to display the description of all created error
objects.
Example:
Dim errobj As [Link]
Dim con As [Link]
Centre for Information Technology and Engineering, Manonmaniam Sundaranar University 229
Advanced Visual Basic
A Recordset object has a Fields collection made up of Field objects. Each Field
object corresponds to a column in the Recordset. The Value property can be
used to set or return data depending on the functionality the provider
exposes, some collections, methods, or properties of a Field object may not be
available.
230 Centre for Information Technology and Engineering, Manonmaniam Sundaranar University
ActiveX Data Objects
Dynamic properties are defined by the underlying data provider, and appear
in the Properties collection for the appropriate ADO object. For example, a
property specific to the provider may indicate, if a Recordset object supports
transactions or updating. These additional properties will appear as Property
objects in that Recordset object’s Properties collection. Dynamic properties
can be referenced only through the collection, using like [Link](0)
or [Link](name) syntax.
á The Type property is an integer that specifies the property data type.
A Recordset object represents the entire set of records from a base table or the
results of an executed command. At any time, the Recordset object refers to
only a single record within the set as the current record.
Centre for Information Technology and Engineering, Manonmaniam Sundaranar University 231
Advanced Visual Basic
To Save changes to the current record Update method is used. In the ADO
model to change the data of the current, there is no need to call Edit method
(actually the Edit Method is not the Method of Record Set object of ADO) as
in DAO and RDO.
Sort and Filter the rows of a RecordSet object using Sort and Filter properties.
These properties are briefed below and used in the example.
Refresh the entire contents of a Recordset object from the data source using
Requery method.
Example:
Dim rs as [Link]
232 Centre for Information Technology and Engineering, Manonmaniam Sundaranar University
ActiveX Data Objects
----------------------------------
[Link]
----------------------------------
[Link]
ADO Methods
Syntax:
[Link] ConnectionString, UserID, Password ,options
Parameters Description
Centre for Information Technology and Engineering, Manonmaniam Sundaranar University 233
Advanced Visual Basic
server=Or8;uid=sa;pwd=pwd”
Here the connection object is declared with the keyword New in the
declaration. All the ADO objects must be declared in similar manner.
Because the ADO is based on Component Object Model technology (COM).
So they can’t simply be declared. They must be created using new keyword.
If ADO objects are declared without the New keyword then before using
them, they must be set as new objects. The following code shows how the
connection object is set as new connection object after it is declared without
new keyword.
In all the above examples the Provider argument is not specified. So, while
opening the connection the default provider parameters are used. The
following section explains about providers and their classifications.
The ADO Data control uses Microsoft ActiveX Data Objects (ADO) to quickly
create connections between data-bound controls and data providers (any
controls that feature a DataSource property). Data providers can be any
source written to the OLE DB specification.
234 Centre for Information Technology and Engineering, Manonmaniam Sundaranar University
ActiveX Data Objects
On the Toolbox, click the ADO Data Control to select it. Then press F4 to
display the Properties window.
The connection string can be specified in any one of the following ways:
• If a Microsoft Data link file (.UDL) is available for the require database,
select Use OLE DB File and click Browse to find the file ([Link])
on the computer.
• If using DSN is desired, then Use ODBC Data Source Name and select a
DSN from the combo box.
Centre for Information Technology and Engineering, Manonmaniam Sundaranar University 235
Advanced Visual Basic
To set the RecordSource property click the button with the caption “...”
In the Properties window, set the DataSource property for Text1 to the name
of the ADO Data control (ADODC1). This binds the text box to the ADO Data
control.
In the Properties window, click DataField and a list of available fields will
drop down. Click the name of the field, which is desired for display.
236 Centre for Information Technology and Engineering, Manonmaniam Sundaranar University
ActiveX Data Objects
Microsoft supplied new data bound controls with Visual Basic 6.0 namely
DataGrid, DataList, and DataCombo. They are ADO versions of DBGrid,
DBList and DBCombo respectively, and can be used in the same way of later.
But the ADO version of data bound controls have one advantage. So far data
bound controls are filled up using a data control. Now instead of data
controls, recordset objects can behave as data supplier to the data bound
controls. The following example shows how a recordset object can supply
data to a Data bound grid control.
The above statement will cause the DataGrid1 be filled up by the products
table of Nwind database.
There is one more data bound control, the Hierarchical Grid control, which
has more flexibility to display the data.
ADO Data Control includes a number of events that are user programmable. The
events listed in Table lists the events and when they occur.
Events Occurs
WillMove On [Link],
Centre for Information Technology and Engineering, Manonmaniam Sundaranar University 237
Advanced Visual Basic
[Link] [Link]
[Link] [Link],
[Link] [Link],
[Link] RecordsetDelete,[Link]
[Link]
MoveComplete After WillMove
WilllChangeField Before the Value property changes
FieldChangeComplete AfterWillChangeField
WillChangeRecord On [Link],[Link],
[Link],[Link]
[Link]
RecordChangeComplete After WillChangeRecord
WillChangeRecordset On
[Link],[Link],[Link]
[Link],[Link]
RecordsetChangeComplete After WillChangeRecordset
InfoMessage When the data provider returns a result.
238 Centre for Information Technology and Engineering, Manonmaniam Sundaranar University
ActiveX Data Objects
Establish Connection
4. Open Recordset and display records in the Text boxes Perform Data
Manipulations like Addition, Deletion, Modification Perform Navigation
methods
5. Try using Action Queries with the help of Command Object Using Command
Object, try executing a Remote Procedure that gives the sum of two numbers
6. Add a Form
7. Choose Microsoft ADO Data Control
Project Æ Components Æ Microsoft ADO Data Control 6.0 (OLE DB)
Centre for Information Technology and Engineering, Manonmaniam Sundaranar University 239
Advanced Visual Basic
240 Centre for Information Technology and Engineering, Manonmaniam Sundaranar University
Connecting to a ADO Database
Lecture - 14
Connecting to a
ADO Database
Objectives
Centre for Information Technology and Engineering, Manonmaniam Sundaranar University 241
Advanced Visual Basic
Lecture Unit - 14
242 Centre for Information Technology and Engineering, Manonmaniam Sundaranar University
Connecting to a ADO Database
Using the ADO Data control in your applications is no more difficult than
using the standard DAO Data control. In the following example, you will
create a sample front end for an ADO database. Although this application is
very simplistic, it does illustrate how easy it is to create an application using
ADO. To create the front end for the Database, perform the following steps:
1. Confirm that you have a valid .MDL file if you will be using an OLE DB Data
source.
2. Start a new project. On the form, place an ADO control. If the ADO control. If the
ADO control is not available in your toolbox, you can add it from the
Components dialog box and select the Microsoft ADO Data Control option
shown in Figure 14.1
Figure 14.1 – The ADO Data control is added to the toolbox after the Components
dialog box is closed
3. In the Properties window of the ADO control, click the ellipsis button on the
ConnectionString property to display the ConnectionString dialog box. This is
shown in Figure 14.2
Centre for Information Technology and Engineering, Manonmaniam Sundaranar University 243
Advanced Visual Basic
Figure 14.2 : Property pages allow you to enter the ODBC source and connecting
string information
4. Select the General tab. If you have created a Data Link file (.MDL), select the Use
Data Link File check box and click the Browse button to locate the .MDL file.
Alternatively, you coluld select either the Use ODBC Data Source Name or Use
Connection String check boxes to create a connection to your database.
5. In the properties window of the ADO control, click the ellipsis button to display
the Record Source dialog box. In the Command Text(SQL) text box, enter the
following SQL statement:
SELECT * FROM Authors WHERE Au_ID = 72
Figure 14.3– SQL statements can also be enter via the RecordSource tab on the
Property Pages dialog box
6. Place two labels and two text boxes on the form. The captions of the text boxes
should be Author and Author ID
244 Centre for Information Technology and Engineering, Manonmaniam Sundaranar University
Connecting to a ADO Database
7. Set the DataSource property for Text1 and Text2 to the name of the ADO control
on the form.
10. Press F5 to run the application. The Completed form should resemble the one in
Figure 14.4
The ADO Data Control can be major resource hog. The ADO control will
automatically use at least two connections for the first ADO control on a form.
Additional ADO controls on the same form require one connection each.
Example
ADO can be used to connect with a OLE DB datasource and non data base types also
Centre for Information Technology and Engineering, Manonmaniam Sundaranar University 245
Advanced Visual Basic
BOF (Beginning Of File): This property returns a Boolean value that indicates
whether the current record position is before the first record in a Recordset
object.
EOF (End Of File): This property returns a Boolean value that indicates
whether the current record position is after the last record in a Recordset
object.
The BOF property returns True if the current record position is before the
first record, and False if the current record position is on or after the first
record.
The EOF property returns True if the current record position is after the last
record, and False if the current record position is on or before the last record.
The BOF and EOF properties can be used to determine whether a Recordset
object contains records or whether the cursor has gone beyond the limits of a
RecordSet object when one of a Move method is used to move the record
pointer from record to record.
If both the BOF or EOF property is True, it means there is no current record.
If an attempt is made to move beyond the limits of a RecordSet object then an
error will occur. So these properties can be used in conjunction with the move
methods. For example, to prevent the move operation beyond the last record
the following code may be used.
[Link]
If [Link] Then
MsgBox "End of the file! , Pointer being moved to last_ record."
[Link]
/End If
246 Centre for Information Technology and Engineering, Manonmaniam Sundaranar University
Connecting to a ADO Database
At the end of the RecordSet rs, its EOF property is set to True. So, as the if
condition satisfies the MoveNext method will be roll backed. Similarly the
BOF property can be used with the MovePrevious method.
Passenger Details
Passenger Id, Passenger Name,Age,Sex,Train name, Class booked
Train Details
Train name, Train no, I class fare, II class fare, Unreserved fare, I seats, II seats
Traiin Pass Details
Passenger id, Coach No, seat no, Date of journey
2. Create a project to list the passenger ids in the combobox and to list the details of
the passenger ( Train number, seat number and ticket fare)
Centre for Information Technology and Engineering, Manonmaniam Sundaranar University 247
Advanced Visual Basic
248 Centre for Information Technology and Engineering, Manonmaniam Sundaranar University
Multiple Document Interface
Lecture - 15
Multiple Document
Interface
Objectives
Centre for Information Technology and Engineering, Manonmaniam Sundaranar University 249
Advanced Visual Basic
Lecture Unit - 15
250 Centre for Information Technology and Engineering, Manonmaniam Sundaranar University
Multiple Document Interface
A Multiple Document Interface is used for opening many windows at the same
[Link] the document windows are contained in a parent window, which provides a
workspace in the application. Visual Basic applications can have only one MDI form,
which contains all the child forms. A chile form is an ordinary Form that has its
Child property set to Trus. Child forms are displayed within the internal area of a
MDI Form at run time.
Mainly there are two styles of interfaces in the windows based applications: the
single-document interface (SDI) and the multiple-document interface (MDI). An example
of the SDI interface is the WordPad application included with Microsoft Windows. In
WordPad, only a single document may be open and in order to open another, the
currently opened document must be closed. The Figure 5.12 shows the Wordpad
application, which is a SDI application.
Applications such as Microsoft Excel and Microsoft Word for Windows are MDI
interfaces; they allow displaying multiple documents at the same time, with each
document displayed in its own window. A MDI application can be recognized by the
inclusion of a Window menu item with submenus for switching between windows
or documents. The Figure 5.2 shows the Excel, which is a MDI application.
Centre for Information Technology and Engineering, Manonmaniam Sundaranar University 251
Advanced Visual Basic
Menu
Any program with more than a few simple functions or features can benefit from the
addition of a well-built menu. When designing a program, the main goal is to make
its features as easy as possible. A well-designed menu will accomplish this goal.
With the help of good menu, programs will seem natural and familiar, as they offer a
convenient and consistent way to group commands and an easy way for users to
access them. The Figure 5.3 illustrates the elements of a menu interface on a Form.
The menu bar appears immediately below the title bar on the Form and contains one
or more menu titles. When a menu title is clicked (such as File), a menu containing a
list of menu items drops down. Menu items can include commands (such as New
and Exit), separator bars, and submenu titles. To make application easier to use,
252 Centre for Information Technology and Engineering, Manonmaniam Sundaranar University
Multiple Document Interface
menu items must be grouped according to their function. In the above, for example,
the file related commands New, Open, and Save As are all found on the File Menu.
Centre for Information Technology and Engineering, Manonmaniam Sundaranar University 253
Advanced Visual Basic
In Visual Basic a child form is an ordinary Form that has its MDIChild property set
to True. An application can include many MDI child forms of similar or different
types. At run time, child forms are displayed within the workspace of the MDI parent
form (the area inside the form's borders and below the title and menu bars). When a
child form is minimized, its icon appears within the workspace of the MDI form
instead of on the taskbar, as in Figure 5.4.
Figure 5.4 Child forms displayed within the workspace of the MDI form.
An MDI application can also include standard, non-MDI forms that are not
contained in the MDI form. A typical use of a standard form in an MDI application is
to display a modal dialog box.
An MDI form is similar to an ordinary form with one restriction. Intrinsic controls
can't be placed on a MDI form unless they have the Align property (such as a picture
box control) or invisible interface (such as a timer control). More over an application
can have only one MDI form. The MDI Form’s main property and method are given
below:
Property Description
ActiveForm It specifies the active MDI child form.
254 Centre for Information Technology and Engineering, Manonmaniam Sundaranar University
Multiple Document Interface
Method Description
Arrange Arranges the windows or icons within a MDIForm
object
Syntax
[Link] arrangement
To cascade the child Forms of the MDIForm1 the following statement is used.
[Link] vbCascade
MDI form and all of its child forms take on special characteristics:
All child forms are displayed within the MDI form's workspace. The user can
move and size child forms like any other form; however, they are restricted to
this workspace.
When a child form is minimized, its icon appears on the MDI form instead of the
taskbar. When the MDI form is minimized, the MDI form and all of its child
forms are represented by a single icon. When the MDI form is restored, the MDI
Centre for Information Technology and Engineering, Manonmaniam Sundaranar University 255
Advanced Visual Basic
form and all the child forms are displayed in the same state they were in before
being minimized.
When a child form is maximized, its caption is combined with the caption of the
MDI form and is displayed in the MDI form's title bar (see Figure 5.5).
The active child form's menus (if any) are displayed on the MDI form's menu bar,
not on the child form.
Figure 5.5 A child form caption combined with the caption of an MDI form.
) MDI stands for Multiple Document Interface, Which is used for opening
several windows at the same time.
) In Word pad application only a single document may be open and in order to
open another, the currently opened document must be closed.
) MicroSoft is a multiple document Interface.
256 Centre for Information Technology and Engineering, Manonmaniam Sundaranar University
Multiple Document Interface
3. On clicking the Picture & Application button another form should be loaded.
Centre for Information Technology and Engineering, Manonmaniam Sundaranar University 257
Advanced Visual Basic
Lecture - 16
Menus
Objectives
About Menu
258 Centre for Information Technology and Engineering, Manonmaniam Sundaranar University
Menus
Lecture Unit - 16
Centre for Information Technology and Engineering, Manonmaniam Sundaranar University 259
Advanced Visual Basic
Menus are one of the most common and characteristic elements of the
Windows user interface. Even in the old days of character-based displays,
menus were used to display methodically organized choices and guide the
user through an application. Despite the visually rich interfaces of Window
applications and the many alternatives, menus are still the most popular
means of organizing a large number of options. Many applications duplicate
some or all of their menus in the form of icons on a toolbar, but the menu is a
standard fixture of a Form. You can turn the toolbars on and off, but not the
menus.
Visual Basic provides Menu Editor, which helps to create new menus, add new
commands to existing menus, and change and delete existing menus. Menus can be
attached only to forms, and you design them with the Menu Editor. To see how the
Menu Editor works, start a new Standard EXE project, and when form1 appears in
the design window, choose Tools>Menu Editor to open the Menu Editor.
Alternatively you can click the Menu Editor button on the toolbar
Feature Convention
Access Keys Each menu item should be assigned a access key (the
underlined letter in a menu or menu selection) to allow for
keyboard access to the menu choices. The key should be
unique in each section of the menu and is normally the first
letter of the caption.
Shortcut Keys Any menu features that are frequently used or need to be
available from any part of the program should be assigned a
shortcut key. For example, the Ctrl+N is the shortcut key for
the New item of the File menu in the most of the windows
applications. Each shortcut key can be assigned to only one
menu item.
260 Centre for Information Technology and Engineering, Manonmaniam Sundaranar University
Menus
Check Box Menu items that simply set or clear a single program option
should contain a checked feature directly in the menu.
• Name This is the name used to refer the menu control from code.
• Caption This is the text that appears on the control.
• Index This is to create an array of menu commands
• Checked Checked to indicate that they are on or unchecked to
indicate that they are off.
Centre for Information Technology and Engineering, Manonmaniam Sundaranar University 261
Advanced Visual Basic
In the Caption text box, type the text for the first menu title that has to appear on
the menu bar. Also, place an ampersand (&) before the letter to assign the access
key for that menu item. This letter will automatically be underlined in the menu.
The menu title text is displayed in the menu control list box.
In the Name text box, type the name that will be used to refer to the menu control
in code.
Click the left arrow or right arrow buttons to change the indentation level of the
control.
Dropdown the menu and click on one of its item. The code window for its click
event procedure will appear, which is something like in the following:
262 Centre for Information Technology and Engineering, Manonmaniam Sundaranar University
Menus
In the Menu Editor window add a menu option and set its Index property to 0. You
can then add commands with the same name and consecutive Index values. At
design time, you don’t have to add more than one option. One command with its
Index property set to 0 is adequate to create the menu control array. You can use this
array’s name and an Index value to add new options at runtime.
Figure shows the RTMenu application, which demonstrates how to add to and
remove items from a menu at runtime.
Centre for Information Technology and Engineering, Manonmaniam Sundaranar University 263
Advanced Visual Basic
The two buttons at the bottom of the Form add commands to and remove commands
from the Run Time Menu. Each new command is appended at the end of the menu,
and the commands are removed from the bottom of the menu( the most recently
added commands).
A pop-up menu is a floating menu that is displayed over a form, independent of the
menu bar. The items displayed on the pop-up menu depend on where the pointer is
located when the right mouse button is pressed; therefore, pop-up menus are also
called context menus. Pop-up menus provide an efficient method for accessing
common, contextual commands. For example, if the right mouse button is clicked in
a text box, a contextual menu would appear, as in Figure 16.4.
Only the first argument is required, and it is the menu’s name, as specified in the
Menu Editor window. The other arguments are optional. The x and y arguments are
the coordinates of a point on the Form (or control) where the menu will be displayed.
The flags argument defines the location behavior of a Pop-up menu and can have one
of the values shown in Table 16.1.
264 Centre for Information Technology and Engineering, Manonmaniam Sundaranar University
Menus
The following code displays a popup menu named mnuFile with its top border
centered on the form when the user clicks the form with the right mouse button.
End Sub
Note : To create a menu that will not display on the menu bar, its top-level menu item’s
Visible property is to be unchecked at design time. When Visual Basic displays it
as a pop-up menu, its Visible property is ignored.
The boldcommand argument is used to specify the name of a menu control in the
displayed pop-up menu, to appear in bold to emphasize the most frequently used
menu item. For example, assume that there is a menu named as mnuMenu and one
of its items is Explore named as itmExplore. The following PopupMenu statement.
Popupmenu mnuMenu , , , , itmExplore
) A menu control array is a set of menu items that share the same name and event
procedure.
Centre for Information Technology and Engineering, Manonmaniam Sundaranar University 265
Advanced Visual Basic
1. Define Menu
1
1. Open a new standard EXE project
3. On clicking the ADD button Item should be added on the file menu
266 Centre for Information Technology and Engineering, Manonmaniam Sundaranar University
DDE & ActiveX Controls
Lecture - 17
Objectives
Centre for Information Technology and Engineering, Manonmaniam Sundaranar University 267
Advanced Visual Basic
Lecture Unit - 17
268 Centre for Information Technology and Engineering, Manonmaniam Sundaranar University
DDE & ActiveX Controls
Programmers are not historians. They don’t like to read lengthy histories
about a specific technology; they just want to learn how to use it. But when
talking about a specific technology As all-encompassing as Active X,
knowing a little about its previous history is a must. Before you can
understand where Active X is going , you first need to know where it came
from.
ActiveX can trace its roots all the way back to Dynamic Data Exchange (DDE), a way
of passing data and commands between applications. Though DDE is still supported
by Visual Basic to maintain backward compatibility, it is seldom used.
Out of DDE evolved OLE1.0, Object Linking Embedding. True to its name, OLE
brought the ability to link Objects to one another or to embed one object inside
another. The classic example of using OLE is the word processor/spreadsheet
combination. A reference to a spreadsheet file can be added to a word processing
document. If the user was to click on the reference , the spreadsheet program that is
used to edit the spreadsheet would be automatically loaded and changes could be
made. In this way , the spreadsheet is linked to the word processing document. With
OLE, the spreadsheet can also be embedded into the word processing document. A
window that shows the contents of the spreadsheet would be contained within the
document. Changes to the spreadsheet can then be made inside that window. The
spreadsheet program is still used to make the changes, but this is transparent to the
user. He or She never has to leave the word processor to make changes to the
spreadsheet.
DDE and OLE1.0 are technologies that were designed to change the way we use
computers. They bridged the gab between application-centric use and data-centric
use. In application-centric Computing, to work on a certain kind of file(such as word
processing document , a graphic image, or a spreadsheet), you would call up
Centre for Information Technology and Engineering, Manonmaniam Sundaranar University 269
Advanced Visual Basic
whichever program was used to edit that kind of [Link] work on a word processing
document, you need only click on the document itself. The operating system then
determines which application is associated with that file type and loads it, along with
the document .
Although the concept of data-centric computing sounds like it does nothing more
than make things easier for the user, it goes far beyond that. It also facilitates the
embedding of different object types within other objects. A web browser , for
example , can display an HTML document that contains many different object types:
images , sounds, videos, animation, and others. If the web browser does not natively
support the object type , the external program (typically, a “plug-in” for Netscape
browsers or an ActiveX control in Internet Explorer) that is associated with the
object type can be used to display the object within the page. Again , this is
transparent to the user.
After that OLE2.0 and COM and DCOM came to the world of computer era.
With this technique, you can insert an object from one application (the server
application) into Another application (the container application). The inserted object
is a copy of the original and can be manipulated and stored separately and apart
from the original object. For example, you can embed a range of cells from an Excel
worksheet in a Word document. To edit the cells , you switch to Excel by double-
clicking the embedded Excel object. If the container application supports in-place
editing, you’ll see the menus of the server application right in the container
application.
This technique is similar to embedding, except that the embedded data are also
linked to the document form which they come. Changes to the object in the server
application are reflected automatically in the container application. Linking doesn’t
store the object, it makes a reference to the object exposed by the server application.
Each time you open the document that contains the linked object exposed, the
container application contacts the server application, which actually opens the most
up-to-date version of the linked object. Linked objects are not copies. They are the
originals, viewed form within different containers.
270 Centre for Information Technology and Engineering, Manonmaniam Sundaranar University
DDE & ActiveX Controls
OLE objects are used in container applications. As Figure-17.1 illustrates, Excel ( the
OLE server) can expose a worksheet (the OLE object) that can be inserted as is in a
Word document ( the container application).
Centre for Information Technology and Engineering, Manonmaniam Sundaranar University 271
Advanced Visual Basic
The simplest way to create the user interface of an ActiveX control is to use controls
that already exist. This is known as creating from constituent [Link] illustrate
the techniques for creating a control, we are going to create a simple Security
control that allows the user to enter a userID and password. If you handle logins for
your applications, or have to pass user information to a database, you at some time
have had to ask for a userID and password. Typically, you place a couple of labels
and text boxes on a form and do a little bit of text processing. This is a simple enough
task, but wouldn’t it be nice if all you had to do was draw a single control on the
form, then access its properties to get all the needed information? This is what the
Security control does
2. Click the ActiveX Control icon. Visual Basic creates a new project that contains a
UserControl, named UserControl1 as shown in Fig-17.2 . This is the control’s
Form on which the visible interface will be built.(Once the project is created, you
will need to set the Name property of the control otherwise your control will go
through life with the generic name User Control1( or 2 and so on).
3. Click the control from the toolbox and place it on the UserControl1.
4. Set the basic properties of the control ( name or the caption property for a label or
command button
After you have finished developing and resting your control, you can use the control
in many programs. You can easily use the control in any other VB program that you
write. You can also use the control in any application that supports ActiveX controls.
272 Centre for Information Technology and Engineering, Manonmaniam Sundaranar University
DDE & ActiveX Controls
These applications include Microsoft Office, other development tools such as FoxPro,
and even Internet applications or web pages that support ActiveX. With this type of
usage available, you can see why the capability to create ActiveX control is such a
powerful feature in VB.
The first step to being able to use your control in other application is to complete it.
When you compile a control, you are creating an OCX file that can be accessed by
other programs. Compiling your control involves the following steps:
1. Select the project in your project group that contains the control.
2. Select the Make OCX item from Visual Basic’s File menu.
3. From the Make Project dialog box, click the Options button to set any necessary
compilation options.
4. In the Make Project dialog box set the name and path for the OCX file.
6. When the process is finished, your will have an OCX file that others can use to
access your control.
To use your ActiveX control in other Visual Basic programs, you have two options:
Using the OCX for the control is the preferred method of accessing the control
unless you are going to modify the control. Even then, you are better off modifying
the original control project and recompiling the control than making modifications
in anew project. To add your OCX control to your Visual Basic toolbox, open the
Components dialog box by pressing Ctrl+T. Then click the Browse button in the
dialog to bring up the Open dialog that allows you to specify the name and path of
the control. When you select the control, it will appear in the Components dialog
and will be marked to be added to your toolbox. After closing the Components
dialog, your control will appear in the Toolbox and will be accessible to the current
project, like any other control.
Internet Explorer 3.0 and 4.0, as well as some other Internet programs, are capable of
displaying and using Active X controls. The key to using the control is the use of the
Centre for Information Technology and Engineering, Manonmaniam Sundaranar University 273
Advanced Visual Basic
<object> tag in the HTML code for the web page. The <object> tag specifies the
following information about the control:
• The controls’s ID
• A name for the instance of the control
• The ClassID of the control
This information identifies the control to your web browser and allows the control to
be displayed if the browser supports ActiveX. The Following code shows one
instance of the HTML code needed to embed an ActiveX control in a page:
Web page designers make it easy to add ActiveX controls to your pages. These
designers handle all the object information for you so you don’t have to remember all
the details about ClassIDs and the other information.
Once you have created the Active X control, you need to test it to make sure that all
the procedures work as you think thy should. You can use all the standard
debugging techniques that are available in VB to debug your control. There are only
a few different steps involved in setting up a test for your ActiveX control.
2. Close the User Control window of your control project. If the User – Control
(form) window is open, Visual Basic assumes that you are still working on the
design of the control and will not allow you to create an instance of the control
in another form
3. Create an instance of the control on your test form. Then you can test the
properties of the control and write code to test its methods
274 Centre for Information Technology and Engineering, Manonmaniam Sundaranar University
DDE & ActiveX Controls
applications and enables the user to edit that data from within the application
in which it was created.
) The OLE control allows adding objects from other applications and it can have
only one object at a time.
1. MDI Form
Open a new project. Add a MDI form along with two forms. Set the child
Property of forms and provide a way (MENU) to access the two forms from the
MDI form.
Centre for Information Technology and Engineering, Manonmaniam Sundaranar University 275
Advanced Visual Basic
Define two containers (picture box, frame) and three controls (command button,
Checkbox, picture box). Set the drag drop mode to automatic. Drag and drop the
controls to different containers. Provide drag icons. Set the Dragover Effect when
a control is dragged over a container.
4. Image List:
Place a Image List on the form and insert some pictures to the Image List Control. Give
appropriate key value from the pictures.
5. Status Bar
Place a status bar control in the MDI FORM. Add panels to the status bar. The status bar
should display the time, date in separate panels. Also display the message in any of the
panels whenever a text is dragged from one text box and Dropped into another text box.
When a new form is opened display its name in any one of the panels of the status bar.
6. Tool Bar:
• Place a toolbar control on the form2. Add buttons to the toolbar as shown below.
Set the Image index for each and every button.
• When the first button is pressed the text in the “Text1” must be displayed in Bold
format
• When the second button is pressed the text in the “Text1” must be displayed in
“Italic” format
• When the third button is pressed the text in the “Text1” must be Underlined
• When a number is selected from the combo1 the font size of the text box must
changed according to the value selected
• When the last button is selected, the form “Form1” must be closed.
276 Centre for Information Technology and Engineering, Manonmaniam Sundaranar University
ActiveX Controls
Lecture - 18
ActiveX Controls
Objectives
Centre for Information Technology and Engineering, Manonmaniam Sundaranar University 277
Advanced Visual Basic
Lecture Unit - 18
278 Centre for Information Technology and Engineering, Manonmaniam Sundaranar University
ActiveX Controls
ActiveX documents are designed the same way as the Visual Basic Forms are
designed. That is, they can have intrinsic controls and ActiveX controls as the
normal Visual Basic Forms have. They can also show message boxes and secondary
Forms. But, in contrast to the independent appearance of the Visual Basic Forms,
ActiveX documents appear in containers, i.e Internet Browser windows such as
Internet Explorer, Netscape Navigator, etc. With Internet Explorer 3.0 or later,
ActiveX document can be saved and read by writing to and reading from the
document's data file.
The base object of an ActiveX document is the UserDocument object that resembles a
Standard Visual Basic Form object with some exceptions.
The UserDocument object has most, but not all, of the events that are found on a
Form object. The events present on a Form that are not found on the UserDocument
include:
Activate
Deactivate
Load
QueryUnload
Unload
Events present on the UserDocument, but not found on a Form object include:
EnterFocus
ExitFocus
Hide
InitProperties
ReadProperties
Scroll
Show
WriteProperties
Hyperlink Objects
Centre for Information Technology and Engineering, Manonmaniam Sundaranar University 279
Advanced Visual Basic
NavigateTo
GoBack
GoForward
This method makes a hyperlink jump to the specified target. For example, the
following code presumes an ActiveX document named "axdMyDoc" exists:
[Link] "c:\mydocs\[Link]"
The above code will cause the appearance of the axdmydoc in the web browser.
Note : Actually ActiveX documents are stored with the extension .dob. But time
being, assume that they are stored with the extension .vbd. Explanation
about this is given shortly.
When the ActiveX documents are viewed in a Web browser, the browser maintains
the list of viewed documents i.e history of documents. The GoBack and GoForward
methods enable to go backwards or forwards through the list. For example, an
ActiveX document ActXDoc1 is viewed first and an another ActiveX Document
ActXDoc2 is currently being viewed. Issuing GoBack method here will enable to
revisit to the ActXDoc1. Once GoBack method is called, the document from which
the GoBack method is called will be added in the Forward list. Issuing GoFoward
method will enable to revisit to that document - in this case ActXDoc2. However, if
there is no documents in the Backward and Forward list, then issuing either GoBack
or GoForward will cause errors. So error-trapping can be enabled as given in the
following example:
Example:
[Link]
--- or ---
[Link]
280 Centre for Information Technology and Engineering, Manonmaniam Sundaranar University
ActiveX Controls
Exit Sub
noDocInHistory:
Resume Next
End Sub
Choose File | New Project to open the New Project dialog box.
Note : The ActiveX Document Dll project type will package the ActiveX
documents as in-process component. To package it as out-of-process
component use ActiveX Document EXE project type.
Centre for Information Technology and Engineering, Manonmaniam Sundaranar University 281
Advanced Visual Basic
The text box in the ActXDoc1 will accept a name of a User Document with full path
such as ..\ActXDoc\[Link]. Clicking Navigate To button will cause a jump
to the document specified in the text box. Clicking the Show Form will display the
frmAddress Form, which will also accept address to Jump To. When the Form is
closed, the address in the txtAddress text box will be replaced by the address entered
in the text box of the Form frmAddress.
[Link] vbModal
It is necessary to activate the Form in modal mode. Because some web browsers
such as Internet Explorer, don't support the showing of modeless forms called from
within a DLL. However, if the documents are compiled as out-of-process component,
Internet Explorer is capable of showing both modal and modeless forms.
282 Centre for Information Technology and Engineering, Manonmaniam Sundaranar University
ActiveX Controls
Note: A project started as ActiveX DLL can be converted to ActiveX EXE and
can be packaged as out-of-process component by simply changing the
Project type from ActiveX DLL to ActiveX EXE in the Project Properties
window.
Create objects and set their properties in the Form frmAddress as given
below:
The reason to change the Control Box property of the frmAddress Form is
that the Form can be closed only by clicking the Close button. The Close
button’s click event procedure has the following line:
[Link]
That is, the Close button simply hides the Form from the vision. It doesn’t
unload it from the memory so that the ActXDoc1 can replace the text of the
txtAddress text box with the newly entered text in the text box of the Form
using the following line.
[Link] = [Link]
Centre for Information Technology and Engineering, Manonmaniam Sundaranar University 283
Advanced Visual Basic
If the Form is closed through the control box, then it will be removed from the
memory and the ActXDoc1 can’t access the text entered in the txtcomAddress
text box. So only, the Control Box property is set to False.
Create objects and set their properties in the User Document ActXDoc2 as
given below:
Clicking Go Back button will enable to revisit to the previously visited Document,
say ActXDoc1. Clicking the Go Next button will display the next document i.e.,
ActXDoc3. If the ActXDoc2 is visited using Go Back from another document, then
alone clicking Go Forward will display that document. Otherwise it won’t work.
Create objects and set their properties in the User Document ActXDoc3 as given
in the following:
284 Centre for Information Technology and Engineering, Manonmaniam Sundaranar University
ActiveX Controls
The Name text box change event procedure has the PropertyChanged statement as in
below:
This causes the Web Browser to prompt the user to save changes. If the user
responds positively, the code writes the property value to the PropertyBag using
WriteProperties event, whose code is given below.
Centre for Information Technology and Engineering, Manonmaniam Sundaranar University 285
Advanced Visual Basic
Option Explicit
Private Sub cmdNavigate_Click()
InvalidAddress:
286 Centre for Information Technology and Engineering, Manonmaniam Sundaranar University
ActiveX Controls
End Sub
Add the following code to the ActXDoc2 User Document.
Option Explicit
Private Sub cmdGoBack_Click()
On Error GoTo noDocInHistory
noDocInHistory:
End Sub
noDocInHistory:
MsgBox "No document in History - Can't go Forward"
Resume Next
End Sub
Private Sub cmdGoNext_Click()
'Jumping to the ActXDoc3
Hyperlink.NavigateTo_
"C:\Raguram\VBasic\ActXDoc\[Link]"
Centre for Information Technology and Engineering, Manonmaniam Sundaranar University 287
Advanced Visual Basic
End Sub
Option Explicit
noDocInHistory:
End Sub
288 Centre for Information Technology and Engineering, Manonmaniam Sundaranar University
ActiveX Controls
Choose File | Save Project to save the project files. Name them as given
below. Visual Basic will provide the indicated extensions automatically. (Save
them in a separate folder, say ActXDoc).
After you have finished testing and debugging your document, you are ready to
compile the document for distribution. To start the compilation process, select the
Make [Link] menu option form the File menu of VB. This will then open the
Make project dialog box, prompting you to supply a name and location for the EXE
or DLL file. The name of the .vbd file is based on the Name property of the
UserDocument object. This file is placed in the same folder that you specified for the
EXE file. After you have compiled the ActiveX Document, you can view it in any
container program that handles ActiveX documents. Internet Explorer and Office
Binder are two such programs. At the time this book is being written, Netscape
Navigator 4.0 does not support ActiveX documents. It is already mentioned that
ActiveX Documents can be built as either in-process or out-of-process component. In
Centre for Information Technology and Engineering, Manonmaniam Sundaranar University 289
Advanced Visual Basic
both cases, when the project is compiled, in addition to creating an .exe. or a .dll file,
Visual Basic creates a Visual Basic Document file (Figure 18.5), which has the
extension .vbd and it is placed in the same directory as the compiled component (.exe
or .dll).
The .vbd file is actually an OLE structured storage — this basically means that data
in the file can be accessed and manipulated via standard OLE interfaces. The Internet
Explorer uses this interface. So only instead of specifying .dob files .vbd files are
mentioned while calling the NavigateTo method of hyperlink object to open another
document.
Figure 18.5 Compiling User Documents produces .exe (or .dll) and .vbd files.
To begin the conversion process, the project whose forms you want to convert must
be open. After you have opened the project, launch the ActiveX Document Migration
Wizard. At this point you will be presented with a series of screens that will guide
you through the conversion process. The first of these screens is introductory only, so
click the Next button to continue.
The second screen of the Wizard, shown in Fig 18.6 includes a list box from which
you can select the forms that you would like to convert. Any forms that have been
290 Centre for Information Technology and Engineering, Manonmaniam Sundaranar University
ActiveX Controls
defined for this project will be displayed in this list box. To select forms, simply click
in the check box next to the name of the form. When you have made all your
selections, click the Next button to continue.
Figure 18.6 - You can select multiple forms in the list box
The Options page of the ActiveX Document Migration Wizard, shown in Figure 18.7
, lets you control how the Wizard will process the forms your have selected. The
three options enable you to do the
following:
Figure 18.7– Select the options that are appropriate to your needs
• Choose to comment out invalid code. This option will comment out statements
such as Load,Unload,or End that are not supported by ActiveX documents.
• Remove original forms after conversion. This option will remove the forms from
the current project after the conversion is made. Typically, you will not want to
check this option because you will want your original project intact.
• Choose whether to convert your project to an ActiveX EXE or ActiveX DLL
project. The option defaults to ActiveX EXE. (ActiveX DLL are used for creating
shared components rather than applications)
Centre for Information Technology and Engineering, Manonmaniam Sundaranar University 291
Advanced Visual Basic
After making your choices, click the Next button to continue. The last page of the
Wizard allows you to view a summary report that describes the Wizard’s actions.
After making your selection, click the Finish button to begin the conversion. The
summary report is a valuable development tool because it provides you with
information regarding the steps you need to complete. Figure 18.8 shows the
summary report.
When the Active X Document Migration Wizard has finished its work, it places the
newly created UserDocument objects in the same project as the original forms. The
document source files are stored in the same folder as the original form files and are
given similar names, with the appropriate extension. For example, a form stored in
the file [Link] creates a UserDocument stored in the file [Link]. As
previously stated, the controls of the form are copied to the UserDocument and their
relative positions are preserved.
Also, as stated previously, most of the code from your original form is copied over to
the UserDocument. Invalid code is commented out and identified by the ActiveX
Document Migration Wizard.(This assumes that you choose to comment out invalid
code on the Option page of the Wizard.)
292 Centre for Information Technology and Engineering, Manonmaniam Sundaranar University
ActiveX Controls
1. What are the uses of ActiveX components. Explain the areas in which it is
using.
1. Open a new project in Visual Basic and select the ActiveX documentEXE
2. Click the UserDocument1 in the Project window and name it as travreq
Centre for Information Technology and Engineering, Manonmaniam Sundaranar University 293
Advanced Visual Basic
Lecture - 19
Data Project
Objectives
About registry
294 Centre for Information Technology and Engineering, Manonmaniam Sundaranar University
Data Project
Lecture Unit - 19
19.4 Registry
Centre for Information Technology and Engineering, Manonmaniam Sundaranar University 295
Advanced Visual Basic
In Microsoft Visual Basic, database projects are not used. You can use the Data
Project template to create a new project, which adds default controls and objects,
including the data environment. To use the Visual Database Tools in Visual Basic,
you can either add a data connection to the data environment, or make a data
connection directly from the Data View window. Also, in Visual Basic, all data
connections are made through OLE DB, although you can still use ODBC data source
names (DSNs) to define your connections.
In Microsoft Visual Basic you can either add a data connection to the data
environment, or make a data connection directly from the Data View window. In
Visual Basic, all data connections are made through OLE DB, although you can still
use ODBC data source names (DSNs) to define your connections.
To see the new visual database tools in action, start a new project, and in the Project
type dialog box, select Data Project.A Data project is not a special project type. It’s
basically a Standard EXE project, but Visual Basic loads all the database tools into the
project’s Toolbox.
In the Project Explorer window, Visual Basic display a new form, as usual, and two
ActiveX Designers. A Designer is a special add –in that simplifies the design of
components. Database applications rely on two basic components:
• The ADODC (ADO Data control), which is equivalent to the Data control
• The DataList and DataCombo controls, which are data-bound versions of the
ListBox and ComboBox contorls; they work with the ADO Data control (but
not with the Data control)
296 Centre for Information Technology and Engineering, Manonmaniam Sundaranar University
Data Project
To access a database with ADO ( or any other data tool), you need two types of
objects:
A combination of features that allows the user to drag an item and drop it into
another item using the mouse. An item can be a source (the item the user drags) or a
target (the item on which the user drops a source).
A feature that enables you to drag one object onto another to perform an action. To
drag an object, click the object and, while holding down the mouse button, move it to
the new location. When you are satisfied with the location, release the mouse button
to drop the object.
Centre for Information Technology and Engineering, Manonmaniam Sundaranar University 297
Advanced Visual Basic
When you design Visual Basic applications, you often drag controls around on the
form. The drag-and-drop features in Visual Basic allow you to extend this ability to
the user at run time. The action of holding a mouse button down and moving a
control is called dragging, and the action of releasing the button is called dropping.
Note Dragging a control at run time doesn't automatically change its location
— you must program the relocation yourself, as described in "Changing
the Position of a Control." Often, dragging is used only to indicate that
some action should be performed; the control retains its original position
after the user releases the mouse button.
Using the following drag-and-drop properties, events, and method, you can specify
both the meaning of a drag operation and how dragging can be initiated (if at all) for
a given control.
All controls except menus, timers, lines, and shapes support the DragMode and
DragIcon properties and the Drag method. Forms recognize the DragDrop and
DragOver events, but they don't support the DragMode and DragIcon properties or
the Drag method.
Note : Controls can only be dragged when they do not have the focus. To prevent
a control from getting the focus, set its TabStop property to False.
19.4 Registry
298 Centre for Information Technology and Engineering, Manonmaniam Sundaranar University
Data Project
Registry Properties
PropertyDescription
Application
Application
Write: NoThe Application [Link]
Boolean
Write: YesDetermines if license logging is started automatically when SQL Server
starts. If True, licensing is started automatically when SQL Server starts. If False,
licensing must be started [Link]
Boolean
Write: YesDetermines if Mail is started when SQL Server starts. If True, Mail is
started automatically when SQL Server starts. If False, Mail must be started
[Link]
Boolean
Write: YesDetermines if SQL Server is started when Windows NT starts. If True, SQL
Server is started automatically when Windows NT starts. If False, SQL Server must
be started [Link]
Boolean
Write: NoIndicates if SQL Server is case-sensitive. If True, SQL Server is using a case-
sensitive sort order. If False, SQL Server is using a case-insensitive sort
[Link]
String
Write: NoDescription of the character set and code page used by SQL
[Link]
String
Write: YesThe full path and file name of the SQL Server error [Link]
String
Write: YesThe Mail account [Link]
String
Write: YesThe password for the Mail account specified by the MailAccountName
[Link]
String
Write: YesThe full path and file name of the database device that contains the
MASTER [Link]
Boolean
Write: NoIndicates if Windows NT event logging is enabled. If True, SQL Server
sends all events to the Windows NT event log as well as the SQL Server error log. If
False, SQL Server sends events only to the SQL Server error
[Link]
Long
Centre for Information Technology and Engineering, Manonmaniam Sundaranar University 299
Advanced Visual Basic
Before diving into using API procedures this section discusses the fundamental
elements of API procedures.
API procedures are contained in DLLs. So applications can link and use them at run
time rather than to link statically at compile time. This means that the libraries can be
updated independently of the application, and many applications can share a single
DLL. Microsoft Windows itself is comprised of DLLs, and other applications call the
procedures within these libraries to display windows and graphics, manage
memory, or perform other tasks.
300 Centre for Information Technology and Engineering, Manonmaniam Sundaranar University
Data Project
The four functional categories of the Windows API procedures (as these procedures
are used in Windows 32 bit environment, they can be abbreviated as Win32 API) are
as follows:
System Services provides procedures to access the resources of the computer such as
disk, and the operating system.
Multimedia provides procedures to play waveform audio, MIDI music, and digital video.
You can gain access to the Windows API (or other outside DLLs) by declaring the
external procedures within your Visual Basic application. After you declare a
procedure, you can use it like any other language feature in the product.
The most commonly used set of external procedures are those that make up
Microsoft Windows itself. The Windows API contains thousands of functions, subs,
types, and constants that you can declare and use in your projects. These procedures
are written in the C language, however, so they must be declared before you can use
them with Visual Basic. The declarations for DLL procedures can become fairly
complex. While you can translate these yourself, the easiest way to access the
Windows API is by using the predefined declares included with Visual Basic.
The file [Link], located in the \Winapi subdirectory of the main Visual Basic
directory, contains declarations for many of the Windows API procedures commonly
used in Visual Basic. To use a function, type, or other feature from this file, simply
copy it to your Visual Basic module. You can view and copy procedures from
Centre for Information Technology and Engineering, Manonmaniam Sundaranar University 301
Advanced Visual Basic
[Link] by using the API Viewer application, or by loading the file in any text
editor.
Note The Windows API contains a vast amount of code. To find reference
information on the procedures and other details included in this API set, refer to the
Win32 SDK, included on the Microsoft Developer Network Library CD.
The API Viewer application enables you to browse through the declares, constants,
and types included in any text file or Microsoft Jet database. After you find the
procedure you want, you can copy the code to the Clipboard and paste it into your
Visual Basic application. You can add as many procedures as you want to your
application.
The API Viewer application
To view an API file
1. From the Add-Ins menu, open the Add-In Manager and load API Viewer.
2. Click API Viewer from the Add-Ins menu.
3. Open the text or database file you want to view.
• To load a text file into the viewer, click File \ Load Text File and choose the
file you want to view.
• To load a database file, click File \ Load Database File.
4. Select the type of item you want to view from the API Types list.
Note You can have the API Viewer automatically display the last file you viewed in
it, when it is opened, by selecting View \ Load Last File.
1. Click the procedure you want to copy in the Available Items list.
2. Click Add. The item appears in the Selected Items list.
3. Indicate the scope of the item by clicking Public or Private in the Declare Scope
group.
4. To remove an entry from the Selected Items list box, click the item and click
Remove.
5. To remove all entries from the Selected Items list box, click Clear.
302 Centre for Information Technology and Engineering, Manonmaniam Sundaranar University
Data Project
1. Click Copy. All of the items in the Selected Items list will be copied.
2. Open your Visual Basic project and go to the module in which you want to place
the API information.
3. Position the insertion point where you want to paste the declarations, constants,
and/or types, and then choose Edit \ Paste.
To optimize speed, you can convert the [Link] file into a Jet database file,
because it is much faster to display the list when opening a database than when
opening a text file.
To convert a text file to a jet database file
1. Start the API Viewer application.
2. Click File \ Load Text File and open the .txt file you want to convert.
3. Click File \ Convert Text to Database.
4. Choose the file name and location for your database file, then click OK.
You can specify a text or database file on the command line for [Link] so that
the file is automatically loaded when you start API Viewer. Use the following syntax
to load the file you choose when you start the API Viewer application:
Tip You can view a prompt that shows the parameters of the command line syntax
by using a DOS window to navigate to the directory in which the API viewer
application is installed, then typing apiload /?.
You can also load the [Link] file in a text editor, such as Microsoft Word or
WordPad, to locate the procedures you want to use. Again, you just copy the
procedures from the file to a Visual Basic module to use them in your application.
Centre for Information Technology and Engineering, Manonmaniam Sundaranar University 303
Advanced Visual Basic
Tip Don't load the [Link] file into a module. This is a large file, and it will
consume a lot of memory in your application. You will generally use only a handful
of declarations in your code, so selectively copying the declarations you need is
much more efficient.
If you are attempting to call a procedure in a DLL that is not part of the operating
system, you must determine the proper declaration for it. The topic "Declaring a DLL
Procedure" explains the syntax of the Declare statement in detail.
Note If you use Visual C++ (or a similar tool) to create DLLs that will be called by
Visual Basic, use the __stdcall calling convention. Do not use the default calling
convention (_cdecl).
) In Visual Basic, all data connections are made through OLE DB, although you
can still use ODBC data source names (DSNs) to define your connections
) Dragging a control at run time doesn’t automatically change its location –--
you must program the relocation yourself, as described in “Changing the
position of a control”. Often,
) Dragging is used only to indicate that some action should be performed; the
control retains its original position after the user releases the mouse button.
) Note You can have the API Viewer automatically display the last file you
viewed in it, when it is opened, by selecting View \ Load Last File.
) Controls can only be dragged when they do not have the focus. To prevent a
control from getting the focus, set its TabStop property to False.
) By specifying a text or database file on the command line for [Link] so
that the file is automatically loaded when you start API Viewer.
Create a Data Project using NWIND ( which is in the VB98 folder) database
304 Centre for Information Technology and Engineering, Manonmaniam Sundaranar University
Dynamic Link Library
Lecture - 20
Objectives
Centre for Information Technology and Engineering, Manonmaniam Sundaranar University 305
Advanced Visual Basic
Lecture Unit - 20
306 Centre for Information Technology and Engineering, Manonmaniam Sundaranar University
Dynamic Link Library
Dynamic-link libraries (DLL) are modules that contain functions and data. A DLL is
loaded at runtime by its calling modules (.EXE or DLL). When a DLL is loaded, it is
mapped into the address space of the calling process. (DLL) A file with the file name
extension .dll that contains one or more functions compiled, linked, and stored
separately from the computing processes that use them.
DLLs can define two kinds of functions: exported and internal. The exported
functions can be called by other modules. Internal functions can only be called from
within the DLL where they are defined. Although DLLs can export data, its data is
usually only used by its functions.
A Windows term for a set of routines that can be called from procedures and are
loaded and linked into your application at run time. DLLs include utility routines or
specific functions not intrinsic to Microsoft Windows. _DLLDefined when /MD or
/MDd (Multithread DLL) is specified. /MD, /ML, /MT, /LD (Use Run-Time
Library)
With these options, you can select either single-threaded or multithreaded run-time
routines, indicate that a multithreaded module is a dynamic-link library (DLL), and
select the retail or debug version of the library.
Note : Having more than one copy of the run-time libraries in a process can cause
problems, because static data in one copy is not shared with the other copy. To
ensure that your process contains only one copy, avoid mixing static and dynamic
versions of the run-time libraries. The linker will prevent you from linking with
both static and dynamic versions within one .EXE file, but you can still end up
with two (or more) copies of the run-time libraries. For example, a dynamic-link
library linked with the static (non-DLL) versions of the run-time libraries can cause
problems when used with an .EXE file that was linked with the dynamic (DLL)
version of the run-time libraries. (You should also avoid mixing the debug and
non-debug versions of the libraries in one process.)
Centre for Information Technology and Engineering, Manonmaniam Sundaranar University 307
Advanced Visual Basic
are selected from the standard .H files. This option also causes the compiler to place
the library name [Link] into the .OBJ file.
Applications compiled with this option are statically linked to [Link]. This
library provides a layer of code that allows the linker to resolve external references.
The actual working code is contained in [Link], which must be available at
run time to applications linked
Creates an import library (.LIB), if an export (.EXP) file is not specified on the
command line; you link the import library to applications that call your DLL.
Interprets /Fe as naming a DLL rather than an .EXE file; the default program name
becomes [Link] instead of [Link].
Changes default run-time library support to /MT if you have not explicitly specified
one of the /M options/LDdNot applicableCreates a debug DLL. Defines _DEBUG.
308 Centre for Information Technology and Engineering, Manonmaniam Sundaranar University
Dynamic Link Library
The debug options select the debug versions of the library or DLL and define
_DEBUG. For more information on using the debug versions, see C Run-Time Debug
Libraries.
• Saves memory and reduces swapping. Many processes can use a single DLL
simultaneously, sharing a single copy of the DLL in memory. In contrast,
Windows must load a copy of the library code into memory for each application
that is built with a static link library.
• Saves disk space. Many applications can share a single copy of the DLL on disk.
In contrast, each application built with a static link library has the library code
linked into its executable image as a separate copy.
• Upgrades to the DLL are easier. When the functions in a DLL change, the
applications that use them do not need to be recompiled or relinked as long as
the functions' arguments and return values do not change. In contrast, statically
linked object code requires that the application be relinked when the functions
change.
• Provides a mechanism to extend the MFC library classes. You can derive classes
from the existing MFC classes and place them in an MFC extension DLL for use
by MFC applications.
Centre for Information Technology and Engineering, Manonmaniam Sundaranar University 309
Advanced Visual Basic
strings for each language version of your application in a separate resource DLL,
and have the different language versions load the appropriate resources.
After the function is declared, it can be called just as a standard Visual Basic
function. Here, the statement to call SetWindowText is attached the Form
Load event:
When this code is run, the function first uses the hWnd property to identify
the window whose caption is to be changed ([Link]), then changes the
text of that caption to "Extending Visual Basic "
Note : Visual Basic can’t verify the arguments that are passed to a DLL procedure.
If incorrect values are passed, the procedure may fail, which may cause
Visual Basic application to stop. So, care should be taken while
experimenting with DLL procedures.
The only difference between Visual Basic procedures and the Win32 API procedures
is that API procedures must be declared before they can be used. Because the Win32
API procedures (DLL procedures) reside in files that are external to Visual Basic
application they can’t be used without specifying their locations (DLL file name) and
their required arguments. The Win32 API procedures are contained mainly in three
Windows DLLs. They are:
Library Description
[Link] Library for user interface routines.
310 Centre for Information Technology and Engineering, Manonmaniam Sundaranar University
Dynamic Link Library
Once the Win32 API procedures are declared they can be used just like a native
Visual Basic procedure.
Syntax
Declare Function publicname Lib "libname" [Alias "alias"] [([[ByVal] variable [As type]
[,[ByVal] variable [As type]]...])] As Type
Declare Sub publicname Lib "libname" [Alias "alias"] [([[ByVal] variable [As type]
[,[ByVal] variable [As type]]...])]
Example
The Lib clause in the declaration statement specifies the name of the .dll file
that contains the function (In the above statement the .dll file name is USER32
Centre for Information Technology and Engineering, Manonmaniam Sundaranar University 311
Advanced Visual Basic
You can extend the native capabilities of Visual Basic by taking advantage of the
facilities of ActiveX controls (.ocx files), ActiveX objects, and dynamic-link libraries
(DLLs). External libraries allow you to access not only the capabilities of other
programs, but of Windows itself.
For example, you can use an ActiveX control to read and update the Windows
registry directly, or it can call system-level functions by linking to one of the DLLs in
Windows.
If the functionality you need isn't already available in an external library, you can
create your own ActiveX control with the Microsoft Visual Basic® Control Creation
Edition version 5.0.
If the functionality you require is available in a DLL, you can link to the library and
call its functions. Before calling a DLL function, you must determine its calling
protocol, including the name of the function, the number and data types of its
parameters, and the data type of its return value.
312 Centre for Information Technology and Engineering, Manonmaniam Sundaranar University
Dynamic Link Library
only the data it needed, instead of directly talking to the whole [Link] type of
application was sometimes referred to as two-tier architecture, because there were
two levels to the application: the GUI and the database. Cutting edge applications
are written as three-tired or n-tire applications.
The ability to build n-tier components — ActiveX EXEs and DLLs — is not new to
Visual Basic. What's new to Version 6.0 is the ability to tailor your components to run
in conjunction with Microsoft Transaction Server (MTS). Until Microsoft Transaction
Server, this typically meant writing server applications or using remote procedure
calls. There were no Microsoft Foundation Class Wizards to quickly whip up a
framework, and to get reasonable performance the server application developer had
to worry about thread and connection pooling.
Using the new MTSTransactionMode property of the class module, you can create
components that ignore MTS, or support transactions by setting a property. When
the component is not running in an MTS environment, the property is ignored.
COM objects
Business logic
Dumb Terminals
Client PCs Client PCs
Or Browser
Centre for Information Technology and Engineering, Manonmaniam Sundaranar University 313
Advanced Visual Basic
• Support for Transaction Active Server Pages – Scripts in Active Server Pages
can now executed within an MTS-managed transaction.
• Crash Protection for IIS Applications – IIS Web applications can now execute
with in their own MTS package, providing process isolation and crash
protection for Web application.
• Support for the XA transaction protocol, including native support for Oracle
To use Remote Data Service technology, you must understand the three-tiered
client/server model. This model separates the various components of a client/server
system into three "tiers":
314 Centre for Information Technology and Engineering, Manonmaniam Sundaranar University
Dynamic Link Library
• Client tier—a local computer on which either a Web browser displays a Web
page that can display and manipulate data from a remote data source, or (in non–
Web-based applications) a stand-alone compiled front-end application.
After you create your ActiveX DLL project, you need to register it with Transaction
Server before it can be used. You do this through the Transaction Server Explorer.
After you have started up the Transaction Server Explorer, you need to make sure
that the DTC is running. If the DTC is not running, click the Computer icon for your
computer and then choose Tools /MS DTC/Start
• Creating Packages
• Installing Components
• Calling Transaction Server Objects from Visual Basic
) DLLs can define two kinds of functions: exported and internal. The exported
functions can be called by other modules. Internal functions can only be called
from within the DLL where they are defined. Although DLLs can export data,
its data is usually only used by its functions.
Centre for Information Technology and Engineering, Manonmaniam Sundaranar University 315
Advanced Visual Basic
) The difference between VB procedures and the Win32 API procedures is that
API procedures must be declared before they can be used.
) Visual Basic can’t vaerify the arguments that are passed to a DLL procedure. If
incorrect values are passed the procedure may fail, which may cause Visual
Basic application to stop. So, care should be taken while experimenting with
DLL procedures.
) We can use an ActiveX control to read and update the Windows registry
directly, or it can call system-level functions by linking to one of the DLLs in
Windows.
316 Centre for Information Technology and Engineering, Manonmaniam Sundaranar University
Packages and Internet Information Server
Lecture - 21
Objectives
Centre for Information Technology and Engineering, Manonmaniam Sundaranar University 317
Advanced Visual Basic
Lecture Unit - 21
318 Centre for Information Technology and Engineering, Manonmaniam Sundaranar University
Packages and Internet Information Server
Before you can start registering components in Transaction Server, you must
know the concept package into which you are going to install the
components. Packages are logical groupings of objects that are generally used
as a unit. As a general rule, you will want to crate one package for each set of
applications that makes use of Transaction Server.
4. Type in a name for the package, as shown in Figure. For your catalog sales
company package, call it Inventory. Then click the Next button
5. If the objects in the package need to run under a specific login account,
select the This User radio button and provide the username and password.
Otherwise, leave the default radio button selected as in Figu, which runs
all of the objects in the package under the account of the user using the
applications that use the objects in this package. ( This can affect the
availability of resources for the process components, depending on how
the access privileges are configured in the system security.)
After you have a package, you can begin installing components into it. This is where
you register the ActiveX DLLs that you have and will be creating with Visual Basic
6. You can install your components by following these steps:
1. Select the Components folder in the package into which you want to install the
components, as seen in Fig
Centre for Information Technology and Engineering, Manonmaniam Sundaranar University 319
Advanced Visual Basic
3. Click the Add Files button and select the [Link] that you want to install, as
seen in Figure
4. When you return to the Install Components dialog box, the upper list box should
show the DLL that you are installing, and the lower list box should show all of
the visible classes within the DLL, as in Figure
5. Click the Finish button and the components are installed in Transaction server,
as seen in Figure.
6. Select the components you just installed, one at a time, and right-click the mouse.
Select Properties from the pop-up menu. On the component Properties Editor,
select the Transaction tab, and select the transaction attribute desired for the
currently selected component, as in Fig
Whenever you recompile any ActiveX DLL built in VB6, you need to refresh the
component information in Transaction Server. This can be easily done by deleting the
component from the Transaction Server Explorer and reinstalling the component by
following the same steps as were followed to install the component originally.
Another way of refreshing the component information in Transaction Server is
choosing Tools/Refresh All Components.
Now that you have a component built and registered with Transaction Server, how
do you call the method in this object form a Visual Basic application? First, the Visual
Basic application has to get a reference to the Transaction Server Object. After the
reference has been acquired, the object’s methods can be called. There are three ways
that a references to a Transaction Server Object can be acquired:
320 Centre for Information Technology and Engineering, Manonmaniam Sundaranar University
Packages and Internet Information Server
From a Visual Basic application, you can create your reference to your Inventory
Maintenance object with the following code:
From here, you can call the object methods by referencing them via the object you
have just created as so:
[Link](iiProductID,CLng([Link]),iBackOrder,iCurInventory)
If you build a simple little applet using the Remote Data Control and the Data Bound
Combo Box, you can call your object and see how Transaction Server works. The first
thing you need to do is to add the Remote Data Control and the Data Bound List
Controls to your Toolbox. You do this choosing Project/Components, as seen in Fig
21.1
Figure 21.1 - Include Remote Data Control & Data Bound List Controls in VB
project
With these controls, you can build a simple form that provides a drop-down list box,
containing the product descriptions from the Products table in the database. You
accomplish this binding the Remote Data Control to the ODBC configuration you
Centre for Information Technology and Engineering, Manonmaniam Sundaranar University 321
Advanced Visual Basic
have set up for your database, providing the username and password that you have
configured, and using the following SQL to populate the Remote Data Control:
Next, specify the Remote Data Control as the row source for the Data Bound Combo
Box and specify the Prd_Desc column as the ListField, and BoundColumn. Add a
text box in which the user can enter the number to add or remove from the inventory
and you have the form seen in Figure 21.2
Figure 21.2 – Form to call the method in the object you registered with
Transaction Server
When the user selects a product, you need to have a variable into which to place the
selected product ID, so declare a variable in the form declarations using the code in
the List
Option Explicit
You set the product ID into this variable whenever the user selects a product from
the list by navigating in the Remote Data Control to the currently selected row, and
then getting the Prd_ID column from that row, as in the List
322 Centre for Information Technology and Engineering, Manonmaniam Sundaranar University
Packages and Internet Information Server
[Link] – grabbing the product id from the remote data control when
the user selects a product
VarCurRecord = dbcProduct,SelectedItem
iiProductID = [Link]!Prd_ID.Value
End Sub
When the user clicks the Received button, you can create a reference to the
Transaction Server Object that you created by using the earlier code snippets, and
you can display for the user the resulting stock and back-order amounts with the
code in the list
Centre for Information Technology and Engineering, Manonmaniam Sundaranar University 323
Advanced Visual Basic
ProgID = “ [Link]”
Exit Sub
End If
iCurInventory) = -1 Then
[Link] ERROR_NUMBER
End If
+ Str$(iCurInventory)
Exit Sub
ErrorHandler:
Exit Sub
324 Centre for Information Technology and Engineering, Manonmaniam Sundaranar University
Packages and Internet Information Server
End Sub
Before you run your form, let’s change the view in the Transaction Server Explorer to
show the status of your object. You do this by selecting the Components folder in the
package you have created. Next choose View/Status. The right side of the Explorer
now shows the activity status of your object. If you run the form with the Transaction
Server Explorer where it can be seen, you can watch as the object that you crated
earlier is instantiated and executed
Microsoft Internet Information Server is a network file and application server and is
included with Windows NT server. IIS supports Hypertext Transfer
Protocol(HTTP),File Transfer Protocol(FTP) and gopher information protocols.
Web Classes
A Web Class is a Visual Basic component that resides on a Web server and responds
to input from the browser. When an IIS Application project type is opened, Visual
Centre for Information Technology and Engineering, Manonmaniam Sundaranar University 325
Advanced Visual Basic
Basic opens a Web designer that creates the Web Class. Webclasses typically contain
WebItems (HTML files) and code that delivers those Webitems to a client.
A webclass in an IIS application has an associated .asp (Active Server Pages) file that
Visual Basic generates automatically during the compile process. The .asp file hosts
the webclass on the Web server and launches its scripts for execution.
As shown in this figure 21.3, each webclass has its own ASP. In turn, a webclass can
have many webitems (HTML files) associated with it.
Reduced cost of deployment per user. End users of an IIS application can run
the application using only a browser; no special software needs to be installed
on their computers for the application to work.
It can send HTML pages either from Templates or from code to the browser.
Note : Templates are nothing but Webitems that holds designed HTML pages.
A Template can have only one HTML page.
) Packages are logical groupings of objects that are generally used as a unit.
) Visual Basic makes it easy to integrate Web browsing into the application by
way of the Web browser control, which is used to add Web-browsing
functionality to the Visual Basic application.
326 Centre for Information Technology and Engineering, Manonmaniam Sundaranar University
Packages and Internet Information Server
) Templates are nothing but Web items that holds designed HTML pages. A
Template can have only one HTML page
Create a IIS Application and accept user name and password and check whether the
password is “Radiant” or not ?.Raise an appropriate Error Message if Password is
wrong.
Centre for Information Technology and Engineering, Manonmaniam Sundaranar University 327
Advanced Visual Basic
Lecture - 22
Objectives
328 Centre for Information Technology and Engineering, Manonmaniam Sundaranar University
IIS, ASP and DHTML Application Compression
Lecture Unit - 22
Centre for Information Technology and Engineering, Manonmaniam Sundaranar University 329
Advanced Visual Basic
In this chapter the discussion will go on application of IIS , ASP and DHTML then
Debugging the IIS application and development process.
IIS applications are similar to DHTML applications in one way. Both arrange the
contents of Web documents dynamically. However, there are some key differences
between the two types of applications:
Webclass designer
When a project of type IIS Application is opened, Visual Basic presents WebClass
designer as in Figure 22.1.
330 Centre for Information Technology and Engineering, Manonmaniam Sundaranar University
IIS, ASP and DHTML Application Compression
The Treeview panel displays each webitem and connected event in the webclass.
There are two kinds of webitems:
HTML Template WebItems — HTML files that can be sent to the browser in
response to a request
The Detail panel displays information about the currently selected item in the
Treeview panel.
The process of creating an IIS application is similar to creating any other project in
Visual Basic. The overall process is presented below.
1. Start a new project and select IIS Application as the project type.
Note : Unlike forms-based Visual Basic applications, you must save an IIS application
before you add HTML template webitems to it.
3. Add as many HTML template webitems and custom webitems to the webclass
as needed.
Centre for Information Technology and Engineering, Manonmaniam Sundaranar University 331
Advanced Visual Basic
5. Write code for all standard, template, and custom events in the project.
Note : Make sure you write code for the Start event, or your application will not run
unless the user specifies a webitem in the base URL. For more information see
"Setting the Start Event".
7. Test and debug the application by running the project and viewing the
application in the browser. It is recommended that you test all browsers you
plan to support before releasing the application to end-users.
Example
This section shows how to create an ASP file using Visual Basic’s IIS Application
project type. Before creating the IIS Application create an HTML file [Link]
whose code listing is given below.
<HTML>
<BODY>
<CENTER>
<H2><U>Now You are in the Secret Site</U><H2>
</CENTER>
</H2>
</BODY>
</HTML>
This file will be used as a webitem in the IIS Application project.
Choose File | New Project to open the New Project dialog box.
332 Centre for Information Technology and Engineering, Manonmaniam Sundaranar University
IIS, ASP and DHTML Application Compression
In the Project Widow double click the Webclass1 to bring its designer front.
Save the project with the default names. (It is very important to store the
project in a specific folder. Then alone the HTML files that are added as
webitems can be stored in the Project folder).
Right click on the HTML Template Webitems in the Treeview panel and
choose Add HTML template from the popup menu that appears.
In the dialog box that appears browse and select [Link] and click open.
This will add a template under the HTML Template Webitems in the
Treeview panel as Template1. Rename it as SecretHtm.
Replace the code of the Web class start event procedure {WebClass_ Start()}
with the following code.
Centre for Information Technology and Engineering, Manonmaniam Sundaranar University 333
Advanced Visual Basic
.Write "<body>"
.Write "You are not an authorised user to go to_
the Secret Site"
.Write "</body>"
.Write "</html>"
End With
End If
End Sub
This event will occur when the [Link] invokes this web class. This procedure
checks whether visitor is an authorized user or not. If he is an authorized user, it
sends the contents of the template file to the browser using the WriteTemplate
method. Otherwise it creates an HTML page, which indicates that he is not an
authorized user, and sends it to the browser.
Choose File | Make [Link] to compile the project. Visual Basic will create
[Link] file.
Create an HTML [Link] file whose code listing is given below. This file
will call the [Link] file.
<HTML>
<BODY>
Type your name and click Submit<BR>
to go to the Secret Site.
<BR><BR>
<FORM Method="Get"
Action = "[Link]
<INPUT Type=Text Name="Name"><BR><BR>
<INPUT Type=Submit Name="Submit" Value=Submit>
</FROM>
</BODY>
</HTML>
The string /ASPs specifies the virtual directory which is mapped to the
project directory in which the [Link] file is stored.
334 Centre for Information Technology and Engineering, Manonmaniam Sundaranar University
IIS, ASP and DHTML Application Compression
Open the [Link] in the Internet Explorer, which will resemble the Figure
22.2
Type Indian in the texfield and click the submit button. This will call the
[Link] file, which invokes the web class. The web class verifies the
entered name. As it is Indian (the valid name), it will supply the [Link] file,
which is stored in the SecretHtm template. The browser receives this file and
renders it as in Figure 22.3.
Figure 22.3 HTML page sent by the ASP file when the user is an authorized
person.
Centre for Information Technology and Engineering, Manonmaniam Sundaranar University 335
Advanced Visual Basic
If some other name is typed and the Submit button is clicked, the web class creates
HTML page on the fly indicating that the user is not an authorised user and sends it
to the browser. The browser renders it as in Figure 22.4.
Figure 22.4 - HTML created and page sent by the ASP file when the user is not
an authorised person.
You debug an IIS application in the same way you do any other Visual Basic
application — by entering run mode from Visual Basic. Visual Basic loads the
webclass run time, creates the virtual root from which to run the .asp file for the
application, if necessary, and launches the system's default browser with an HTTP
reference to the .asp file. The .asp file, in turn, launches the webclass.
Note Although you can view the .htm files associated with your application in the
browser by opening them from the browser's File menu, this is not debugging your
application. You must use the Start option from Visual Basic to enter debugging
mode.
When you debug, you have the full Visual Basic development environment at your
disposal. You can use all the tools available in Visual Basic — breakpoints, watch
variables, debug statements, and so on — to debug your project.
Visual Basic prompts you when you debug that it is going to create a virtual
directory for your project. A virtual directory is a directory outside your Web
server's home directory that appears to browsers as a subdirectory of the home
directory. It allows you to publish contents to the Web from directories outside the
home directory structure. You cannot change the location of the virtual directory
Visual Basic creates for the webclass.
The Project Properties dialog box's Debugging panel settings determine whether the
system waits for you to tell it what to do when you go into run mode or
automatically starts the webclass you specify. When you choose to automatically
336 Centre for Information Technology and Engineering, Manonmaniam Sundaranar University
IIS, ASP and DHTML Application Compression
start the webclass, Visual Basic launches Internet Explorer, navigates to the URL for
your application, and fires the webclass's BeginRequest event.
Visual Basic deletes all temporary files when it comes out of run mode. In addition, it
destroys the instance of the Webclass Designer and restarts the designer in design
mode.
Errors in Webclasses
You can use Visual Basic's error-handling features in your IIS applications to trap
errors and take corrective action. When an error occurs, Visual Basic sets the various
properties of the error object, Err, such as an error number or a description. You can
use the Err object and its properties in an error-handling routine so that your
application can respond intelligently to an error situation.
In addition to standard error handling, IIS applications allow you to use two special
features to handle errors:
• You can use the Trace method to debug your application on the production
computer.
• You can use the FatalErrorResponse event to respond to serious run-time errors.
Using the Trace Method
You can use the Trace method to help identify errors during the debug process and
to track performance and statistical data. The Trace method sends a specified string
to the Win32 OutputDebugString API. The string can then be captured to a suitable
debugging tool such as DBMON.
Using the Trace method can allow you to debug on your production server computer
and record useful information such as information about the execution of the
application, error messages that occur, and any other information you need.
A fatal error on a webclass is one from which the application cannot recover or
restore the appropriate webitem. For example, a fatal error might be an unhandled
error within a webclass event, a structural error, or an unexpected error within the
run-time DLL. Following such an error, the webclass run time fires the
FatalErrorResponse event. The application is terminated and the instance of the
webclass is destroyed.
Centre for Information Technology and Engineering, Manonmaniam Sundaranar University 337
Advanced Visual Basic
When a fatal error occurs, the application can write a message to the Response object
in the handler for the FatalErrorResponse event. This message can be one that you
write, or it can be the default message for the .asp file associated with the webclass.
To write your own message, use the Response object, then set the senddefault
argument of the FatalErrorResponse event to False. To use the default error message,
leave the senddefault argument set to True.
Note :- The webclass run time provides an Error property that is only available
from within the FatalErrorResponse event. This property returns an
object that describes the error that caused the webclass to terminate.
The webclass run time also logs fatal errors to the NT event log. On Windows 95
systems, the run-time DLL creates a log file in the Windows directory and logs the
error there.
) Visual Basic deletes all temporary files when it comes out of run mode. In
addition, it destroys the instance of the Webclass Designer and restarts the
designer in design mode.
) DHTML applications are dependent on Internet Explorer 4.0 or later. But end
users of an IIS application do not need a specific operating system or browser.
338 Centre for Information Technology and Engineering, Manonmaniam Sundaranar University
Internet Concepts
Lecture - 23
Internet concepts
Objectives
About Internet
About Intranet
Centre for Information Technology and Engineering, Manonmaniam Sundaranar University 339
Advanced Visual Basic
Lecture Unit - 23
23.3 Intranet
340 Centre for Information Technology and Engineering, Manonmaniam Sundaranar University
Internet Concepts
If there is one technology that caught up literally overnight and has affected more
users than any others, it is the Web. The World Wide Web (WWW) is the set of all
Web sites and the documents they can provide to clients (users). Visual Basic 6 has
evolved to help the programmers to build Web applications. There are two different
types of Web applications — Dynamic HTML (DHTML) applications and Microsoft
Internet Information Server (IIS) applications.
Internet
Each computer on the Internet has a unique address, for example, [Link]. Each
number is a value in the range 0 through 255, which means the Internet have more
than 256*256*256*256, or approximately 4,000,000,000 computers. To accommodate a
large number of users, Internet service provider use a pool of addresses( since not all
users connect at once, 256 addresses may accommodate 100 users or more. It would
be nice it we all had a unique IP address, like an e-mail address, but this is not
possible. If we did, we could build wide area networks that span the globe easily.
However, every time you connect to your Internet service provider you get a
different IP address
23.3 Intranet
Unlike Internet, which is a global network, it is a private network. But it uses the
Internet communication standards and tools to provide information to the restricted
users. For example, a company may setup a Web site that is accessible only to its
employees who are geographically separated. On an intranet, you can exploit the
web model to simply operations, without the security issues you face on the Internet
or the limitations imposed by connecting computers with modems.
Centre for Information Technology and Engineering, Manonmaniam Sundaranar University 341
Advanced Visual Basic
some other organization, and they are not accessible by the outside world. Unlike the
World Wide Web, intranets don’t have more than one server. This machine supplies
all the documents requested by the clients. Many corporations use intranets to
provide information to their employees, and they run another Web site for external
users. The reason for building corporate intranets is to exploit the technology that
made the Web so popular. So the main characteristic of a corporate intranet is not
that it uses TCP/IP, as much as HTTP (HyperText Transfer Protocol)
The World Wide Web (WWW or simply the Web) gives a graphical, easy-to-navigate
interface for looking at documents on the Internet. These documents, as well as the
links between them, comprise a “Web” of information.
Files or pages on the Web are interconnected. This connection is made by means of
special text or graphics called hyperlinks.
Pages can contain text, images, movies, and sounds – just about anything. These
pages can be located on computers anywhere in the World. When a connection to
the Internet is made, it means equal access is available to information worldwide.
The computers that host Web sites are called servers; their service is to provide the
documents that the clients request. Clients are the seemingly endless numbers of
personal computers connected to the Internet. Web browser, such as Internet
Explorer (explained in the next section), helps to exploit the Web.
The Internet Explorer toolbar provides a range of detailed functions and commands
for managing the browser. The addressbar below the toolbar displays the address of
the current Web page. Typing an address and hitting Enter in it will enable to visit to
the specified page. Clicking a hyperlink will also enable to jump to the new page.
With Netscape dominating the Web browser and server market, Microsoft, in the
early 1996 introduced a new Web browser and server to the Internet community.
Microsoft Internet Explorer is destined to be one of the most popular Web browser
for several reasons. Not only is the browser easy to use and is supported by the
world’s largest software company, it also supports several other specific HTML
extensions. These include the following
342 Centre for Information Technology and Engineering, Manonmaniam Sundaranar University
Internet Concepts
For a computer to be a server on the Internet, it must have two things: an address by
which other computers can locate it and the capability to understand and process the
various protocols. A server is assigned a unique numeric ID called an IP (Internet
Protocol) address. As the numeric address is very difficult to remember their
corresponding domain name is used, which are in friendlier format such as
http:/[Link].
The software used on the physical computer to make it a server that can speak the
protocols of the Internet and respond accordingly is called Internet Server Software or
Web Server such as Microsoft Internet Information Server.
For a client computer to be able to communicate with a server on the Internet, it must
have a connection to the Internet. Then, when connected, it must have a way to
contact and receive data from Internet servers through the various protocols. The
connection is accomplished via an Internet Service Provider (ISP), such as VSNL,
Satyam Online, etc. The tool to communicate to the server and receive the data
returned by the Internet Server is handled by the Internet browser, such as Internet
Explorer. The Figure 5.1 depicts the working of the Internet.
Centre for Information Technology and Engineering, Manonmaniam Sundaranar University 343
Advanced Visual Basic
) The World Wide Web (WWW or simply the Web) gives a graphical, easy-to-
navigate interface for looking at documents on the Internet. These documents, as
well as the links between them, comprise a “Web” of information.
344 Centre for Information Technology and Engineering, Manonmaniam Sundaranar University
DHTML
Lecture - 24
DHTML
Objectives
About DHTML
About Server
Centre for Information Technology and Engineering, Manonmaniam Sundaranar University 345
Advanced Visual Basic
Lecture Unit - 24
346 Centre for Information Technology and Engineering, Manonmaniam Sundaranar University
DHTML
This chapter is discuss on HTML developing , its structure and its applications.
This section develops a simple DHTML document, which has 5 major segments
(designed using DIV tags). The first segment has one password box and a command
button. This segment alone is visible when the document is loaded in browser and
all other segments are invisible. When a user enters a password and clicks the
command button, the script written for the command button’s click event, verifies
the validity of the entered password. If it is valid the first segment disappears and
second segment appears, which has three option (radio) buttons. The other three
segments are designed for each option button and they are positioned at a same
location. Because only one option button can be selected, the segment corresponding
to that option alone is made visible and other two segments are made invisible. This
DHTML document is named as [Link], as it describes about Indian Monuments
and its listing is given below.
<HTML>
<HEAD>
<TITLE>
Indian Monuments
</TITLE>
Sub Opt1_Onclick()
[Link] = "Visible"
[Link] = "Hidden"
[Link] = "Hidden"
End Sub
Sub Opt2_Onclick()
[Link] = "Visible"
[Link] = "Hidden"
[Link] = "Hidden"
End Sub
Sub Opt3_Onclick()
[Link] = "Visible"
[Link] = "Hidden"
Centre for Information Technology and Engineering, Manonmaniam Sundaranar University 347
Advanced Visual Basic
[Link] = "Hidden"
End Sub
Sub cmdLogin_onClick()
End Sub
</SCRIPT>
</HEAD>
<BODY background="[Link]">
<CENTER>
<H2>INDIAN MONUMENTS</H2><HR>
</CENTER>
<DIV Id=divLogin>
<FORM Id=frmLogin>
<LABEL>Password
<INPUT Type=Password Id=txtPWord>
</LABEL>
<INPUT Type=Button Id=cmdLogin Value="Login">
</FORM>
</DIV>
Left:20;Top:90;Visibility:Hidden">
<DIV Style="Position:Relative;Top:10;Width:130;Height:80;
Background-color:Yellow">
<FORM Id=frmOptions>
<INPUT Type=Radio Name=Monument Id=Opt1 Checked>Taj
348 Centre for Information Technology and Engineering, Manonmaniam Sundaranar University
DHTML
Mahal<BR>
<INPUT Type=Radio Name=Monument Id=Opt2>Qutub Minar<BR>
<INPUT Type=Radio Name=Monument Id=Opt3>Fatehpur Sikri<BR>
</DIV>
</FORM>
</DIV>
Style="Position:Absolute;Left:275;Top:85">
<DIV Style="Position:Absolute;Left:20;Top:240;Width:450;Background-
color:Yellow">
One among the 7 World wonders. Built by Shajahan at the riverbank of
Yamuna.
</DIV>
</DIV>
<DIV Style="Position:Absolute;Left:20;Top:240;Width:450;
Background-color:Yellow">
Astonishing tower with height 242 feet. Started by Quthputheen and successfully
completed by Eldhuthmish.
</DIV>
</DIV>
<DIV Style="Position:Absolute;Left:20;Top:240;Width:450;
Background-color:Yellow">
Instance for sculpting art. Nick named as love designed in stone. Built by
great emperor Akbar.
</DIV>
</DIV>
</BODY>
</HTML>
Centre for Information Technology and Engineering, Manonmaniam Sundaranar University 349
Advanced Visual Basic
When this HTML page is opened in the Internet Explorer it will prompt to enter the
password as in Figure 24.1.
Enter the password Indian and click Login button. Now the first segment in this
document that contains the textfield, button, will disappear and the other segments
that describes about Indian Monuments will appear as in Figure 24.2
So far, web pages are created in non-visual environment (Notepad). Creating web
pages in this method consumes much time and also positioning the controls and
elements of a web page at proper location will cause the developer’s eye turn to red.
As so much of tags are used even to create simple web pages, there is a chance that
few tags may be misspelled. And it is difficult to trace out the errors caused due to
this misspelling.
350 Centre for Information Technology and Engineering, Manonmaniam Sundaranar University
DHTML
Visual Basic 6.0 includes new project type called DHTML Application, which
provides visual environment to rapidly develop the DHTML applications.
An HTML page is stored in a .htm file that is analogous to a .frm file. The following
table sums up the differences between forms-based applications and Web-based
applications:
Forms-based Web-based
application application
Visual Basic code that handles the events generated from the HTML
pages.
A project DLL that contains the Visual Basic code and is accessed by the
run-time component generated automatically when the application is
compiled.
When a DHTML project is compiled, all HTML pages are stored in separate .htm
files. The code that handles the events generated from the HTML pages are
compiled in to a .dll file. The id of the .dll file is automatically included in the .htm
Centre for Information Technology and Engineering, Manonmaniam Sundaranar University 351
Advanced Visual Basic
files. So whenever an event raises from a .htm file, the code for that event in the .dll
file is executed by the browser automatically.
Visual Environment HTML pages can be created in the familiar Visual Basic IDE.
As it is a Visual environment, controls can be placed in the HTML pages at the
desired locations easily. Debugging tools can also be used to fix the bugs in VB
scripts.
Code Security When scripts are embedded with an HTML page, anyone can access the
page, read the script, and make changes to it. As Visual Basic compiles the code into
.dll, the code is not part of the HTML file itself, and so it can’t be tampered.
When a project of type DHTML is opened, Visual Basic presents DHTML Page
designer as in Figure 5.4, which enables to:
Determine which elements on the page are programmable and explore all the
dynamic elements on the page.
Access the Code Editor window to write code for each programmable
element on the page.
The following sections brief the different areas of the DHTML Page designer.
352 Centre for Information Technology and Engineering, Manonmaniam Sundaranar University
DHTML
Detail Pane
Presents a drawing surface that enables to create a new page or edit the contents of
an existing page. It provides a visual environment to add HTML elements to the
page, position them, and set properties that control their physical appearance.
Contains buttons that are frequently used when formatting an HTML page in the
designer. The items on this toolbar are available whenever a DIV element, or a
hyperlink, or a piece of text, or the BODY or DOCUMENT objects in the treeview or
detail panes of the designer is selected.
When a toolbar button is clicked to carry out the action represented by that button,
Visual Basic inserts the appropriate opening and closing HTML tags or tag attributes
to the selection. These tags are not visible within the designer, but the results of
formatting are rendered in the detail pane.
Contains buttons that are frequently used when grouping the elements on the page
such as by using DIV tag or working with tables. With the exception of the Table
Operations icon, the options on this toolbar band are available only when some
elements are selected. The Table Operations icon is always available.
Note : The HTML files created using DHTML Page designer are stored in the
files with the extension .dsr. The actual .htm files are created only
when the application is compiled.
This section shows how to create a simple DHTML application, which contains three
HTML pages.
Centre for Information Technology and Engineering, Manonmaniam Sundaranar University 353
Advanced Visual Basic
The first HTML page has a hyperlink that leads to the second HTML page. The
second page contains a command whose clicking leads to the third page using code.
This is not a full-fledged application. But the purpose of this section is to show how
creation of the DHTML applications are simpler than by using HTML tags.
Choose File | New Project to open the New Project dialog box.
This will create a new DHTML Application with default DHTML page (DHTMLPage1).
In the Project Explorer window double click the ArabicSea to bring its design
window front.
In the Format band select Header1 from the HTML Block Elements combo
box and enter “Arabic Sea” in the Details pane.
Right click on the word “me” in the popup menu that appears, choose
Properties. This will display the Properties dialog box.
354 Centre for Information Technology and Engineering, Manonmaniam Sundaranar University
DHTML
Enter [Link] in the Link text box and Leads to Bay of Bengal in
the popup text box as in Figure 5.5. This text will appear in the browser
window when the mouse pointer moves over the hypertext “me”. When it is
clicked [Link] page will appear in the browser.
Figure 24.4 Destination (through Link) and Popup text for the hypertext “me”.
The designed DHTML page ArabicSea should resemble the Figure 24.5
In the Project Explorer window double click the BayOfBengal to bring its
design window front.
In the Format band select Header1 from the HTML Block Elements combo
box and enter “Bay of Bengal” in the Details pane.
The designed DHTML page BayOfBengal should resemble the Figure 24.6.
Centre for Information Technology and Engineering, Manonmaniam Sundaranar University 355
Advanced Visual Basic
Write the following lines for the button’s (Click me to go...) click event
procedure.
[Link] = "[Link]"
The above line assigns the HTML file name “[Link]” to the Href
(Hyperlink reference) property of the location object of the basewindow to
jump to that file.
In the Project Explorer window double click the IndianOcean to bring its
design window front.
In the Format band select Header1 from the HTML Block Elements combo
box and enter “Indian Ocean” in the Details pane.
When the Visual Basic prompts the .dll file name accept the default file name
[Link].
When the Visual Basic prompts file name for each DHTML files, enter them
as [Link], [Link], and IndianOcean respectively.
Open the Internet Explorer and in its address text box type [Link]
with full path and hit enter. This will open the [Link] file in the
Internet Explorer.
Test the
356 Centre for Information Technology and Engineering, Manonmaniam Sundaranar University
DHTML
) Visual Basic 6.0 includes new project type called DHTML Application, which
provides visual environment to rapidly develop the DHTML applications.
) Visual Environment HTML pages can be created in the familiar Visual Basic
IDE. As it is a Visual environment, controls can be placed in the HTML pages
at the desired locations easily. Debugging tools can also be used to fix the
bugs in VB scripts.
) Code Security When scripts are embedded with an HTML page, anyone can
access the page, read the script, and make changes to it. As Visual Basic
compiles the code into .dll, the code is not part of the HTML file itself, and so
it can’t be tampered.
Centre for Information Technology and Engineering, Manonmaniam Sundaranar University 357
Advanced Visual Basic
Lecture - 25
Data Report
Objectives
358 Centre for Information Technology and Engineering, Manonmaniam Sundaranar University
Data Report
Lecture Unit - 25
25.2 Report
Centre for Information Technology and Engineering, Manonmaniam Sundaranar University 359
Advanced Visual Basic
25.2 Report
Displays or prints a report under the control of a report definition file created with
MODIFY REPORT or CREATE REPORT.
Syntax
Arguments
FileName1
Helps you design a report that displays fields and records from the underlying table
or query.
A report is an effective way to present data in a printed format. You can display the
information the way you want to see it.
You create the report using graphical objects called Data Report designer controls.
Data Report designer controls include: a data-bound TextBox control, a Function
control which displays calculated figures, an Image control for inserting graphics,
labels that display captions, and a Line and a Shape control that graphically
organizes the data.
360 Centre for Information Technology and Engineering, Manonmaniam Sundaranar University
Data Report
Note : Although the Data Report designer controls are similar to Visual Basic intrinsic
controls, Data Report Designer controls have a limited subset of features. When
the Data Report designer is added to a project, the designer's controls are placed
in the Visual Basic Toolbox on a new tab named DataReport and can be used
only in the Microsoft Data Report.
The Data Report generates reports using records from a database. To use it:
Use the DataReport object to programmatically change the appearance and behavior
of the Data Report by changing the layout of each Section object.
The Data Report designer also features the ability to export reports using the
ExportReport method. This method allows you to specify an ExportFormat object,
from the ExportFormats collection, to use as a template for the report.
Centre for Information Technology and Engineering, Manonmaniam Sundaranar University 361
Advanced Visual Basic
Section object— The data report designer contains sections which helps to configure
the report more elegantly. The Sections of the Data report designer is explained in
the next section.
Data Report Controls—Special controls that only work on the Data Report designer
are included with it. These controls are found in the Visual Basic Toolbox, but they
are placed on a separate tab named "DataReport."
Use the Report Designer to create and modify reports. When the Report Designer
window is active, Visual Basic displays Report Controls toolbar.
Drag-and-Drop Functionality for Fields— When fields are dragged from the
Microsoft Data Environment designer to the Data Report designer, Visual Basic
automatically creates a text box control on the data report and sets the DataMember
and DataField properties of the dropped field. A command object can also be
dragged from the Data Environment designer to the Data Report designer. In that
case, for each of the fields contained by the Command object, a text box control will
be created on the data report; the DataMember and DataField property for each text
box will be set to the appropriate values.
Toolbox Controls—The Data Report designer features its own set of controls. When
a Data Report designer is added to a project, the controls are automatically created
on a new Toolbox tab named DataReport. Most of the controls are functionally
identical to Visual Basic intrinsic controls, and include a Label, Shape, Image,
TextBox, and Line control. The sixth control, the Function control, automatically
generates one of four kinds of information: Sum, Average, Minimum, or Maximum.
Print Reports— When a report is generated, it can be printed by clicking the printer
icon on the toolbar.
File Export – In addition to creating printable reports, it can be exported to text files,
by clicking the Export icon and specifying text file name.
362 Centre for Information Technology and Engineering, Manonmaniam Sundaranar University
Data Report
Note These shortcut menu options are context sensitive. Not all of the following
options appear each time you open the shortcut menu.
Paste
Places from the Clipboard cut or copied sections of text at the insertion point. This
command corresponds to the Paste command in the Edit menu.
Cut
Removes selected text to the Clipboard. Once you cut something, you can paste it
elsewhere in the current application or in other application. This command
corresponds to the Cut command in the Edit menu.
Copy
Duplicates selected text and puts it on the Clipboard. Once you copy something to
the Clipboard, you can paste it elsewhere in the current application or in other
applications. This command corresponds to the Copy command in the Edit menu.
Preview
Shows you the results of your work without printing it and displays the Print
Preview toolbar. Use the options on the toolbar to change the preview. You can also
click the image of the previewed page to zoom in, and click again to zoom out or
return to design mode. This command corresponds to the Preview command in the
View menu.
Print
Allows you to print the current report by displaying the Print dialog box. This
command corresponds to the Print command in the File menu.
Data Environment
Displays the Data Environment Designer which allows you to visually create and
modify the data environment of the report. This command corresponds to the Data
Environment command in the View menu.
Data Grouping
Displays the Data Grouping dialog box so you can create data groups and specify
their properties. This command corresponds to the Data Grouping command in the
Report menu.
Centre for Information Technology and Engineering, Manonmaniam Sundaranar University 363
Advanced Visual Basic
Properties
Displays a dialog box that corresponds to the object type selected (a text field,
rectangle, an OLE Object field, etc.) which allows you to set the object's position and
other parameters. These parameters can include printing instructions, calculations
and expressions.
Help
Displays Help on the selected item.
Report Header—contains the text that appears at the very beginning of a report, such
as the report title, author, or database name.
Page Header—contains information that goes at the top of every page, such as the
report's title.
Details—contains the innermost "repeating" part (the records) of the report. The
details section is associated with the lowest-level Command object in a Data
Environment hierarchy.
364 Centre for Information Technology and Engineering, Manonmaniam Sundaranar University
Data Report
Page Footer—contains the information that goes at the bottom of every page, such as
the page number.
Report Footer—contains the text that appears at the very end of the report, such as
summary information, or an address or contact name.
Centre for Information Technology and Engineering, Manonmaniam Sundaranar University 365
Advanced Visual Basic
This topic creates a simple data report using a Data Environment designer as a data
source. The Data Environment designer uses the NorthWind database supplied with
Visual Basic to create a simple hierarchical cursor. The cursor contains two tables,
Customers and Orders, and uses the CustomerID field to link the two. The finished
report resembles the figure 25.3 .
Before you begin the step-by-step process, ensure that the Northwind database
([Link]) is present on your computer. If it is not present, copy the file from
your Visual Basic CD onto your hard disk.
2. On the Project menu, click Add Data Environment to add a designer to your
project. If the designer is not listed on the Project menu, click Components. Click
the Designers tab, and click Data Environment to add the designer to the menu.
3. On the Data Link Properties dialog box, click Microsoft Jet 3.51 OLE DB Provider.
This selects the correct OLE DB provider for accessing a Jet database.
5. Click the ellipsis button (…) next to the first text box.
6. Use the Select Access Database dialog box to navigate to the [Link] file,
which is installed in the Program Files\Microsoft Visual Studio\Vb98 directory.
8. Right-click the Connection1 icon, and click Rename. Change the name of the icon
to Northwind.
9. Right-click the Northwind icon, and then click Add Command to display the
Command1 dialog box. In the dialog box, set the properties as shown below:
Property Setting
Command Name Customers
Connection Northwind
DataBase Object Table
Object Name Customers
366 Centre for Information Technology and Engineering, Manonmaniam Sundaranar University
Data Report
11. Right-click the Customers command, and click Add Child Command to display
the Command2 dialog box. In the dialog box, set the properties as shown below:
Property Setting
Command Name Orders
Connection Northwind
DataBase Object Table
Object Name Orders
12. Click the Relation tab. The Relate to a Parent Command Object check box should
be checked. The Parent box should contain Customers; both the Parent Fields and
Child Fields/Parameters boxes should contain CustomerID.
When designing relational databases, it's customary for related tables to use the
same name for linking fields. In this case, the linking fields are both named
CustomerID. The Data Environment designer automatically matches such pairs
in the dialog box.
Clicking the Add button adds the relation to the Command object. After closing
the dialog box, the Data Environment designer reflects the relationship by
displaying the two commands as a hierarchy. This hierarchy will be used to
create the data report.
14. Set the properties of the project and designer according to the settings below,
then save the project:
Centre for Information Technology and Engineering, Manonmaniam Sundaranar University 367
Advanced Visual Basic
4. Set the properties of the Command1 control according to the table below:
Property Setting
Name cmd
Show Caption
Show Report
You can also display the data report with no code at all.
368 Centre for Information Technology and Engineering, Manonmaniam Sundaranar University
Data Report
Note : If you use this method, you can remove the Form object from your
project.
Printing a data report can be accomplished in one of two ways. The user can click the
Print button that appears on the data report in Print Preview mode (using the Show
method), or you can programmatically enable printing using the PrintReport
method. If an error occurs during printing, trap it in the Error event.
[Link] True
The Print dialog box allows the user to select a printer, print to file, select a range of
pages to print, and specify the number of copies to print.
In some cases, you may wish to print the report without user intervention. The
PrintReport method also gives you the option of selecting a range of pages to print,
either all, or a specified range.
Centre for Information Technology and Engineering, Manonmaniam Sundaranar University 369
Advanced Visual Basic
PrintReport Method
At run time, prints the data report created with the Data Report designer.
Syntax
Settings
ConstantValueDescriptionrpt RangeAllPages0(Default)
All pages will be printed. rptRangeFromTo1Only the specified range of pages will be
exported.
Long
If no arguments are supplied with the method, a dialog box will be displayed
prompting the user for appropriate information.
1. On the Data Environment designer, right-click the Orders Command object. Then
click Add Child Command.
370 Centre for Information Technology and Engineering, Manonmaniam Sundaranar University
Data Report
Property Setting
Command Name OrderDetails
Connection Northwind
DataBase Object Table
Object Name Order Details
3. Click the Relation tab. The Relate to a Parent Command Object check box should
be checked. The Parent box should contain Orders; both the Parent Fields and
Child Fields/Parameters boxes should contain OrderID. Click the Add button
and then click OK to close the dialog box.
4. Right-click the OrderDetails Command object, and click Add Child Command.
Set the properties of the connection as shown below:
Property Setting
Command Name Products
Connection Northwind
DataBase Object Table
Object Name Products.
Click the Relation tab. The Relate to a Parent Command Object check box should be
checked. The Parent box should contain OrderDetails; both the Parent Fields and
Centre for Information Technology and Engineering, Manonmaniam Sundaranar University 371
Advanced Visual Basic
Child Fields/Parameters boxes should contain ProductID. Click the Add button and
then click OK to close the dialog box.
Once the data environment has been extended with new tables, you can extend the
data report as well by dragging fields from the Data Environment designer to the
Data Report designer.
1. Right-click the Data Report designer, and clear Show Page Header/Footer box.
Clearing this option deletes the page header and footer, which are not being used
at this point.
2. Right-click the Data Report designer, and click Insert Group Header/Footer. The
Insert New Group Header/Footer dialog box will be displayed.
The dialog box allows you to determine if the new header and footer will "bracket" other
header/footer pairs. This becomes important as you add more header and footer pairs
because the outermost pair of header/footers subordinates all other pairs. Click OK to
select the default placement of the new header and footer pair and close the dialog box.
3. Select the new group header, and on the Properties window, change its name
from Section1 to Orders_Header. Change the corresponding footer name from
Section4 to Orders_Footer.
4. Repeat steps 2 to 3. Name the new group header OrderDetails_Header, and the
new group footer OrderDetails_Footer.
5. Click the Detail (Orders_Detail) section to select it. On the Properties window,
change the section's name to Products_Detail.
6. Using the mouse, drag the OrderDate field from the Detail (Products_Detail)
section to the Orders_Header section.
7. From the Data Environment designer, drag the ProductName field (under the
Products command) into the Detail (Products_Detail) section.
372 Centre for Information Technology and Engineering, Manonmaniam Sundaranar University
Data Report
9. Resize the group headers, and rearrange the text box controls to resemble the
figure 25.5 below.
The figure above requires some explanation. First, the Group footers are all closed in
order to take up the least possible space. Like the Details section, any additional
space left in any header or footer will be multiplied in the final report. Therefore, if a
header or footer doesn't contain any fields, you can close the distance between the
headers or footers.
The Group Header named OrderDetails_Header is also closed. If you wonder why
no fields are being shown, you must understand that the Order Details table in the
Northwind database is a join table—the table contains only the IDs of records from
the Orders table joined to IDs of records from the Products table. Thus the Order
Details table doesn't contain fields which are actually displayed. Instead, it functions
only to join two other tables. In the Data Report designer, the Order Details table
therefore functions only to create groups of records—the product names grouped
under the order dates.
Finally, the Details section contains only the names of products. The Details section
contains the innermost level of repeating records.
Centre for Information Technology and Engineering, Manonmaniam Sundaranar University 373
Advanced Visual Basic
• The first four kinds of ActiveX designers loaded for a project are listed on the
project menu. If more than four designers are loaded, the later ones will be
available from the More ActiveX submenu of the Project menu.
• Visual Basic’s intrinsic controls, or any ActiveX controls, can not be used on the
Data Report Designer.
3. What are all the Options available in Data Report Shortcut Menu?
• EMP
Eno
Ename
Basic
HRA
DA
PF
Dno
• DEPT
Dno
Dname
374 Centre for Information Technology and Engineering, Manonmaniam Sundaranar University
Data Report
Create a report, which shows all the above listed fields grouped by their Dno
Display the title of the report as ‘XYZ COMPANY’ and a Logo to the left of it
The Date of preparation should be displayed in the top right corner of the report
Centre for Information Technology and Engineering, Manonmaniam Sundaranar University 375
Advanced Visual Basic
Lecture - 26
Objectives
376 Centre for Information Technology and Engineering, Manonmaniam Sundaranar University
Active Server Page
Lecture Unit - 26
Centre for Information Technology and Engineering, Manonmaniam Sundaranar University 377
Advanced Visual Basic
[Link] Shot
This chapter will discuss on how to display Data Report during the Run Time,
Introduction about Active Server Page, Developing Active Server Page and its
applications.
Microsoft introduced several methods for developing scripts on the server - some of
them quite simple and others not as simple. There was a confusing time when
companies did their best to simplify the development for sever side scripts, but none
of these methods were particularly easy for Visual Basic developers or even for Web
authors.
The situation changed drastically with the introduction of Active Server Pages (ASP),
an elegant solution to the problem of scripting. Active Server Pages are basically
HTML code that contains VBScript code, which is executed on the server. The
HTML code is transmitted to the client, as is. Active Server Pages almost look like
HTML document. As the HTML document has the .htm extension, ASP has the
extension .asp.
The scripts included on an Active Server Page produce text and HTML tags that are
also sent to the client, where they are rendered on the screen. An Active Server Page
can produce any output, but only HTML documents can be rendered on the client.
Open Architecture
Active Server Pages are not limited to a particular language. Currently, they support
VBScript and JScript, but third parties can provide support for other languages such
as Perl. In addition, multiple scripting languages can be used interchangeably in the
same ASP file.
Ease of Development
Active Server Pages make it easy for HTML authors to activate their Web pages on
the server.
Browser Independence
The output produced by an ASP is straight HTML code, which can be viewed with
any browser. All application logic needed to generate dynamic content resides on
378 Centre for Information Technology and Engineering, Manonmaniam Sundaranar University
Active Server Page
the server. It may be complicated. But the visitors do not see this complexity, and
they aren’t required to have a specific browser. Any browser that can handle the
latest version of HTML will render the documents produced by the ASP.
Active Server Pages provide the client’s the requested information. Actually the
request is made by the client’s browser. It passes visitor-supplied data to the Server.
In the Server, the ASP read the data, process them, and pass the results in the form of
another HTML page, which is generated on the fly.
In a normal HTML page, when a hyperlink is clicked or some button that lets a jump
to another page is clicked, the browser passes the address of the page (which is to be
displayed) to the Server and the Server supplies that page to the browser.
But, for the client to interact with the Server there must be a way for the browser to
send information to the server, along with the name of the requested page or
document For example, a visitor may like to get information about specific products,
say Car. The browser must request the document, say [Link], with the user
entered data – Car. These data are appended as parameters with the requested
document and sent to the server, which is something like this.
[Link]
parametername=parametervalue
The parametername parameter is the name, and parametervalue is the value of the
parameter. If a Form (defined using <FORM> tag) is used collect information from
the visitor, the parameter names are the names of the controls on the Form. Multiple
parameters are separated by the ampersand (&) sign, as in the following:
[Link]
If a value contains spaces, each space is replaced by the plus sign (+) as in the
following:
Centre for Information Technology and Engineering, Manonmaniam Sundaranar University 379
Advanced Visual Basic
[Link]
Diesel
To append the parameter to an address the <FORM> tag requires two parameters:
Action
Method
The Action parameter specifies the name of the application that will process the
request on the Server. For the purpose of this chapter, this application is an Active
Server Page (a file with the extension ASP). The method parameter indicates the
type of form-handling protocol that will be used to pass the parameters to the
application, and it can have one of the values GET and POST. The application that
receives the information usually dictates the method. Active Server Pages recognize
both methods, but handle them differently.
The browser, therefore, picks up the address of the application from the <FORM> tag
and appends the parameter=value pair to it. Each pair corresponds to a control on
the Form: The control’s name is the parameter name, and the control’s value is the
parameter value. The whole thing is done automatically. When the Submit button in
the FORM is clicked, the browser submits the request to the Server. This button is
defined using <INPUT> tag as in the following:
Previous section explained how the browser sends information to the Server. Active
Server Pages, which are, get executed on the Server must have some way to process
the information sent by the browser. They use objects to process the incoming
information and to give response to the browser. Their major objects are:
Request
It enables to access the parameters passed to the Server by the client, along with the
address. Its property QueryString returns the entire parameters collection. This
collection can be stored in a variable and parameter names can be used to access their
values as in the following:
380 Centre for Information Technology and Engineering, Manonmaniam Sundaranar University
Active Server Page
Response
<%
[Link] “<BODY>”
If PName = “Car”
[Link] “<P> <B> New Cars </B> </P>”
[Link] “Indica <BR>”
[Link] “Hyundai <BR>”
Else
[Link] “<P> <B> General Products </B> </P>”
---------------------------------------
---------------------------------------
End if
[Link] “</BODY>”
%>
This section first gives a listing of an HTML page, which gets a word from the visitor
and calls an ASP page with the entered word as an argument. Then this section
shows how to create the ASP page, which gets the entered word by the visitor,
generates an HTML page on the fly that prints that word for five times and sends
that HTML page to the browser. The following is the listing of the HTML page
[Link].
<HTML>
<BODY>
Type a word and click Submit.<BR>
Web Server will print it for five times
<FORM Method="GET"
Action="[Link]
</FORM>
</BODY>
Centre for Information Technology and Engineering, Manonmaniam Sundaranar University 381
Advanced Visual Basic
</HTML>
The string [Link] in the Action parameter of the FORM tag specifies the
address of the Web Server of the local computer. The string /ASPages specifies the
virtual directory which contains the [Link] file that is to be executed.
Physical directories in the Web Server are mapped into Virtual directories and the
Web Server makes use of it. Using virtual directories will prevent the visitors from
knowing about the actual location of the Active Server Pages.
The FORM in this HTML page contains two controls – a textfield and a submit
button. The Name argument in the INPUT tag that defines the textfiled specifies the
name of the textfield as “Word”. So that when submit button is clicked the
parameter=value pair in the address string will appear as in the following:
Word=someword
The value argument in the INPUT tag that defines the Submit button specifies the
caption of the Submit button as “Submit”.
<HTML>
<%
Set Param = [Link]
[Link] "<BODY>"
[Link] "<H2> Response from ASP</H2> <HR>"
For I = 1 to 5
[Link] "<H4>" & Param("Word") & "</H4>"
Next
[Link] "</BODY>"
%>
</HTML>
Save it as [Link]
The scripts in this document are placed between the tags <% and %>. So they are
not visible to the user and they are replaced by their output (Proved in a Figure
shortly). This document first assigns the parameter collection sent by the browser
in the variable Param. Then it begins to build the HTML document that prints the
value of the “Word” parameter for five times using the write method of the
Response object. The result of the write method produces an output stream and it
is directed by the Server to the browser, and the browser renders the received
output.
382 Centre for Information Technology and Engineering, Manonmaniam Sundaranar University
Active Server Page
Open the [Link] in the Internet Explorer, which will resemble the Figure
26.1
Type a word in the textfield, say Jaihind, and click the Sumbit button. The
browser will send the request to the Server as in the following:
[Link]
When the Server receives the request it will invoke the [Link] file with the
received parameter “Word”. The output produced by the [Link] is directed
by the Server to the Browser, which renders it as in Figure 26.2
Centre for Information Technology and Engineering, Manonmaniam Sundaranar University 383
Advanced Visual Basic
Choose View | Source from the Internet Explorer menu. This will display the
created HTML document code in the NotePad as in Figure 26.3.
Note that the scripts in the [Link] are replaced by its output.
) To call Active Server Pages that live in the local computer, either Internet
Information or Personal Web Server must be installed in the local computer.
) Server side scripts such as [Link] “….”, are enclosed in a pair of <% and
%>. These tags enclose all the statements that must be executed on the server.
Everything Between these two tags is considered server-side scripts, which is
replaced by its output and Seen by the client.
) Active Server Pages provide the client’s the requested information.
1. What are all the steps involved do display a Data Report during the Run Time?
2. Write a note on Active Server Pages
3. What are the advantages of Active Server Pages?
4. What are all the ASP Object type?
384 Centre for Information Technology and Engineering, Manonmaniam Sundaranar University
Package and Deployment
Lecture - 27
Objectives
Centre for Information Technology and Engineering, Manonmaniam Sundaranar University 385
Advanced Visual Basic
Lecture Unit - 27
386 Centre for Information Technology and Engineering, Manonmaniam Sundaranar University
Package and Deployment
This Chapter mainly will discuss on about Package and Deployment wizard.
The package and Deployment Wizard is one of the application in the VB6
program group. You can also use it from within Visual Basic by selecting it in
the Add –In Manager.
The Visual Basic Package and Deployment Wizard helps you create .cab files
for your application, group them into a unit, or package, that contains all
information needed for installation, and deliver those packages to end users.
You can use Visual Basic's Package and Deployment Wizard to create
packages that are distributed on floppy disks, CDs, a local or network drive,
or the Web. The Package and Deployment Wizard automates much of the
work involved in creating and deploying these files.
The distribution process of an completed Visual Basic application has the following
two steps:
Packaging – The application’s files must be packaged into one or more .cab files to
deploy them in a desired location. A .cab file is a compressed file that is well suited to
distribution on either disks or the Internet. A setup program must also be created to
install the packaged files in the end user’s system.
Deployment – The packaged application must be moved to the location, from which
users can install it. This means copying the package to floppy disks or to a local or
network drive, or deploying the package to a Web site.
The Visual Basic Package and Deployment Wizard helps automates much of the
work involved in creating and deploying the .cab files and setup files.
The Package option helps to package a project's files into a .cab file that can then
be deployed, and in some cases creates a setup program that installs the .cab files.
The wizard determines the files needed to package and leads through all the
choices that must be made in order to create one or more .cab files for the
application.
The Deploy option helps to deliver the packaged applications to the appropriate
distribution media, such as floppies, a network share, or a Web site.
Centre for Information Technology and Engineering, Manonmaniam Sundaranar University 387
Advanced Visual Basic
The Manage Scripts option lets to view and manipulated the scripts that are
saved from previous packaging and deployment sessions in the wizard. Each
time the wizard is used a script is saved containing all the choices made in the
current session. These scripts are useful to speed up the deployment process of
the same application for its later versions.
Application packaging is the act of creating a package that can install an application
onto the user's computer. A package consists of the .cab file or files that contain the
compressed project files and any other necessary files the user needs to install and
run the application. These files may include setup programs, secondary .cab files, or
other needed files. The additional files vary based on the type of package that is
created. There are two kinds of packages:
need to be updated.
Figure 27.1 Portion of Make tab of Project Properties dialog box to set Major and
Minor release numbers, and Revision number.
The following steps are common for any package type. And the Package and Deployment Wizard performs many of
these steps automatically.
388 Centre for Information Technology and Engineering, Manonmaniam Sundaranar University
Package and Deployment
1. Determining the type of package Either standard package can be chosen for
Windows-based programs that will be distributed on disk, on CD, or over a
network; or an Internet package for programs that will be distributed (ActiveX
programs) on the Web. Creation of only a dependency file can also be chosen.
2. Determining the files needed for distribution The wizard must determine the
project files and dependent files for the application before it can create the
package. Project files are the files included in the project itself — for example, the
.vbp file and its contents. Dependent files are run-time files or components the
application requires to run. Dependency information is stored in the [Link]
file, or in various .dep files corresponding to the components in the project.
3. Determining where to install files on the user's machine Program and setup
files are usually installed into a subdirectory of the Program Files directory, while
system and dependent files are usually installed into the \Windows\System or
\Winnt\System32 directory. The setup program must take this into account and
determine where to install each file.
4. Creating the package The wizard creates the package and the setup program
([Link]) for it, referencing all necessary files. The end result of this step is one
or more .cab files and any necessary setup files.
Using Deployment portion of the Package and Deployment Wizard to deploy the
applications to floppy disks, a local or network drive, or to a web site.
The Package and Deployment Wizard provides shortcuts and automatically performs some of the same tasks that is
performed manually.
The following steps are common in both ways (by hand -manual and by
Wizard) of deploying an application.
Centre for Information Technology and Engineering, Manonmaniam Sundaranar University 389
Advanced Visual Basic
1. Identifying the package to deploy The active project might have been packaged
using different package types such as Standard package, Internet Package, etc.
This step identifies a package for deployment.
3. Choosing the files to deploy If the application is deployed to the Internet, some
files may be added or removed from the list of files to be deployed. For example
very common .ocx may be available in the end users system. These files can be
removed from the list of files to be deployed. This will reduce the download time
of the end user’s system.
4. Determining the destination for deployed files For Internet deployment, this
involves specifying a Web site to which the package is to be deployed. For
directory deployment, this means indicating the drive location to which the
package is to be deployed. For floppy disk deployment, this means choosing the
appropriate floppy drive.
This section shows how to Package and deploy the simple Visual Basic application
PackDep_Demo.
Start a new project (Standard EXE) and rename the project as PackDep_Demo.
Place a command button on Form1 and write the following code in its click event.
Msgbox “India Jindabadh”
Save the Form1 and PackDep_Demo project in a separate folder say PDDemo.
This section shows how to package the PackDep_Demo application in the sub folder
Setup of the folder PDDemo.
390 Centre for Information Technology and Engineering, Manonmaniam Sundaranar University
Package and Deployment
This will display Package and Deployment Wizard as in Figure 27.2. Figure 27.2
Package and Deployment Wizard in ready mode to Package and Deploy active
project PackDep_Demo.
Note: As this Wizard is launched from the Visual Basic IDE the current project is
selected automatically for Packaging and Deployment. If this Wizard is
launched as a stand-alone component i.e., via start button and Visual Basic sub
menu, it will prompt to select a project.
Click Package icon. This will immediately go to the next step unless the active
project is already compiled. Otherwise the Wizard will ask to compile as shown in
the following figure.27.3
Figure 27.3 Wizard asking to compile the active project or to locate the
executable file of the active project.
Centre for Information Technology and Engineering, Manonmaniam Sundaranar University 391
Advanced Visual Basic
After the Wizard compiles the project will prompt to choose the package type
as shown in the following figure.
In this step the Wizard will prompt to choose a folder to assemble the
package. Click New folder button and enter Setup as name of the new folder
that is created as sub folder to the PDDemo folder as shown in the following
figure 27.5 and click Next.
Visual Basic applications consist of more files than just the executable. The next
dialog lists the files that need to be installed with the executable. This dialog
provides a Add button to include other files such as .mdb (database file),
.hlp,(help file) etc. As there are no such files for this case, simply click Next.
This step deals with the size of .cab files by providing two options – Single Cab
file and Multiple cab files (Figure 5.21). If the package is to be distributed by
floppy disks then multiple cab files option must be chosen and cab size no
392 Centre for Information Technology and Engineering, Manonmaniam Sundaranar University
Package and Deployment
longer than the floppy must be specified. As floppy disks are not used in this
example select Single Cab file option and click Next.
Note: If the package type Internet Package then instead of .cab file .htm
file will be created which can be used to download the package
using a Web browser such as Internet Explorer.
In this step Wizard prompts to enter a title that is to be displayed while installing
the application. Enter PackDep Demonstration as shown in the following figure
27.7.
In this step the Wizard prompts to specify a location to place an icon to launch the
application. By default the Wizard has created a group with the application’s name
and then an icon as shown in the following figure 27.8.
Centre for Information Technology and Engineering, Manonmaniam Sundaranar University 393
Advanced Visual Basic
As the application has only a single icon, the standard is to create that icon under
Programs. Click PackDep_Demo group and click Remove button. And Click
New Item button and enter PackDep_Demo as the name of the application and
click OK in the dialog box that appears (Figure 27.9). And Click Next.
Figure 27.9 Dialog box that gets certain options about new icon.
394 Centre for Information Technology and Engineering, Manonmaniam Sundaranar University
Package and Deployment
In this step the Wizard enables to change the installation location for each file.
This example has only one file. But some other application may require more
files such as database (.mdb) file and they have to be installed in some sub folder.
Sub folders can be created by adding their name to the macro $(AppPath) in the
Install Location box (shown in the figure 27.10). For example to install database
files in a DBs sub folder path can be specified in the Install Location box as
$(AppPath)\DBs.
Figure 27.10 Wizard prompting to specify install location for the listed files.
As the specified directory $(AppPath) is sufficient for this example simply click
Next.
In this step the Wizard presents a dialog box (Figure 27.11) that lets to mark any
files as shared. In this example the only listed file is PackDep_Demo.exe. As
executable files can’t be a shared file simply click Next.
Note : Certain files, such as DLLs and OCXs are considered as shared files. If any these
kinds of files are added as part of the installation, they must be marked as
shared. So that, when the user uninstall the application, the shared files are
verified whether any other application uses these files. These files are removed
only if every program, which uses them, is removed.
Centre for Information Technology and Engineering, Manonmaniam Sundaranar University 395
Advanced Visual Basic
In this final step of packaging process the wizard prompts to enter a script
(explained shortly) name under which settings of the current session are saved.
Simply accept the default script name (shown in the following figure- 27.12) and
click Finish.
In the package method itself, an application can be packaged to a floppy disk and
network drive straight away. The main disadvantage in this method is that if
another copy is required in a floppy disk then the entire application must be
repackaged. So fist the package method is used to package the application and the
deployment method is used to make multiple copies. Moreover deploying the
package in a web site is possible only in the Deployment method. This section
shows how to deploy the PackDep_Demo application in a new folder.
Choose Deploy icon in the Package and Deployment Wizard. This present a dialog
as in Figure 27.13.
396 Centre for Information Technology and Engineering, Manonmaniam Sundaranar University
Package and Deployment
If an application has more than one package created with different settings or by
different package types then the Package to Deploy combo will list their
corresponding script names. From this list desired package can be selected for
deployment. For the PackDep_Demo application there is only one package with
the script name Standard Setup Package 1 and it is selected by default. So simply
click Next.
This step presents a dialog (Figure 27.14) to select the deployment method –
Folder or Web publishing. If Web publishing option is selected the Wizard will
permit to remove files or add more files for deployment. Then the Wizard will
prompt to enter an URL (Unified Resource Locator – a Web site address) to
deploy the files. As this example is going to deploy the files in a new folder
select Folder option and click Next.
In this step the Wizard will prompt (Figure 27.15) to select a folder to
deploy the files. Select a path and create a new folder PackDep_App and
click Next.
Figure 27.15 Wizard prompting to select folder to deploy the packaged files.
Centre for Information Technology and Engineering, Manonmaniam Sundaranar University 397
Advanced Visual Basic
In this final step the Wizard will ask a script name to store the current session
(deployment session) settings as in the final set of packaging session. Accept the
default name and click finish.
After the wizard finishes deployment process, it generates a report about what
was accomplished. Read the report and then click Close on the report and the
wizard
• When creating standard and Internet packages, the Package and Deployment
Wizard can also be used to create dependency files. Dependency files list the run
time components that must be distributed with the application’s project files.
• The Internet Package option will appear in the Package Type list for the ActiveX
Projects only
• Standard package and Increment package are two kinds of application packaging
wizard.
Create a Setup program to install the following utility which displays date and time
In the text box whenever user presses the button.
398 Centre for Information Technology and Engineering, Manonmaniam Sundaranar University