Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 219

lOMoARcPSD|27913987

B.Com CA - Software Development with VB-217 97

Software engineering (Bharathiar University)


lOMoARcPSD|27913987

B.Com. (C.A.)

Third Year
Core Paper No14
SOFTWARE DEVELOPMENT
WITH VISUAL BASIC
lOMoARcPSD|27913987

(Syllabus)
B.Com. (Computer Applications) – III Year
Core Paper-14 SOFTWARE DEVELOPMENT AND
VISUAL BASIC

Objectives : To enable the students to develop a front end tool for Customer
Interaction in Business.

UNIT – I
Introduction – Client/Server – Benefits of Client/Server – Downsizing – Upsizing-
Right sizing – Client/Server Models – Distributed Presentation – Remote
Presentation – Remote Data – Distributed Logic – Distributed Data –
Client/Server Architecture – Technical Architecture – Application Architecture –
Two Tier Architecture – Three Tier Architecture OLTP & n Tier Architecture.

UNIT – II
Introduction to Visual Basic – Steps in VB Application – Integrated Development
Environment (IDE) – Menu Bar – Tool Bar – Project Explorer Window – Property
Window – Toolbox – Properties, Methods and Events – Event Driven
Programming – Working with Forms – Variables – Scope of Variables –
Constants – Data Types.

UNIT – III
Functions – Procedures – Control Structure : If – Switch – Select – For – While
– Do While – Arrays – User Defined Data Types – Data Type Conversions –
Operators – String Functions – Data and Time Functions.

UNIT – IV
Creating and Using Standard Controls : Form, Label, Text box, Command
Button, Check Box, Option Button, List Box, Combo Box, Picture Box, Image
Controls, Scroll Bar – Drive List Box – Directory List Box – Time Control, Frame,
Shape and Line Controls – Control Arrays – Dialog Boxes – Single Document
Interface (SDI) – Multiple Document Interface (MDI) – Menu – Menu Editor –
Menu Creation.

UNIT – V
Data Controls – Data Access Objects (DAO) – Accessing and Manipulating
Database – Recordset – Type of Recordset – Creating a Recordset – Modifying,
Deleting Records – Finding Records – Data Report – Data Environment – Report
– Designer – Connection Object – Command Object – Section of the Data Report
Designer – Data Report Controls.

2
lOMoARcPSD|27913987

CONTENT

Lessons PAGE
No.
UNIT
I
1 Client Server Technology : An Introduction 4

UNIT
II
2 Introduction to Visual Basic 35

3 Integrated Development Environment (IDE) 42

4 Methods and Events 51

UNIT
III
5 Functions 72

6 Define Control Structures 81

7 Arrays 102

8 Operators 110

UNIT
IV
9 Using Standard Controls 122

10 Other Controls 141

11 Timer Controls 152

UNIT
V
12 Using Data Controls 166

13 Record Set 184

14 Data Report 193

3
lOMoARcPSD|27913987

UNIT - I
LESSON-1
CLIENT SERVER TECHNOLOGY : AN
INTRODUCTION

INTRODUCTION

The term client/server was first used in the 1980s in reference to personal computers (PCs)
on a network. The actual client/server model started gaining acceptance in the late 1980s.
The client/server software architecture is a versatile, message-based and modular
infrastructure that is intended to improve usability, flexibility, interoperability, and
scalability as compared to centralized, mainframe, and time sharing computing .
Client/server describes the relationship between two computer programs in which one
program, the client, makes a service request from another program, the server, which
fulfils the request.
Although programs within a single computer can use the client/server idea, it is a more
important idea in a network. In a network, the client/server model provides a convenient
way to interconnect programs that are distributed efficiently across different locations.
Computer transactions using the client/server model are very common.
For example, to check your bank account from your computer, a client program in your
computer forwards your request to a server program at the bank. That program might in
turn forward the request to its own client program that sends a request to a database server
at another bank computer to retrieve your account balance. The balance is returned back to
the bank data client, which in turn serves it back to the client in your personal computer,
which displays the information for you.

Nearly all the major online information and e-commerce services (sites such as
Amazon.com, eBay, Yahoo, MSN, and more) follow the client-server file sharing model.
On a smaller scale, most campus services (such as NetFiles, Express Email, Illinois
Compass, and Banner) also follow the client-server file sharing model.

4
lOMoARcPSD|27913987

DEFINITIONS

There are a variety of definitions for the term client/server.


The client/server system is defined in terms of individual pieces that work together as a
whole and viewed as a system that integrates hardware, software, and networking. This
integration of technology is specifically designed to share resources, in support of one or
more business functions, in multiple locations simultaneously.

As an example is the Internet itself is the world9s largest client/server system. This
client/server system is comprised of thousands of clients and servers transferring
information and supporting millions of business functions across a network that spans the
globe.

ADVANTAGES OF CLIENT/SERVER ARCHITECTURE

The client/server model is particularly recommended for networks requiring a high degree
of reliability, the main advantages being:
 centralised resources: given that the server is the centre of the network, it can
manage resources that are common to all users, for example: a central database
would be used to avoid problems caused by redundant and inconsistent data
 improved security: as the number of entry points giving access to data is not so
important
 server level administration: as clients do not play a major role in this model, they
require less administration
 scalable network: thanks to this architecture it is possible to remove or add clients
without affecting the operation of the network and without the need for major
modification

DISADVANTAGES OF THE CLIENT/SERVER MODEL

Client/Server architecture also has the following drawbacks:


 increased cost: due to the technical complexity of the server
 a weak link: the server is the only weak ling in the client/server network, given that
the entire network is built around it! Fortunately, the server is highly fault tolerant
(primarily thanks to the RAID system)

CLIENT/SERVER SYSTEM OPERATION

A client/server system operates as outlined in the following diagram:

5
lOMoARcPSD|27913987

 The client sends a request to the server using its IP address and the port, which is
reserved for a particular service running on the server.
 The server receives the request and responds using the client IP address and port .
 Every client/server systems consists of at least one of each of the following:

A client that requests information;


A server that supplies information;
A network that transfer information between the client and the server;

The client component of the client/server system can be either hardware or software. In
the hardware context, a client is the personal computer functioning as a workstation.
This client workstation is capable of stand-alone information processing, which
distinguishes it from its mainframe predecessor, the dumb terminal. In the software
context, a client is the software that allows to interact with the information residing on the
server. Web browsers are examples of software clients, as are email programs (Orifaldi 1996).

The server component can also considered both hardware and software.
As hardware, the server is typically a personal computer or workstation with enhanced
storage capacity.

Often, it resides in the same location as the business activity it is required to support.
As software, servers have a variety of incarnations, depending on the operational
function. For example, windows NT Server acts as a secure server, allowing users to
share files and printers over a network. Web servers like Microsoft9s Information Server
provides access to and delivery of information over the World Wide Web (Martin 1997).

MOST CLIENT- SERVER SYSTEMS HAVE THE FOLLOWING


DISTINGUISHING CHARACTERISTICS

1. Service: client-server is primarily a relationship between processes running on


separate machines. The server process is the provider of services. The client is a
consumer of services. In essence, client-server provides a clean separation of
function based on the idea of service.
2. Shared resources: a server can service many clients at the same time and regulate
their access to shared resources.

6
lOMoARcPSD|27913987

3. Asymmetrical protocols: there is a one-to-one relationship between clients and


servers. Clients always initiate the dialog by requesting a service. Servers are
passively waiting on requests from the clients.
4. Transparency of location: the server is a process, which can reside on the same
machine as the client or on different machine across the network. Client-server
software usually masks the location of the server from the clients by redirecting the
service calls when needed.
5. Mix and match: the ideal client-server software is independent of hardware or
operating system software platform. One should be able to mix and match client and
server platforms.
6. Message-based exchanges: clients and servers are loosely coupled systems which
interact through message passing mechanism. The message is the delivery
mechanism for the service requests and replies.
7. Encapsulation of services: the server is a specialist. A message tells a server what
service is requested and it is up to the server to determine how to get the job done.
Servers can be upgraded without affecting the clients as long as the published message
interface is not changing.
8. Scalability: client-server systems can be scaled horizontally or vertically.
Horizontal scaling means adding or removing client workstations with only a slight
performance impact. Vertical scaling means migrating to a larger and faster server
machine or multi-servers.
9. Integrity: the server code and client code is centrally maintained, which results in
cheaper maintenance and the guarding of shared data integrity. At the same time, the
clients remain personal and independent.

In a client/server system, the network is the glue that binds the various pieces of hardware
and allows the sharing of data and information. Networks are generally considered
hardware, as they provide a physical link between clients, servers, printers, and other
shared resources. In addition, in cases where networks are required to link and facilitates
interaction between varying vendor-specific resources, middleware may play a role in
supporting network functionality.

Middleware, as the name implies, is the piece of hardware or software placed between
two different technologies to allow the two technologies to interact with each other. In the
context of client/server systems, middleware has a variety of incarnations;however, the
two most common are:
Network Middleware
which handles message routing between different platforms;

Database Middleware
which handles the translation of data request into database commands.

7
lOMoARcPSD|27913987

Client/server information systems architecture must serve three purposes:


1. Respond to the organization9s need for easy information access, flexibility, smooth
administration, reliability, security and proficient application development;
2. Utilize current. installations of hardware, software and networks, which often run
mission-critical applications that cannot be compromised;
3. Anticipate future demands on information systems and networks;

Client/Server computing. systems come under the broad category of system architectures
known as “Open Systems Architecture=. In an open systems environment, hardware and
software from different vendors are interchangeable and can be combined into an
integrated working environment.

Two important concepts in open systems are Interoperability and Interconnectivity.


Interoperability - means that open systems can exchange information meaningfully with
each other even when they are from different vendors. For example, manufacturing relies
on VAX/VMS, Accounting runs of the IBM 3090 mainframe, sales and marketing use.
OS/2 server running Netware (Network Operating System) on a Token Ring network and
top management and corporate planning need real time data from all three on their PCs
and Macintoshes. Interoperability is at the software application level.

Interconnectivity - refering to the ability to connect computers from possibly different


vendors, is an integral part of interoperability. Interconnectivity is at the hardware level.

CLIENT SERVER CONFIGURATION

Although the client/server idea can be used by programs within a single computer, it is a
more important idea in a network. In a network, the client/server model provides a
convenient way to interconnect programs that are distributed efficiently across different
locations. Computer transactions using the client/server model are very common.

You can take the example of your bank account - To check your bank account from your
computer, a client program in your computer forwards your request to a server program at
the bank. That program may in turn forward the request to its own client program that
sends a request to a database server at another bank computer to retrieve your account
balance. The balance is returned back to the bank data client, which in turn serves it back
to the client in your personal computer, which displays the information for you.

Client/server networking, however, focuses primarily on the applications rather than the
hardware. The same device may function as both client and server; for example, Web
server hardware functions as both client and server when local browser sessions are run
there. Likewise, a device that is a server at one moment can reverse roles and become a
client to a different server (either for the same application or for a different application).

8
lOMoARcPSD|27913987

What are the applications of Client/Server model?


As you all know some of the most popular applications on the Internet follow the
client/server design like:
• Email clients
• FTP (File transfer) clients
• Web browsers
Each of these programs presents a user interface (either graphic- or text-based) in a client
process that allows the user to connect to servers. In the case of email and FTP, the user
enters a computer name (or sometimes an IP address) into the interface to set up future
connections to the server process.

For example, an Earthlink subscriber enters the name smtp.earthlink.net into the
configuration settings of their email client to allow them to send messages over the
Internet. In the case of email, a person generally enters the server information only one
time, as the server side of the connection rarely changes.

When using a Web browser, the name or address of the server appears in the URL of each
request. Although a person may start a Web surfing session by entering a particular server
name (such as www.yahoo.com), the name regularly changes as they click links on the
pages. In the Web model, server information is provided by the HTML content developer
encoded in the anchor tags.

9
lOMoARcPSD|27913987

Client/server systems can be configured in a variety of ways, depending on what is going


to be accomplished. These different configurations are called client/server system
architectures, the most common of which is the two-tier and three-tier architectures.

ADVANTAGES OF CLIENT SERVER MODEL


Resource Sharing
Communication
GroupWare
Management Control
Reduced Costs - downsizing
Support business environmental changes
Improved Information Accessbility
Faster/Better Information
Open Architecture - Compatibility Issues
Empowered Users

Benefits and risks

Client-server file sharing has both unique benefits and unique risks.

Benefits of client-to-server file sharing

Central administration and security: Both for system administrators and for system
users, the client-server model of file sharing means that there's only one system (or group
of systems) responsible for the data distribution, and usually a professional system
administrator (or team of administrators) deals with the security issues.

Unlike system-native file sharing, where every user needs to be his or her own security
officer and set file permissions on every share, client-side users typically don't have to
change any security settings in order to access files on the server or post files for
distribution from the server. The security design is taken care of by the server's
administrators. Users simply need to make sure their connection to the server is secure, by
using encryption methods such as SSL, SSH, and the like. Then the server sends the files
(applications, web pages, etc.) over the secure connection to the client who wants the
information.

NetFiles, Express Email, Illinois Compass, Banner, and many more server-based file and
data sharing services automatically require users to make secure connections. If you're
using any of these systems, you've already taken care of the encryption you need, because
you aren't allowed to connect without it. The encryption ability may be built into your web
browser, your email client, or another piece of software required for access.

10
lOMoARcPSD|27913987

Risks of client-server file sharing

Single target for attacks: Because a client-server model transfers most of the security
responsibilities to the central server, most of the security risks focus on the server as well.
If a password database is compromised, or if a file is infected with a virus, security
problems can arise for the users who store their passwords in the database or download
infected files. In addition, the client-server file sharing model is more vulnerable to denial-
of-service attacks. Since everyone knows that the data comes from the central system,
attackers can overload the system with fake requests for information and slow the system
to a halt.

Not all systems are well secured: Although many systems require the use of encryption
to protect your password and your communications with the server, not all systems are
designed this way. Some web sites store passwords unencrypted, send them to you in
unprotected email for your records, or simply assume that security isn't required. For
example, many chat, blog, forum, and other noncommercial sites assume that since no
money is changing hands, password security isn't as important as it would be to a bank or
online store. If you reuse passwords in more than one location, a compromise of a forum
password can make your other accounts vulnerable.

Downsizing

The process of moving an {application program} from a {mainframe} to a cheaper


system, typically a {client-server} system.

The clear definition of downsizing are given below :


1) Converting mainframe and mini-based systems to client/server LANs.

(2) To reduce equipment and associated costs by switching to a less-expensive system.

With few exceptions, mainframe sites are either considering, or are in the midst of,
downsizing from their mainframes. It is rare nowadays to find a reference to mainframes
in the press that does not state that they are obsolete, expensive, and doomed to extinction
in the near future. Because of this negative notion, there is much talk about downsizing
from mainframes to smaller systems.
Undoubtedly, there is a strong increase in the number of new applications being developed
in client/server technologies. There are many situations when an IS department might
develop a new application on a client/server platform.

In a 1993 survey conducted by the big-six accounting firm Deloitte & Touche and
published in Computerworld, a poll of more than 400 CIOs showed that 27% of their
applications were on a client/server platform, up from 5% in 1992. And, a 1994 survey
conducted by the same firm on the same CIOs indicated that 43% of their applications
were on a client/server platform, up significantly from 27% in 1993. The survey did not
take into account the size of these applications --- but just the number of applications.

11
lOMoARcPSD|27913987

This survey, though, also showed a distressing conclusion. The 1993 average IS budget
only rose by 0.04%. However, companies making use of client/server technologies in
1993 saw jumps of 9%. And in 1994, companies with more than 25% of applications on
client/server saw jumps of 16%. What this means, according to the person who headed
the study, is that < client/server is not cheaper. When you are making a commitment to
client/server, you are making a dollar commitment.=

This was no surprise to many people. For example, Rose Taylor, the general manager of
planning and architecture at Chevron, said that <Many outside consultants and companies
are selling client/server as the latest and greatest thing to solve all your problems.=
Charles Popper, the CIO for Merck & Co., indicated that < the dissatisfaction we9ve seen
relates to the cost of client/server.= Steve Pliskin, a principal at Deloitte & Touche,
articulated that <They [the industry] sold an awful lot of technology before its time.=

THE TRUE COST OF MAINFRAMES

MIPS

A large mainframe, with hardware and software, can cost between £10 to £20 million
pounds. The most expensive IBM-compatible Pentium-based PC can be purchased for
less than £10000 pounds. It would be naive to say that PCs are 1000 or 2000 times more
productive than mainframes. What is needed is a more common yardstick of computer
effectiveness by which systems of all sizes can be compared.

Processing speed, or the rate at which a computer can process instructions, is one possible
measure. Dividing the cost of the computer by its MIPS rating would seem a convenient measure
of effectiveness. A large mainframe running at 220 MIPS costing £8 million pounds will have a
cost- per-MIPS of £36,000. A PC on the other hand, might have a cost-per-MIPS rating of
£100. Clearly, in this measure the mainframe would have a disadvantage.

However, MIPS for years has stood for Meaningless Indicator of Processing Speed in our
computing industry. Computers of different designs do not have the same criteria
regarding which instructions should be counted in calculating MIPS ratings. And some
designs have rich instruction sets, whereas RISC-based processors have a small set of
simple instructions. MIPS is not a sensible measure of processing speed, even when
comparing systems of similar design.

Data Handling
For most organizations, the work is data-intensive rather than processor-intensive, where
relatively simple operations are applied to very large amounts of data. The calculations
for producing an invoice or airline seat reservation are trivial, but a lot of data has to be
retrieved, updated, and stored. Mainframes are specifically designed for data-intensive

12
lOMoARcPSD|27913987

work, with very sophisticated data-handling routines - nowadays performed by multiple


dedicated processors in the central processing box and the peripheral devices attached to it.
In practice, most mainframe shops are data rich, and MIPS poor --- that is, they control
very large amounts of data with a relatively modest amount of processing power. In a
survey by IBM of 807 installations, it was found that the mainframe typically had 3
gigabytes of data per MIPS, UNIX minis a fifth of a gigabyte, and a tenth of a gigabyte for
PCs.
It is easy to make a case that the amount of data managed by the computer is of greater
practical significance than speed at which the computer can perform a million additions or
subtractions. Most organizations have massive files that need to be accessible. And by
that measure, mainframes have as clear an advantage over minicomputers as
minicomputers ostensibly have over mainframes in terms of MIPS.

User Effectiveness
Data handling speed is not an entirely satisfactory measure of a computer's effectiveness
for an organization. What really matters is the number of users, performing whatever
functions are necessary to the organization, that a computer can support with a reasonable
level of service. If this criterion is accepted, then the key measure of a computer's
effectiveness is the total cost per user over a reasonable span of time - say, five years.

The costs of computing can be divided into three categories:


 hardware, including printers, operating software, terminals. This has to include the
cost of maintaining hardware over that period.
 applications software, including off-the-shelf packages and customized programs to
allow the computer to do useful work.
 personnel costs associated with operating the hardware and software. This includes
time wasted waiting for the computer system.

In the hardware category, we will look at numbers comparing an IBM ES/9021 and IBM
ES/9021-520 (equivalent of an IBM 3090-600J) versus an HP 8XXS, running UNIX,
capable of supporting 200 users. Here are the calculations for the basic hardware,
software, and maintenance costs over five years for these two systems. These numbers
exclude finance charges and inflation. The estimate for per user cost:
IBM - £1545 to £2236; HP - £1680 to £2240
These are based on a workload of commercial applications and office systems, and assume
that 60% of users are active at any time, and that each active user interacts with the
computer every 45 seconds.
These figures make no allowance for batch processing. Most sites use the overnight shift
to reorganize files to improve on-line performance during the day. Mainframes are the
undisputed masters of batch processing, while on-line networks are only active during
office hours. However, due to the difficulties in quantifying batch processing in terms of
effectiveness, it was decided to leave out the benefits of batch processing altogether.
Besides, the concept of 8batch9 is foreign to most client/server platforms.

13
lOMoARcPSD|27913987

Applications Software

For the IBM mainframe, the study used a ratio of one programmer for every ninety users.
For an installation of 6690 users, that equates to a 75-member development staff, which at
£25,000 a year, works out to £280 per user, or £1440 over five years.
The study concluded that it was likely that the cost for downsized platforms using
packaged software would be less --- say £200 per year, or £1000 over a five-year period.
Many packages are available for the mainframe also, but most large organizations,
particularly those that use computers to gain a competitive advantage, regularly pay a
premium for tailored software. The Japanese, in particular, are very averse to off-the-shelf
software; and clearly, they have not suffered competitively as a consequence.
So in terms of application software, downsized platforms have an advantage over
mainframes. However, the study based its numbers on the HP specifications that called
for an user response time of 2-4 seconds, which is a common criterion for downsized
platforms. Mainframes, on the other hand, are generally configured for sub-second
response times. It was estimated that downsized configurations capable of supporting 50-
60 users would cost at least £2500 more per user over a five-year period. Today, even the
largest client/server platform cannot support 200 concurrent on-line users with sub-second
response time. IBM's marketing literature for client/server platforms classifies
configurations supporting more than 25 users as 8large systems.9 An under-figured
system, although cheaper, will carry a cost penalty.

Personnel

Let9s look at personnel costs. All computers require some human supervision, except
Commander Data of the starship Enterprise. The costs of running mainframes are very
visible; operators and systems programmers who do nothing but administer the
mainframe. Current mainframe configurations require one technician for every two
mainframe MIPS, which, at an average employment cost of £30,000, suggests a total of
£1.875 million in salaries for a 125-MIPS IBM mainframe to support 6690 users. That
would amount to £1401 per user over a five-year period.

For downsized platforms, fewer technical staff are required because these systems do not
normally operate 24 hours a day, like mainframes are expected to do. The study estimated
a cost for operators of £75 per user per year, or £375 for a five-year period. However, it is
estimated that one full-time specialist is required to support every 80 users in a typical
client/server environment. If the specialist costs £24,000 a year to employ, this computes
to a five-year cost of £1500 per user. The total cost for a downsized platform, is £1875
for the 5-year period.
For PC LANs, the numbers are even worse. It is estimated that the average PC user
spends two hours a week, or 25 minutes a day, either tending to the system or waiting for
a response from it. KPMG Peat Marwick estimated a cost for PC support as £6212 per
user for each year for support.

14
lOMoARcPSD|27913987

Do you really know the cost of PC support? A survey published in PC Magazine


compared the actual component costs of PCs with the costs perceived by their users. The
results are as follows:

Perceived % Actual %
Hardware 60 20
Software 20 10
Supplies 5 5
Maintenance 5 5
Outside Help 5 15
Support 5 45

In other words, outside help and internal support cost sixteen times more than the users
suspect, relative to the hardware and software.
White-collar productivity in the United States, which has the world9s highest per capita
penetration of PCs, increased by just 0.2% in the last decade. Japan, which has the lowest
penetration of PCs of any developed country, recorded a far higher productivity growth.
A study published in Information Week found:

=...[there is] a negative relationship between the proportion of users who have PCs and IS
effectiveness. Highly effective IS organizations have fewer PCs per worker than
ineffective ones.=

Dinosaur Study Totals

In addition to what We have summarized above, the 8Dinosaur9 paper presented a variety
of cost factors. The final totals are indicated in the table below:

Cost Range
IBM Mainframes £5285 to £5973
Proprietary Minis £7306 to £7786
UNIX Minis £7180 to £7740
PCs on LANs £9400 to £15,500

As you can see, the final numbers are even more skewed towards giving mainframes the
advantage over downsized platforms.
In a separate study, published in the IBEX Bulletin, MIS managers were canvassed for the
total cost and number of users for the different types of systems they use. This study came
up with the following numbers:

15
lOMoARcPSD|27913987

Type Cost
AS/400 $6795
Proprietary Minis $6667
UNIX Minis $5000
Mainframes $4800
PC LANs $3571

The Hidden Costs of Downsizing


Here are additional concerns of downsizing.

Data Integrity
Mainframes have a very high level of data integrity. When a mainframe database crashes,
data is restored to pre-abend state. Over 95% of mainframe crashes result in no significant
data loss. Contrast this with the typical minicomputer or PC environment, where it's often
left to the user to back-up before going home.

Decentralization
Can your organization live with decentralized control? Downsizing is typically
accompanied by de-centralizing of data. With the mainframe, there is no question about
who is responsible for systems administration, data security, backup, recovery, and other
data center functions. But client/server environments often have no central point of
control. Client/server involves a whole new world of maintenance. Even simple tasks
such as software upgrades can become nightmares without sufficient support.

Partitioning
With the mainframe, applications are always placed on the server. But with client/server
technologies, knowing how to partition application logic among client and server nodes
can be very confusing. Typically, database-intensive logic is placed on the server, while
activities requiring user interaction, such as querying and report writing, are on the client.
Once your partitioning is hard-coded in this fashion, it can be very difficult to change
short of a complete application rewrite.

Client/server is saddled with the mainframe. Why? The principal problem is distributed
database software. It has evolved too slowly during the past decade. Distributed backup,
security, and systems management compound the problem. Like it or not, corporate-wide
data will remain centralized for the rest of the decade.

Staff Morale
Little consideration is generally given to the IS professional9s emotional well-being, as
staff can undergo trauma while transitioning to new platforms. With mainframes, you
might tweak your database to suit certain situations. But that is nothing compared to the
range of things you can do in the UNIX world. Every company knows the expense and
frustration of hiring a competent UNIX administrator. You need someone both

16
lOMoARcPSD|27913987

technically competent and able to work with little supervision, two fairly difficult traits to
assess in the fresh-from-college applicants who are the only ones likely to be interested in
what you9re willing to pay. Those field-proven UNIX administrators seem to have
lucrative consulting careers and are able to name their price. Will management be patient
during the learning process? Will there be any mentors?

The new software technologies are utterly different. For instance, in procedural languages
you break down work-flow and code it. With the newer object-oriented languages, you
break down events and assign attributes to objects without really considering work-flow.
To take a programmer from the mainframe world and into the client/server world, takes a
certain amount of training, mentoring, and experience to pull off the transition. Of course,
if you have solid skills, the transition should not be that difficult. But when you take that
step into a new environment, you go back to the starting point. You have to understand
that you will be frustrated for a while and just accept it.

New Skills and Training


It is generally easy to re-train people who show that they really want to do it, but what
about the others? Do you force-fit them into a new role? For many, it is either a matter of
learning new client/server skills, or finding an employer who appreciates the old skills.
PowerBuilder contrives an image that developing systems is just a matter of drawing
screens and creating icons. Uh-uh - you still have to consider user feedback, the initial
needs of a GUI style-guide, understanding object-oriented concepts such as classification
and inheritance, and learning C.

Transition costs training. Here are some numbers published by Forrester Research, Inc., a
Cambridge, Massachusetts consultancy. These costs include training and lost productivity:

 cost to train a central IS person to learn a new infrastructure: $35,000 to $50,000


 cost to train a developer to work on new platforms: $25,000 - $40,000
 weeks of class time for each central IS person: 10
 weeks of class time for each developer: 5
 months of reduced productivity for each central IS person: 4+
 months of reduced productivity for each developer: 2

And Wait! There are many other items to consider.

The Orange County Appraiser's Office, in Orlando, Florida, came up with a list of
essential questions after conducting a two-year downsizing effort. These are some of the
essential questions they considered:

 Money-What can be spent for hardware, software, and project costs?


What is the anticipated return of investment, and over what time period?
 File Sizes What is the size of the current databases? Will it shrink during migration?

17
lOMoARcPSD|27913987

 Databases What impact will your prior database have on your new selection?
 Batch What are the batch processing time windows?
Will the completely migrated system fit into these windows?
 OLTP Does the on-line transaction rate meet the minimum standard of
performance for screen transactions, such as a half to full second
response time?
 Printing Can mainframe benchmarks be met or exceeded?
 Maintenance Will costs drop from the associated mainframe platform, and by how
many percent? Aim for a minimum decline of 30% as a first-year target.
 Network Can the network handle both the downsized and legacy systems as well?
 Hardware Can workstations be upgraded to the optimal 486s with eight meg of
Ram?
PC upgrades are perhaps not an issue to private companies, but for state governments with
ever-shrinking budgets, this is a definite issue.

UPSIZING
Upsizing is the term coined by Microsoft to describe the process of upgrading Microsoft
Access Database to a Microsoft SQL Server. This allows to continue using Microsoft
Access as a database front-end whereas the actual back-end is served by a separate local or
remote SQL Server allowing much higher productivity and data volumes. Microsoft
Access from the version 2000 on has a special Upsizing Wizard which facilitates the data
migration to the proprietary Microsoft SQL Server. No other RDBMS are currently
supported for upsizing.

Upsizing strategies
There are two strategies how database can be migrated from Access to a SQL Server.
1. Using ODBC from Microsoft to get access to a remove database via ADO.
2. Using Access Projects (available in Microsoft Access 2000 and higher) which allow
more "native" integration with Microsoft SQL Server.
The first strategy is often seen as the first step towards complete migration on a SQL
server on the stage 2[1], and can be seen as a part of the strategy 2. For peculiarities of
every strategy see the table.
Parameter Strategy 1 Strategy 2
Database Via ODBC using ADO, Native integration with Microsoft SQL Server
access somewhat slower than using Access Project (.adp), data access using
strategy 2. ADO
Can be integrated with
Integration (almost) any RDBMS Native support only for Microsoft SQL Server

18
lOMoARcPSD|27913987

Serves as database front-end with limited


Serves as database front-
functionality. Local tables are not allowed[2].
The role end with full features of
Querries are generally transformed into database
of Microsoft Access JET
views, VBA code manipulating the data is
Access Engine and VBA.
transformed into procedures stored on server.
(compare to thick client)
(compare to thin client).

Performing the upsizing


As any data migration procedure Microsoft Access database upsizing requires
fundamental refactoring of the database structure and source code. Even though some
aspects of this procedure seem to be automatized by the Upsizing Wizard, there are still
many points requiring human intervention. Following changes have to be done on
upsizing
1. Complete change of data access interface from DAO to ADO.
2. Substantial change of Microsoft JET SQL to Transact-SQL.
3. Substantial adaptation of object (e.g. tables, columns etc) names.
4. Reconception of the source code to optimally employ the new functionality of ADO
and Microsoft SQL Server of the "upsized" solution.

RIGHTSIZING
The goal of Rightsizing is to determine the right platform (microcomputer/network,
Client/Server, mainframe/minicomputer) for an application. Rightsizing seeks to provide
the best blend of application performance, usability, and cost containment.

Generally, the two factors to consider when Rightsizing

(1) database size


(2) and the amount of user interaction.
If both of these factors are large, Client/Server is the appropriate platform. If the database is large
and user interaction is minimal, a mainframe/minicomputer is the appropriate platform. If the
database is small and user interaction is constant, a microcomputer/network is the appropriate
platform (although security and data integrity issues may effect this decision). If both of these
factors are small, then it really doesn't matter. Look at existing platform availability and choose
the most readily available platform.

The following Application Platform Worksheet can be used as a guideline for the selection
of the Rightsize platform. It assigns weights to the database size and the user interaction,
adds an optional amount for security & fault tolerance, then indicates the range of results
appropriate to each platform. If the application falls within a range where two platforms
overlap, then either platform can be used. Leverage the investment in existing equipment
by selecting the platform that is most readily available.

19
lOMoARcPSD|27913987

The primary goal of Rightsizing onto the mainframe/minicomputer is to leverage


existing computer resources, not to encourage the purchase of new
mainframe/minicomputer equipment. Today's Client/Server hardware technology can
provide performance and fault tolerance equivalent to all but the newest
mainframe/minicomputers, at a fraction of the cost. Client/Server's cost efficiency make it
extremely difficult to justify the purchase of a mainframe/minicomputer. The businesses
that would require the type of processing power embodied in the newest
mainframe/minicomputers are very, very few. The vast majority of businesses will easily
accomplish their business goals with Client/Server technology.

If the Application Platform Worksheet indicates the need to purchase a


mainframe/minicomputer, you should carefully review your requirements in an attempt to
avoid the purchase. In the event of a miscalculation or a change in direction, Client/Server
equipment can always we redistributed in a useful manner. Once a
mainframe/minicomputer ceases to be useful, it is a net loss. The organizations buying
used mainframe/minicomputers have become few and far between, and salvage for scrap
metal is a painful way to dispose of a mainframe/minicomputer.
Businesses usually discover that the Rightsizing process tends to move strategic applications
from the mainframe/minicomputer onto Client/Server platforms. This migration frees
expensive resources on their existing mainframe/minicomputer, allowing them to leverage
their current mainframe/minicomputer investment and avoid expensive upgrades.
Some businesses, after Rightsizing their strategic applications, determine that they can
completely eliminate the mainframe/minicomputer, eliminating existing maintenance
contracts, and actually reducing their ongoing operating expense.
The initial step is to Rightsize all new applications. Their tendency towards Client/Server
will ease the load on the mainframe/minicomputer, allowing its existing backlog of
requests to be serviced, and heading off any expensive upgrades that would have
otherwise been necessary. As the personnel gain experience with the Client/Server
environment, they can start Rightsizing existing applications, with an eye towards
enhancing business capabilities and reducing ongoing operating expenses.

CLIENT-SERVER COMPUTING
The client-server vision
It is a vision of individual personal computers being used as "clients" in the client-server
computing paradigm. This paradigm had its origins in local area networks where client
machines and server machines cooperate much better than in traditional terminal-
mainframe networks. Local area networks may be 1,000 times faster than terminal-
mainframe networks and this fact alone facilitates tighter integration. At such speeds,
information can be easily distributed between client machines and server machines and yet
be presented coherently without delay or without end-user knowledge of the network
topology. Client machines in local area networks can be server machines, and server
machines can be clients, interchangeably. Every machine in the network has client and
server qualities.

20
lOMoARcPSD|27913987

The Gartner Group has defined five different styles of client-server computing.
[1] The difference in these styles depends on the portion of the computing process that is
"distributed" to an alternate computer over the network. The five styles are defined
in relation to the three main processes in a computerized application:
(1) presentation (user interface),
(2) process (application logic)
and (3) data storage (data management)
The dotted lines represent the different areas for breaking processes between the
client and server machines. There are five dotted lines, each representing another
style of client-server computing.

FIVE STYLES ARE :


1. Distributed presentation, also known as "screen scraping," for example, when you
take a 3270 screen and dress it up with a graphical user interface front end.
2. Remote presentation, when the presentation is fully disconnected from the
application logic.
3. Distributed logic, known variously as cooperative processing, peer- to-peer
processing, or remote procedure calls.
4. Remote data management, which may be implemented as SQL commands, sockets,
or remote procedure calls.
5. Distributed database, a logical database distributed over multiple hardware
platforms.
Conceptually, client-server computing is not difficult to understand, just to implement.
The implementation challenges are greater as you move up the diagram from distributed
presentation to distributed database.

Client-server computing is attractive because it allocates more than one computing


machine to a particular task. Imagine, if you will, the difference between a terminal-
mainframe application with one computer and sixty users, and a client-server application
with the same number of users but sixty-one computers (sixty personal computers for the
users and one computer for the server). In place of monolithic computing cycles on a
centralized mainframe, client-server computing shares out computing cycles to a network
of client machines and server machines.

21
lOMoARcPSD|27913987

CLIENT SERVER ARCHITECTURE

Components of the client server computing can be grouped into four categories of
architecture.
 Business solutions architecture
 Application architecture
 Platform architecture
 Technical architecture

Now we discuss application architecture briefly

Application architecture

Application architecture layer can be defined here as those services that perform business
functions on the computer. It represents the components that provide the automation
support for a business function or activity in the business process (but does not include the
platform and cross application architecture). Fro example a manufacturer9s sales and
marketing system application architecture could include sales tracking application and the
distributed data architecture to support both networked sales offices and mobile sales
people.

TECHNICAL ARCHITECTURE

Because of its relative importance in client/server implementations .The technical


architecture consists of the infrastructure and systems software layers. Discussed
previously the differentiation between them is primarily a question of make to buy that is a
key decision for organizations intent on= building an architecture is how much they want
to build Vs. how much they simply buy from preexisting sources. An organization can
choose to build a great deal, thereby making the architecture very close to what it wants.
That means that there is a great deal of logic being built by the shop.

The organization can choose to buy most of what it wants. To extent that business or
application demands make it necessary for the tools to be integrated, developers can then
do simple assembly, or gluing together, of the pieces. The decision for most organizations
depends on balancing demands. On the other hands the organization has a large front-end
commitment to build and an ongoing commitment to maintain infrastructure architecture;
on the other hand the organization has a tool that is exactly what it wants.

Over the years there has been a tendency to buy rather than make. This is especially the
case as the market matures with more technical entrants. By purchases rather building they
can then more easily apply their strong skills in the application architecture business

22
lOMoARcPSD|27913987

COMPONENTS OF A TECHNICAL ARCHITECTURE

Business solutions

Application Architecture

Infrastructure
Technical Architecture
System software

Platform

Execution development operations


Architecture Architecture Architecture

 An execution architecture describes the components required when an application


executes.
 An development architecture describes the components required to create the
execution architecture.
 An operations architecture describes the components required to operate and mange
the system.

These architectures must be flexible enough to accommodate a wide range of


technologies, but they must be also be structured enough to provide valuable guidelines
and ensure that interoperability is available where it is required.

TYPES OF ARCHITECTURE

When considering a move to client/server computing, whether it is to replace existing


systems or introduce entirely new systems, practitioners must determine which type of
architecture they intend to use. The vast majority of end user applications consist of three
components: presentation, processing, and data. The client/server architectures can be
defined by how these components are split up among software entities and distributed on a
network. There are a variety of ways for dividing these resources and implementing
client/server architectures. This paper will focus on the most popular forms of
implementation of two-tier and three-tier client/server computing systems.

23
lOMoARcPSD|27913987

2-Tier and 3-Tier Client/Server Architectures


Every client/server application contains three functional units:
 Presentation logic or user interface (for example, ATM machines)
 Business logic (for example software that enables a customer to request an account
balance)
 Data (for example, records of customer accounts)
These functional units can reside on either the client or on one or more servers in your
application. Which of the many possible variations you choose depends on how you split
the application and which middleware you use to communicate between the tiers.

Figure 1 –client server with multi level


Two-tier Architecture
Although there are several ways to architect a two-tier client/server system, we will focus
on examining what is overwhelmingly the most common implementation. In this
implementation, the three components of an application (presentation, processing, and
data) are divided among two software entities (tiers): client application code and database
server (Figure 2). A robust client application development language and a versatile
mechanism for transmitting client requests to the server are essential for a two tier
implementation. Presentation is handled exclusively by the client, processing is split

24
lOMoARcPSD|27913987

between client and server, and data is stored on and accessed via the server. The PC client
assumes the bulk of responsibility for application (functionality) logic with respect to the
processing component, while the database engine - with its attendant integrity checks,
query capabilities and central repository functions - handles data intensive tasks. In a data
access topology, a data engine would process requests sent from the clients. Currently, the
language used in these requests is most typically a form of SQL. Sending SQL from client
to server requires a tight linkage between the two layers. To send the SQL the client must
know the syntax of the server or have this translated via an API (Application Program
Interface). It must also know the location of the server, how the data is organized, and how
the data is named. The request may take advantage of logic stored and processed on the
server which would centralize global tasks such as validation, data integrity, and security.
Data returned to the client can be manipulated at the client level for further sub selection,
business modeling, "what if" analysis, reporting, etc.

Figure 2 - Data Access Topology for two-tier architecture. Majority of functional logic exists at the client
level

In 2-tier client/server applications, the business logic is buried inside the user interface
on the client or within the database on the server in the form of stored procedures.
Alternatively, the business logic can be divided between the client and server. File servers
and database servers with stored procedures are examples of 2-tier architecture.
2- tier architecture is used to describe client/server systems where the client requests
resources and the server responds directly to the request, using its own resources. This
means that the server does not call on another application in order to provide part of the
service.

25
lOMoARcPSD|27913987

The most compelling advantage of a two-tier environment is application development


speed. In most cases a two-tier system can be developed in a small fraction of the time it
would take to code a comparable but less flexible legacy system. Using any one of a
growing number of PC-based tools, a single developer can model data and populate a
database on a remote server, paint a user interface, create a client with application logic,
and include data access routines. Most two-tier tools are also extremely robust. These
environments support a variety of data structures, including a number of built in
procedures and functions, and insulate developers from many of the more mundane
aspects of programming such as memory management. Finally these tools also lend
themselves well to iterative prototyping and rapid application development (RAD)
techniques, which can be used to ensure that the requirements of the users are accurately
and completely met.
Tools for developing two-tier client/server systems have allowed many IS organizations to
attack their applications backlog, satisfying pent-up user demand by rapidly developing
and deploying what are primarily smaller workgroup-based solutions. Two-tier
architectures work well in relatively homogeneous environments with fairly static
business rules. This architecture is less suited for dispersed, heterogeneous environments
with rapidly changing rules. As such, relatively few IS organizations are using two-tier
client/server architectures to provide cross-departmental or cross-platform enterprise-wide
solutions.
Since the bulk of application logic exists on the PC client, the two-tier architecture faces a
number of potential version control and application re-distribution problems. A change in
business rules would require a change to the client logic in each application in a
corporation's portfolio which is affected by the change. Modified clients would have to be
re-distributed through the network - a potentially difficult task given the current lack of
robust PC version control software and problems associated with upgrading PCs that are
turned off or not "docked" to the network.
System security in the two-tier environment can be complicated since a user may require a
separate password for each SQL server accessed. The proliferation of end-user query tools
can also compromise database server security. The overwhelming majority of client/server
applications developed today are designed without sophisticated middleware technologies
which offer increased security. Instead, end-users are provided a password which gives
them access to a database. In many cases this same password can be used to access the
database with data-access tools available in most commercial PC spreadsheet and database
packages. Using such a tool, a user may be able to access otherwise hidden fields or tables
and possibly corrupt data.
Client tools and the SQL middleware used in two-tier environments are also highly
proprietary and the PC tools market is extremely volatile. The client/server tools market
seems to be changing at an increasingly unstable rate. In 1994, the leading client/server
tool developer was purchased by a large database firm, raising concern about the
manufacturer's ability to continue to work cooperatively with RDBMS vendors which
compete with the parent company's products. The number two tool maker lost millions
and has been labeled as a takeover target. The tool which has received some of the

26
lOMoARcPSD|27913987

brightest accolades in early 1995 is supplied by a firm also in the midst of severe financial
difficulties and management transition. This kind of volatility raises questions about the
long-term viability of any proprietary tool an organization may commit to. All of this
complicates implementation of two-tier systems - migration from one proprietary
technology to another would require a firm to scrap much of its investment in application
code since none of this code is portable from one tool to the next.

3- TIER ARCHITECTURE

In 3-tier client/server applications, the business logic resides in the middle tier, separate
from the data and user interface. In this way, processes can be managed and deployed
separately from the user interface and the database. Also, 3-tier systems can integrate data
from multiple sources.
In 3-tier architecture, there is an intermediary level, meaning the architecture is generally
split up between:
1. A client, i.e. the computer, which requests the resources, equipped with a user
interface (usually a web browser) for presentation purposes
2. The application server (also called middleware), whose task it is to provide the
requested resources, but by calling on another server
3. The data server, which provides the application server with the data it requires

27
lOMoARcPSD|27913987

Figure 3 - Three Tier Architecture. Most of the logic processing is handled by functionality servers.
Middle-tier code can be accessed and utilized by multiple clients

The three tier architecture (Figure 3) attempts to overcome some of the limitations of the
two-tier scheme by separating presentation, processing, and data into separate, distinct
software entities (tiers). The same types of tools can be used for presentation as were used
in a two-tier environment, however these tools are now dedicated to handling just the
presentation. When calculations or data access is required by the presentation client, a call
is made to a middle tier functionality server. This tier can perform calculations or can
make requests as a client to additional servers. The middle tier servers are typically coded
in a highly-portable, non-proprietary language such as C. Middle-tier functionality servers
may be multi-threaded and can be accessed by multiple clients, even those from separate
applications.

Although three-tier systems can be implemented using a variety of technologies, the


calling mechanism from client to server in such as system is most typically the remote
procedure call or RPC. Since the bulk of two-tier implementations involve SQL
messaging and most three-tier systems utilize RPCs, it is reasonable to examine the merits
of these respective request/response mechanisms in a discussion of architectures. RPC
calls from presentation client to middle-tier server provide greater overall system
flexibility than the SQL calls made by clients in the two-tier architecture. This is because
in an RPC, the requesting client simply passes parameters needed for the request and
specifies a data structure to accept returned values (if any). Unlike most two-tier
implementations, the three tier presentation client is not required to "speak" SQL. As such,
the organization, names, or even the overall structure of the back-end data can be changed
without requiring changes to PC-based presentation clients. Since SQL is no longer
required, data can be organized hierarchically, relationally, or in object format. This added
flexibility can allow a firm to access legacy data and simplifies the introduction of new
database technologies.

28
lOMoARcPSD|27913987

In addition to the openness stated above, several other advantages are presented by this
architecture. Having separate software entities can allow for the parallel development of
individual tiers by application specialists. It should be noted that the skill sets required to
develop c/s applications differ significantly from those needed to develop mainframe-
based character systems. As examples, user interface creation requires an appreciation for
platform and corporate UI standards and database design requires a commitment to and
understanding of the enterprise's data model. Having experts focus on each of these three
layers can increase the overall quality of the final application.

The three tier architecture also provides for more flexible resource allocation. Middle-tier
functionality servers are highly portable and can be dynamically allocated and shifted as
the needs of the organization change. Network traffic can potentially be reduced by having
functionality servers strip data to the precise structure required before distributing it to
individual clients at the LAN level. Multiple server requests and complex data access can
emanate from the middle tier instead of the client, further decreasing traffic. Also, since
PC clients are now dedicated to just presentation, memory and disk storage requirements
for PCs will potentially be reduced.

Modularly designed middle tier code modules can be re-used by several applications.
Reusable logic can reduce subsequent development efforts, minimize the maintenance
work load, and decrease migration costs when switching client applications. In addition,
implementation platforms for three tier systems such as OSF/DCE offer a variety of
additional features to support distributed application development. These include
integrated security, directory and naming services, server monitoring and boot capabilities
for supporting dynamic fault-tolerance, and distributed time management for
synchronizing systems across networks and separate time zones.

There are of course drawbacks associated with a three tier architecture. Current tools are
relatively immature and require more complex 3GLs for middle tier server generation.
Many tools have under-developed facilities for maintaining server libraries - a potential
obstacle for simplifying maintenance and promoting code re-use throughout an IS
organization. More code in more places also increases the likelihood that a system failure
will effect an application so detailed planning with an emphasis on the
reduction/elimination of critical-paths is essential. Three tier brings with it an increased
need for network traffic management, server load balancing, and fault tolerance.

COMPARING TWO AND THREE TIER DEVELOPMENT EFFORTS

2-tier architecture is therefore a client-server architecture where the server is versatile, i.e.
it is capable of directly responding to all of the client's resource requests.
In 3-tier architecture however, the server-level applications are remote from one another,
i.e. each server is specialised with a certain task (for example: web server/database
server). 3-tier architecture provides:

29
lOMoARcPSD|27913987

 A greater degree of flexibility


 Increased security, as security can be defined for each service, and at each level
 Increased performance, as tasks are shared between servers
Time to deployment is forecast in overall systems delivery time, not man hours.
According to a Deloitte & Touche study, rapid application development time is cited as
one of the primary reasons firms chose to migrate to a client/server architecture. As such,
strategic planning and platform decisions require an understanding how development time
relates to architecture and how development time changes as an IS organization gains
experience in c/s.

Figure 4 - Initial Development Effort


Figure 4 shows the initial development effort forecast to create comparable distributed
applications using the common two tier and three tier approaches discussed above. The
three tier application takes much longer to develop - this is due primarily to the
complexity involved in coding the bulk of the application logic in a lower-level 3GL such
as C and the difficulties associated with coordinating multiple independent software
modules on disparate platforms. In contrast, the two-tier scheme allows the bulk of the
application logic to be developed in a higher-level language within the same tool used to
create the user interface.

30
lOMoARcPSD|27913987

Figure 5- Subsequent Development Efforts


Subsequent development efforts may see three-tier applications deployed with greater
speed than two tier systems (Figure 5). This is entirely due to the amount of middle-tier
code which can be re-used from previous applications. The speed advantage favoring the
three-tier architecture will only result if the three-tier application is able to use a sizable
portion of existing logic. Experience indicates that these savings can be significant,
particularly in organizations which require separate but closely related applications for
various business units. Re-use is also high for organizations with a strong enterprise data
model because data-access code can be written once and re-used whenever similar access
needs arise across multiple applications. The degree of development time reduction on
subsequent efforts will grow as an organization deploys more c/s applications and
develops a significant library of re-usable, middle-tier application logic.

Figure 6 - Client Tool Migration

Figure 6 makes the important case for code savings when migrating from one client
development tool to another. It was stated earlier that client tools are highly proprietary
and code is not portable between the major vendor packages. The point was also made that
the PC tools market is highly volatile with vendor shake outs and technical "leapfrogging"
common place. In a two-tier environment, IS organizations wishing to move from one PC-
based client development platform to another will have to scrap their previous investment
in application logic since most of this logic is written in the language of the proprietary
tool. In the three-tier environment this logic is written in a re-usable middle tier, thus when
migrating to the new tool, the developer simply has to create the presentation and add
RPC calls to the functionality layer.
Flexibility in re-using existing middle-tier code can also assist organizations developing
applications for various PC client operating system platforms. Until recently there were
very few cross-platform client tool development environments and most of today's cross-
platform solutions are not considered "best-of-breed". In a three-tier environment the
middle tier functionality layer can be accessed by separate client tools on separate
platforms. Coding application logic once in an accessible middle tier decreases the overall
development time on the cross-platform solution and it provides the organization greater
flexibility in choosing the best tool on any given platform.

31
lOMoARcPSD|27913987

SUMMARY
In the early 1980's, ANSI, in conjunction with the University of Minnesota, defined a
three layer architecture for building portable systems. This architecture divided data
processing into presentation, processing (functionality logic), and data. This paper has
considered the role of each of these data processing layers within the framework of two
popular client/server architectures.

Two tier architectures group the presentation with most of the non-database processing in
a single client application. The robustness and ease of use of two tier development tools
dramatically decrease initial development time, however IS organizations may pay a
penalty when trying to update functionality simultaneously in a variety of systems, when
trying to integrate systems, or when trying to migrate from a proprietary development tool.
Three tier architectures split these three layers into three distinct software entities. This
architecture requires more planning and support, but can reduce development and
maintenance costs over the long term by leveraging code re-use and flexibility in product
migration. Three tier architectures are also the most vendor-neutral of the architectures
considered and thus can facilitate the integration of heterogeneous systems.

Kean (1991) pointed out that a firm's long term ability to compete is directly related to
(enabled or limited by) the reach and range provided by the firm's technical architecture.
His suggestions for defining a platform include selecting architectures which:
* protect existing IT investments
* ensure the firm's ability to adopt new technologies
* provide integration of heterogeneous resources
* accommodate emerging standards embraced by a broad base of firms.
Our discussion of popular client server architectures exposes the weaknesses in the
overwhelming majority of current client/server systems - systems employing a two-tier
architecture - as they relate to Kean's platform selection criteria. Such systems may
provide adequate work group-level systems which can be developed rapidly and employ
empowering interfaces. However, such systems lack the openness, flexibility, scalabilty,
and integration provided by three-tier systems. The case for deploying three-tier systems
will develop over time as tools mature and momentum for vendor-neutral standards
increase. A variety of research opportunities exist including examining issues in migration
from two-tier to three-tier systems, operationalizing the conceptual graphs presented here
as they relate to development time, and studying how the level of complexity in three-tier
systems acts as a barrier to its wide-spread acceptance.

32
lOMoARcPSD|27913987

ONLINE TRANSACTION PROCESSING (OLTP)

Distributed Computing can be categorized by two principal parts:


Decision Support Systems (DSS)
and On-Line Transaction Processing (OLTP) .
On one side DSS means that data is mined for trends , quick answers, and summaries. It is
less demanding of resources than OLTP. On the other hand, OLTP means the distributed
system must deliver fast, secure, reliable, and scalable results

What is OLTP?
It refers to a class of programs that facilitate and manage applications for data entry or
retrieval on a computer network. OLTP systems handle active data instantly. OLTP has
the capacity to ensure that multiple transactions are processed accurately and efficiently.
Those using this application include banks, airlines, mail-order firms, manufacturers and
retailers.

What are its applications?


Applications that use this technology include sales order processing, inventory, accounts
payable and e-commerce. When you withdraw money from an ATM or punch in a time
clock, OLTP works behind the scenes to make the system store and manage all these
transactions in real-time.
The response from an OLTP system is immediate. Large applications depend on
transaction management software such as Customer Information Control System to
process thousands or millions of updates to OLTP-oriented databases. As the records are
entered, the database is updated and the OLTP system sends a confirmation—all at the
same time. Demands on such software are high as they have to function reliably 24x7x365
on dependable computer and network systems.

What is the technology powering OLTP?


OLTP adopts a client-server or multi-tier computing model. The data updating mechanism
allows branches to operate offline and connect to it at intervals to update or retrieve
information. It can also work in an always-connected mode. The server has three
components—a hardware platform, operating system and transactional engine. As the
technology can work in online/offline mode, it can compensate for link failures and host
downtime. The software does not permit two users to change data at the same time. Also,
it does not allow a user to change information when it is being accessed by another user
until the first user finishes accessing the said information. Commonly-used offline
processing transaction processing facility sites use IBM9s Multiple Virtual Storage and
Virtual Machine operating systems.
lOMoARcPSD|27913987

What is the role of middleware in OLTP?


Transaction Processing Software uses middleware to handle infrastructural functions such
as sending data or a message from one PC to another or queuing them. OLTP is a three-
tier architecture system. A three-tier system consists of a client, application server that acts
as the middleware, and the database server. It enables higher processing speed to access
multiple databases. Some of the examples of middleware are BEA Tuxedo9s /WS and
ATMI, Encina9s Transactional RPS, and IBM9s WebSphere XD.

What are its benefits and limitations?

In an OLTP, the transactions that take place either succeed or fail it is not left incomplete.
A major benefit is that when a transaction is taking place it does not affect other
transactions taking place simultaneously. Along with the numerous advantages of using
OLTP there are some limitations too. They are configuration and version management,
and difficulty in distribution of the new updated version of OLTP or the application code
patches. It should be ensured that both the new version and the patches are loaded on
every machine. Performance may be affected if a client server system sends in a large
amount of traffic across a network. In OLTP, latency—which is the amount of time
needed to complete a single operation—and throughput often clash.

34
lOMoARcPSD|27913987

UNIT - II
Lesson – 2
Introduction to visual basic
Steps in Visual Basic application
Creating A Project In Visual Basic
The Parts Of A Visual Basic Project
Lesson – 3
Integrated Development Environment (IDE)
Menu bar
Tool bar
Form Window
Project Explorer Window
Property Window
From Layout Window
Tool box
The form designers and Code window
Help in Visual basic
Lesson - 4
Methods and events
Event Driven programming
Working with forms
Variables
Scope of variables
Constants
Data types

LESSON-2
INTRODUCTION TO VISUAL BASIC

INTRODUCTION TO VISUAL BASIC

While programming in high level languages like BASIC, Fortran, Pascal, C etc, the
programmer needs to know the sequence of operations to be performed by the program.
The program lines are added in the same sequence.
While programming in visual basic the application developer must decide how the
application interacts with the user. The user may click the mouse on various controls, or
press a key or key combination on the user interface. These are known as events. The
application developer must developer must decide how the application must react to the
user9s actions. This is called event- driven programming.

35
lOMoARcPSD|27913987

In Visual basic, the application does not determine the flow. Instead, the events caused by
the user determine the flow of the application. The applications are to be programmed to
react to various external conditions known as events. In this way, the visual basic
application, the user9s action determines the application9s flow.

In name visual basic the word <Visual <refers to the method used to create the Graphical
User Interface (GUI). Rather than writing numerous lies of code to describe the
appearance and location of interface elements, pre-built objects are simple added into
place on screen. The word <Basic= refers to the BASIC (Beginners All purpose Symbolic
Instruction Code) language, a language used by more programmers than any other
language in the history of computing.

Visual basic has evolved from the original BASIC language and now contains several
hundred statements, functions, and keyword, many of which related directly to the
windows GUI. Beginners can create useful application by learning just a few of the
keywords, yet the power of the language allows professionals to accomplish anything that
can be accomplished using any other Widows programming languages.

It9s no secret that Visual Basic is the favorite programming environment of many
programmers. When Visual Basic first appeared, it created a revolution in Windows
programming, and that revolution continues to this day. Never before had Windows
programming been so easy just build the program you want, right before your eyes, and
then run it. Visual Basic introduced unheard-of ease to Windows programming and
changed programming from a chore to something very fun.

Visual Basic, including how to create Visual Basic projects and seeing what is in such
projects. We have also get an overview of essential Visual Basic concepts like forms,
controls, events, properties, methods, and so on. And examine the structure of a Visual
Basic program, taking a look at variables, variable scope, and modules. In other words, we
re going to lie bare the anatomy of a Visual Basic program.

Visual basic introduced in the year 1991 by windows application. The term Visual refers
to Object and basic refers to codings. Visual basic follows that <A picture is worth a
thousand words=. In early days DOS is used for programming. Then they introduced the
following concepts for user convince

 GUI based application called Graphical User Interface.


 It is a user friendly.
 No need to create methods and functions.
 Build in function can be used easily.
 Multiple windows can execute at a time
The requirements for Visual basic are Pentium with 166 mhz, 32 mb Ram and 300 mb
space in hard disk to install.

36
lOMoARcPSD|27913987

Steps in Visual Basic application

Visual basic (VB) is one component of the Microsoft Studio. Visual basic can be started
by using the following steps.
Click the Start button
1. Choose programs  Microsoft Visual studio 6.0  Microsoft Visual basic 6.0
Alternatively, if one is using only visual basic straight away a click on Program 
Microsoft Visual basic 6.0 or double click on the Visual basic icon exist in your
desktop.
After Visual basic is started, the new project dialog box will appear as

The following options are available


 New
 Existing
 Recent
 Don9t show this dialog in the future

1. New - This tab enables the creation of a new project or application


choosing from an assortment to templates or wizards.
2. Existing - This tab enables the selection of an existing project displays
a windows file open dialog box.

37
lOMoARcPSD|27913987

3. Recent - This tab lists the visual basic projects that have been used
recently.
4. Don9t show this dialog in the future check box - Selecting this option will
prevent this dialog box from being displayed when visual
basic is started in the future. However, from the File  new
project menu option, one will not receive the Existing and
Recent tabs.

Whenever a project is opened or a new project is started the visual basic 6.0 Integrated
Development Environment (IDE) window will appear as follows. The IDE window
consist of following different parts of window.

1. Form Window
2. Toolbox
3. Project explorer
4. Property window
5. Form layout window

38
lOMoARcPSD|27913987

In order to see the different parts of the IDE, a new standard EXE project is created by
selecting standard Exe in the new project dialog box. This will open a new project named
as project1. Visual basic is now waiting for you to start the work on this new project.

Creating A Project In Visual Basic

There are three different editions of Visual Basic:


1. The Learning Edition, which is the most basic edition. This edition allows you to
write many different types of programs, but lacks a number of tools that the other
editions have.
2. The Professional Edition, designed for professionals. This edition contains all that
the Learning Edition contains and more, such as the capability to write ActiveX
controls and documents.
3. The Enterprise Edition, which is the most complete Visual Basic edition. This
edition is targeted towards professional programmers who may work in a team and
includes additional tools such as Visual SourceSafe, a version-control system that
coordinates team programming.

We ll use the Enterprise Edition in this book, so if you have either of the other two
editions, we might occasionally use something not supported in your Visual Basic edition.
We ll try to keep such occurrences to a minimum.

The following are the some of the project types that Visual Basic supports:

 Standard Windows EXE programs


 ActiveX EXE files
 ActiveX DLLs
 ActiveX controls
 Programs written by the Visual Basic Application Wizard
 Data projects
 IIS (the Microsoft Internet Information Server) applications
 Visual Basic add-ins
 ActiveX document DLLs
 ActiveX document EXE files
 DHTML applications
 VB Enterprise Edition controls

39
lOMoARcPSD|27913987

This list of project types indicates some of the ways Visual Basic has grown over the
years In this case; we just want to take a look at the basics of a standard Visual Basic
project, so double-click the Standard EXE item in the New Project dialog box, opening
Visual Basic Integrated Development Environment (IDE).

THE PARTS OF A VISUAL BASIC PROJECT

Projects can become quite advanced in Visual Basic, even containing subprojects of
different types. From a programming point of view, however, standard Visual Basic
projects usually contain just three types of items: global items, forms, and modules are
displayed in following diagram.

The parts of a Visual Basic project.

1. Forms
Forms are familiar to all Visual Basic programmers, of course they re the templates you
base windows on. Besides standard forms, Visual Basic also supports Multiple Document
Interface (MDI) forms.

Visual Basic project

Global Items

Forms Forms Forms

Module Module Module

2 . Modules

Modules are collections of code and data that function something like objects in object-
oriented programming (OOP), but without defining OOP characteristics like inheritance,
polymorphism, and so on. The point behind modules is to enclose procedures and data in
a way that hides them from the rest of the program. Here we cover Visual Basic

40
lOMoARcPSD|27913987

programming techniques and style; breaking a large program into smaller, self-contained
modules can be invaluable for creating and maintaining code.

The user can think of well-designed modules conceptually as programming objects; for
example, you might have a module that handles screen display that includes a dozen
internal (unseen by the rest of the program) procedures and one or two procedures
accessible to the rest of the program. In this way, the rest of the program only has to deal
with one or two procedures, not a dozen.

Besides modules, Visual Basic also supports class modules. Programming with class
modules will bring us much closer to true OOP programming.

3. Global Items

Global items are accessible to all modules and forms in a project, and you declare them
with the Public keyword. However, Microsoft recommends that you keep the number of
global items to an absolute minimum and, in fact, suggests their use only when you need
to communicate between forms. One reason to avoid global variables is their accessibility
from anywhere in the program; while you re working with a global variable in one part of
a program, another part of the program might be busy changing that variable, giving you
unpredictable results.

41
lOMoARcPSD|27913987

LESSON-3
INTEGRATED DEVELOPMENT ENVIRONMENT (IDE)

Integrated Development Environment (IDE)


Menu bar
Tool bar
Form Window
Project Explorer Window
Property Window
From Layout Window
Tool box
The form designers and Code window
Help in Visual basic

INTEGRATED DEVELOPMENT ENVIRONMENT (IDE)

The Visual basic development environment includes an assortment of menus, toolbars,


windows and other tools that help to create applications as quickly and as easily as
possible. This group of tools is collectively called the Integrated Development
Environment (IDE).

The visual basic IDE has three distinct states


1. Design
2. Run
3. Debug

The IDE consist of following types


 Menu bar
 The toolbar
 Form Window
 Project explorer
 Property window
 Form layout window
 Toolbox
 The form designers
 The code window

42
lOMoARcPSD|27913987

THE MENU BAR

The term menu is nothing but the available option are put into group under the common
name called menu name. Like the same that in Vb menu also consist of various options
exist in application. The following are the types of menu exist in vb for some process.

File  File handling and printing the applications


Edit  Standard editing functions, undo option exist.
View  Displays or hides the windows and toolbars.
Project  Sets project properties, adds/removes forms and modules,
and adds/removes references and components
Format  Aligns or sizes controls
Debug  Starts/stops debugging and stepping through programs
Run Starts a program, or compiles and starts it
Tools  Adds procedures, starts the Menu Editor, sets IDE options
Add-Ins  Add-in manager, lists add-ins like Application Wizard and
API Viewer
Window  Arranges or selects open windows
Help  Handles Help and the About box

Note: The one important job of the File menu is to create EXE files for your program.
When you run a program from the Run menu, no EXE file is created; if you want to run
the program outside of Visual Basic, you must create that EXE file, and you do that with
the File menu s Make ProjectName.exe

THE TOOLBAR

The main toolbar, you can also display other dockable toolbars in Visual Basic: the
Debug, Edit, and Form Editor toolbars. To display one of these toolbars, just select it
using the Toolbars item in the View menu; the toolbar appears free – floating at first, but
can dock it as you like in the IDE.

Note : If you are not sure what a particular tool in the toolbar, move the mouse pointer
over the tool , the complier will show the tool tip as a message.

The visual basic standard toolbar displays different buttons and changes its appearance as
one uses the different features of visual basic. One can also dock or undock the toolbars.
Docking refers to the features by which the toolbox is connected or placed in a window
where it works best for the users.

43
lOMoARcPSD|27913987

Visual basic has four default toolbars that can be made to appear on the screen or hidden
using View  Toolbars menu selection. These fout types of toolbars are

1. Standard

2. Edit

3. Debug

4. Form Editor

The different toolbars are described below:

Standard  This is the default toolbar that can be seen at the top
of the screen
Edit  This toolbar contains items to assist in editing Visual
basic code.
Debug  This toolbar contains items to assist in finding errors
in the code during a debugging session.
Form editor  This toolbar assists in adjusting items on the forms.

THE FORM WINDOW

The form window is used to design the different forms as application will contain. An
application can have one or more forms, and each form can have many controls that
perform various functions. The form window can be resized to whatever size that is
required. As it is resized, its new size will be displayed in the right most coordinate
section of the standard toolbar. The form window is a part of the IDE window.

44
lOMoARcPSD|27913987

PROJECT EXPLORER

View Object
Toggle folder
View Code button

The project explorer is usually located at the far right of the screen. It contains a widow
explorer like tree view of all the customizable forms and general code that make up your
application. Each project can have multiple forms and code that activates the controls on a
form is stored with the forms in separate files.
The project explorer window is viewed to manage the various components or files of the
project. Related items are listed together in a tree listing the above diagram. The three
buttons on the project explorer window enables the display of the code or the object
(commonly the form), or the toggle the folders setting to group or ungroup the related
objects. Although the project explorer window can displays the various projects, forms,
modules, class modules, user controls, user documents, and property pages for an
application, one will be working on only forms and code modules.

45
lOMoARcPSD|27913987

PROPERTY WINDOW

The properties window enables one to change one or more properties for the currently
selected object. The highlighted object is usually a form or control. The various properties
of an object can be viewed either in alphabetical order or by category. For example when
the first text box control is placed on a form, its name property is set to Text1 by default.
The properties window can be used to change this property to an appropriate name such as
txtCustomer.

Most programmers reconfigure their workspace to make the properties window larger than
the default to quickly access the various items in the properties window. The method of
changing the individual properties is an important task in visual basic.
Note : If the property window is hidden for some reason, you can make it visible by
pressing f4, clicking on the properties tool, or simply choosing view  property.

FORM LAYOUT WINDOW

46
lOMoARcPSD|27913987

The form layout window enables to preview the final location on the screen where the
form one is working with will appear. If an application is having multiple forms, using the
form layout window to align them properly onscreen can be easier than setting their
properties by hand.
Using this window user can position forms as you want them to appear on the screen when
they are first displayed. To give a Form new initial location, just drag that form in the
form layout window to that new location.

TOOLBOX

The toolbox contains the various controls that can be placed on a form when mouse cursor
is placed over any of the controls on the toolbar, a pop-up tool tip will appear, displaying a
short description of the control.
When a new project is started, these controls are already added to the toolbox. However
many more controls come with Visual basic 6 and they can be added to the toolbox
whenever required. The method of adding these controls to the toolbox by using
component option exist in project menu.

The user can use the toolbox to add controls to your projects, and you do so in a very easy
way – by click a tool, such as the command button , and so on in the form.
The toolbox is loaded with controls, user can add to form like text boxes, labels, picture
box, Image box, labels, option button, check box, list box, timers progress bar, status bar,
menu editor and more tools can be added in to the form.

47
lOMoARcPSD|27913987

The form designers and Code window

The last parts of the IDE that we have an overview are form designers and code windows,
appears in above. The form designer displays the current form under design, complete
with command button, and the code window displays the code for the Form_Load()
procedure.

Form designers are really just windows in which a particular form appears. You can place
controls into a form simply by drawing them after clicking the corresponding control s
tool in the toolbox.

Code windows are similarly easy to understand: you just place the code you want to attach
to an object in the code window to open an objects code in the code window, just double-
click that object. There is two drop-down list boxes at the top of the code window: the left
list lets you select the object to add code to, and the right list lets you select the procedure
to add all the methods the object supports appear in this list.

48
lOMoARcPSD|27913987

HELP IN VISUAL BASIC

Using the Online help facilities

The online documentation included with Visual basic 6 actually contains answers to
almost any question that the user will have while working in visual basic.

Micro soft has changed the format of online help files to match the new MSDN Library
network. One can access the Visual basic Help system from the Help menu by selecting
Contents, Index, or Search to access MSDN online. MSDN stands for Microsoft
Developer Network, which includes MSDN CD-Rom subscriptions, an MSDN website,
technical articles, and newsletters. Selecting Help  Contents will display the screen for
complete help for users, when MSDN have separately installed in the system.

The available tabs offer the following options.

 Contents - Enables to scan help contents organized in <books= by topic.


 Index - Enables to scan for help through indexed keywords.
 Search - Enables to perform a full text search of the
information in the library.
 Favorites - Enables to store links to frequently used topics
for easy retrieval.

Interactive help features

Most traditional help systems wait for the user to start eh interface and require information
on a particular topic or question. Visual basic includes two very useful help – related
features that no longer wait for the user.
The two types of help are
 Auto List members
 Auto Quick Info
Auto list members are a time saving option that displays a list box which contains the
members (properties and methods) that are available in the code window.

49
lOMoARcPSD|27913987

From the above example is that, while writing coding for command button1 in code
window it displays the auto list member related to that command button. If the user type
the term command1 the dot it displays the auto list members and then select the option
which is required for the user by selecting simply or pointing it and the press spacebar.

By using the help of the auto list member concept that helps the user in time saving in
typing the commands completely.

Note: If the control is placed or present in the current form, then while writing coding time
if the user types command and press dot means the complier does not displays the auto list
members because it displays only the control exist in the current form.

Auto Quick info option displays the syntax of any function, subroutine, or method. When
the user one enters the name of that procedure followed by a period, space, or opening
parenthesis. The procedure can be either a built – in – function or subroutine that is
contained in visual basic or it can be one that is written by the user.

From the above dialog box is that the user is typing a coding for message box in code
window for form _load event. At the time the general syntax of message box is displays
while typing. From this information or help the user can able to continue the writing of
coding to complete the whole statement without any help line from the other users.

50
lOMoARcPSD|27913987

LESSON-4
METHODS AND EVENTS
Methods and events
The Event procedure
Event Triggering
Mouse Events
Keyboard Events
Other Events
Event driven programming
Working with forms
Variables
Dimensioning of variables
Option Explicit statement
Variable assignment statement.
Modifying a Variable
Scope of variables
Constants
Data types

METHODS AND EVENTS

Events are responsible for everything that9s happening within windows. Events are an
integral part of the widow operating system. Visual basic events help to create complex
applications easily.

Pressing the keys, moving the mouse, clicking an object, and so on are the some of the
events that happen in visual basic. The program understands the recent event that occurred
and the responds accordingly.

If the user clicks the mouse in the application window, visual basic notices it and then
sends a message to that application indicating that the event has occurred along with some
additional information, known as parameters of the event.

The Event procedure

Knowing when an event occurs is the first step in using them in the application. When the
user types something on the keyboard or uses the mouse, Visual basic will receive the

51
lOMoARcPSD|27913987

input from the event and then passes it on to the application. The application then decides
how to react to that event.

An event can be ignored simply by not adding any code to its event procedure. Every
object in the application has one or more events associated with following figures are that
code editor with the drop down event list for the form.

If a new project is created and executed without adding any code, nothing would happen if
any event is performed on the form. However, even if a single line of code is added to the
form load event procedure for instance, it would be executed when the form is loaded.

Event Triggering

In a Visual basic application, two different types of events can occur. The first type is a
user event; that is, something that the user does that triggers the event. The second type is
a system event, or the user does not control something that occurs within the application.
The system events include

 Timer actions
 Data access errors
 From status changes
 Control status changes

As it can be seen, triggering an event controls all the actions in the program. Because of
this, there are usually many ways for the user to trigger the same event. For example, the
click event can be triggered in response to several other events besides just left – clicking
the mouse on an object. The following are some of the other ways to triggers a click
event.

52
lOMoARcPSD|27913987

 Clicking the right mouse button on certain controls.


 Pressing the Space bar if a command button has the focus
 Pressing the Enter key if the command buttons default property is true
 Pressing the Esc key if the command buttons default property is true
 Pressing the hot key if it has been defined in the caption property.

From the preceding short list, it can be seen that there are a variety of ways to trigger a
click event. This gives the control needed to complete a Visual basic application.

Mouse Events
Many events can be triggered using the mouse. Each of them enables to response to them
as needed. The mouse – oriented events are as follows.

Click - Occurs when a user presses the left mouse button


Dbclick - Occurs when the user presses the left mouse button
twice.
DragDrop - Occurs when the mouse button is held down and
dragged to another control that has Drag drop
enabled. Visual basic responds by executing the Drag
drop procedure for the target object.
Drag Over - Occurs when the user is in the process of dragging an
object.
Mouse Down - Occurs when a mouse button is pressed.
Mouse Up - Occurs when a mouse button is released.
Mouse Move - Occurs when the mouse is moved over an object with
no button pressed.

The following new project is used to explain the usage of these events. In the project a
command button and the text box are first placed on the form.

53
lOMoARcPSD|27913987

Again without the code, this program will do nothing. The following code added to
display a message in the text box when the mouse is moved over it and to displays
message if the mouse is moved over the command button. If the mouse is anywhere else
on the form both the message will be cleared.

Private sub form_mousemove (button as integer, shift as integer, x as single, y as single)


Text1.text = < <
End sub

Private sub command_mousemove (button as integer, shift as integer, x as single, y as


single)
Text1.text = <This is a sample
program= End sub

Private sub text_mousemove (button as integer, shift as integer, x as single, y as single)


Text1.text === You are learning Visual basic=
End sub

Keyboard Events

Keyboard events enable the program to monitor any keyboard input that is passed to a
program, and to validate and modify that input if needed. The main purpose of these
events is input validation. The following three main events are associated with the
keyboard.

Key press - occurs when a key is pressed but before the


program actually processes it.
Key down - occurs when a key is pressed.
Key Up - Occurs when a key is released.

These events give the control needed to verify input in a professional manner. If a user
presses a letter key when a numeric key is expected, the program should display an error
message and the user to correct the error.

Other Events

Many other events can be used in the application that would be useful to perform certain
actions when something starts or changes. Visual basic has been written to trap several
states – change events so that the program will have a chance to respond if needed. The
following are some of the events in this group.

Activate - Occurs when a form becomes the active window.


Forms are activated using the show method.

54
lOMoARcPSD|27913987

Deactivate - Occurs when a form is no longer the active window.


This can be done using Hide method.
Got Focus - Occurs when an object receives the focus either by
user action such as tabbing to or clicking the object,
or by changing the focus in code using the Setfocus
method.
Lost Focus - Occurs when the focus is moved to another control
either by user action, such as tabbing to or clicking
another object, or by changing the focus in code using
the Setfocus method.

Load - Occurs the first time a form a loaded. For a startup


form this event occurs when an application starts as
the result of a load statement or as the result of a
reference to an unloaded form9s properties or
controls.
Unload - Occurs when the form is unloaded. This event is
triggered by user closing the form using the close
command on the control menu or an unload statement.
Bu using these and many more status events, one can change the application with a great
deal of control and enhanced appearance.

EVENT DRIVEN PROGRAMMING

Forms and controls are the basic elements in the user interface of any Visual basic application.
In visual basic, these are called objects, because they are used like real world objects. Like any
other physical objects, they also have properties and react to external events.

Consider that the fountain pen, for instance is a physical object and one of its properties is
the colour of the ink used in the pen. When a pen is purchased the colour of the ink to be
used in the pen is decided and that colour ink is used to fill up the pen. At the same time,
at a later stage, different colour ink can also be used. Similarly most control properties of
the visual basic objects are set when they are created and placed on the form. But the
properties of those controls can be changed later by assigning a new value to it. This
means that the properties of the visual basic objects can be assigned at design time through
the properties window or at runtime though the visual basic program code.

WORKING WITH FORMS

The initial from window displays at the center of the IDE window. In that window by
adding controls and changing its size can be customizing by the user. The size of the form
can be controlled either by manually changing the height and width properties at design
time and runtime or by selecting the form and dragging the sizing handles at design time.

55
lOMoARcPSD|27913987

The height property represents the form9s vertical size on the screen, whereas the width
property represents the form9s horizontal size of the screen. To change the height and
width properties at runtime. The form_ activate event is executed whenever the login form
is initialized or get focus.

Private sub form_activate ()


Frmlogin.height = 2500
Frmlogin.width = 5000
Endsub

When F5 button is pressed to run the application, it can be noticed that the login form
would have a changed its height and width.

The keyword Me can be used to refer to the currently loaded form object instead of
explicitly giving the form name.

Private sub form _activate ( )


Me.height = 2500
Me.width = 5000
End sub

In addition to controlling the form9s height and width, one also can have control over its
position on the screen during runtime. The relative position of the form can be controlled
during design time by manually changing the Top and Left properties in the properties
dialog box or by selecting the form and dragging the sizing handles at design time. The
top property represents the distance from top edge of the object to the top of its container.

56
lOMoARcPSD|27913987

Again changes can be made at design time by using the properties dialog box. To change
the top and left properties at design time, simply the desired property value selected and
the new value is types. When the application is rum, the new property values will be used.

To make changes at runtime, some code segments need to be added to the application.
Typically these code segments are not more than a few lines in length, but they give
programmatic control over how the form or control is positioned during runtime. The
coding will adjust the top and left properties so that the form is positioned in the upper –
left corner of the screen.

Private Sub_form load ( )


Frmlogin.Top = 1000
Frmlogin.Left = 1000
End sub

The following are the common properties for Form

 Caption - The caption property sets the title of the form.


 Name - This property is used only in code.
 Appearance - Determines whether the form will have three dimensional
look. The default property value is 1.
 Border style - It consists of 5 values. The default value is 2, allows the user
to size and shape the form.
1- Fixed single, 2- Sizable, 3- Fixed
double , 4- fixed tool window, 5- sizable
tool window.
 Control box - Changes to this property go into effect only when the user
runs the application.
 Enabled - It has two status of true or false. If it false that the form will
not responded to any event occurred.
 Font - It can use to change the font used to display information on
the form.
 Height, Width - This property will affect the form height
and width while in design time itself.
 Icon - This property determines the icon your application will
display when it is minimized on the toolbar or turned into a
stand – alone application on the windows desktop.

57
lOMoARcPSD|27913987

 Visible - This has a value of true and false. If you want to make form
invisible only when you are designing an application with
multiple forms.
 Window state - This property determines how the form will look at run tie.
A setting of 1 reduces to icon; setting of 2 maximizes the
form, setting 0 to the normal default setting.

4.4 VARIABLES

Computer program have the capability to work with and store information to be used in
many different processes. This requires that the program can store and manipulate that
information whenever it is needed. This is done using variables.

A variable is a location in memory that is given a name. The name given to a variable may
be almost anything, although there are some restrictions. A variable can be declared
simply by using a name in the program.

Example:
A
Memory location for data storage.

A = 100, here a is memory location with variable name is A.

However, if option explicit is specified in the general declaration, every variable must be
defined or an error will occur.

Variables in Visual basic hold information (values). Whenever you use a variable, visual
basic sets up an area in the computer memory to store information. Variable names in
visual basic can be up to 255 characters long and provided the first character is a letter,
can include any combination of letters, numerals, and underscores.

The rules for declaring a variable in visual basic


1. The name must begin with a letter (a to z , A to Z).
2. The name can contain only letters, numbers, or the underscore character.
3. It must not exceed 255 characters.
4. It cannot be a Visual basic reserved word. However, it can contain a reserved word
like opencustomer is valid one, but open is invalid one.

It is better to declare any variables in the program explicitly using a DIM statement as
shown below.
Dim str as string
Str = <Best of
luck=

58
lOMoARcPSD|27913987

Dimensioning of variables

I order to declare or dimension a variable in the program, the DIM statement is used. This
informs the computer that the user wants to declare a variable. It also specifies the name
and the data type of the new variable.

The following is the syntax of the DIM statement.

Dim variable_name [as variable _type]

The variable_name is the name to be used for that variable.


The as variable_type is an optional parameter.

The following example shows a routine in visual basic using DIM statement.

Private sub form _ load ()


Dim frm as Boolean
Dim msg as string
Frm = true
Msg = <welcome to
India= Print= This is demo
<, msg End sub
This code declares both variables prior to actually using them. By using this method, the
amount of space that the program uses when executing is reduced. Another benefit of
declaring variables this way is that visual basic will displays any type mismatch error that
might occur.

Output
This is demo welcome to India

Option Explicit statement

When dimensioning variables, there is one pitfall that must be watched out. If a variable is
not explicitly declared in the program, visual basic will implicitly declare it and the
application developer will never realize it. The same thing will happen if a variable is
misspelled; however, the program might not work correctly because there is now an extra
variable being used. To prevent this from happening, the option explicit statement should
be used in the declaration section of each form as shown in the following figures.

59
lOMoARcPSD|27913987

The option explicit statement will instruct visual basic to display an error for any variables
that was not explicitly dimensioned in the program. To ensure that this setting is always
turned on, the option in visual basic can be set so that every form or module that is added
to a project will automatically have this option added to it. This can be done by selecting
Tools  options from the visual basic menu to display the options dialog box as shown
below.

By clicking the Require variable declaration setting, the option explicit statement will be
included in every new form or module that is added to a project.

60
lOMoARcPSD|27913987

Variable assignment statement


Assignment statements are what you use to give a visual basic variable a new value.
Another way is to think about assignment statements as a means of copying information
from the source to destination. In any case giving values to variables is one of the most
common tasks in visual basic code. Visual basic uses an equal sign for this operation
For example
Test = 100
Here it set the value of a variable named test = 100. The variable name always appears on
the left of the equality sign, and the value always appears on the right. Visual basic must
be able to obtain a value from the right side of an assignment statement, and it will do any
processing needed to make this happen.
For example
Test1 = 25 + 5

Here it would make the variable test2 have value is 30. This is because Visual basic would
do the addition first, and then store the result in the variable.

Modifying a Variable
Constants are variables that cannot be modified within the program while it is executing.
A constant, as the name implies, cannot be changed. If a value is needed in several
different sections of code, it is recommended that this value is declared as a constant.
There are two main benefits of using a constant in the program. First one need not have to
remember a specific number to type into every section of code that uses it. A constant can
be declared to be equal to that number and that constant can be used wherever that number
is referenced. The second benefits is the ability to change one value in the declaration
section of the program, and have all the references to it change automatically.
The syntax of a constant declaration is as follows
Const variable_name [as variable type] = value
Declaring a constant is similar to declaring a variable except for the assignment portion of
the statement at the end of the declaration.

SCOPE OF VARIABLES

Project Scope

An objects scope indicates how much visibility it has throughout the project in the
procedure where it s declared, throughout a form or module, or global scope ie. Which
means it9s accessible everywhere. There are two types of scope in Visual Basic projects:
variable scope (including object variables) and procedure scope.

61
lOMoARcPSD|27913987

Variable Scope
The user will use the Dim statement to declare a variable. If you do not specify the
variable type when you use Dim, it creates a variant, which can operate as any variable
type. You can specify the variable type using the as keyword like this:

Dim ab As Integer
Besides Dim, you can also use ReDim to redimension space for dynamic arrays, Private
to restrict it to a module or form, Public to make it global that is, accessible to all modules
or forms or Static to make sure its value doesn9t change between procedure calls. These
ways of declaring variables are summarized in

Visual Basic declaring statements.


Keyword Meaning
Dim Using Dim alone creates variants. Use the as
keyword to specify variable type.
Private Makes variable available only in the current form/module.
Public Makes variable global variable is available to the
rest of program.
ReDim Reallocates storage space for dynamic array
variables.
Static Variable preserves its value between procedure calls.
Type Declares a user type.
There are three levels of variable scope in Visual Basic: at the procedure level, at the form
or module level, and at the global level.

Procedure Scope

As with variables, you can restrict the scope of procedures, and you do that with the
Private, Public, Friend, and Static keywords. The Private and Public keywords are the
main keywords here; using them, you can specify if a subroutine or function is private to
the module or form in which it is declared or public (that is, global) to all forms and
modules. You use these keywords before the Sub or Function

Example
Private Function ret()
Dim test
test = 7
ret = test
End Function

62
lOMoARcPSD|27913987

In visual basic user can also declare procedures as friend procedures with the Friend
keyword. Friend procedures are usually used in class modules (they are not available in
standard modules, although you can declare them in forms) to declare that the procedure
is available outside the class, but not outside the current project. This restricts those
functions from being called if the current project serves as an OLE automation server.

Thus the earlier declarations, you can also declare procedures as Static, which means that
the variables in the procedure do not change between procedure calls, and that can be
very useful in cases like this, where we support a counter variable that is incremented
each time a function is called:

Static Function Count ()


Dim CtVal as Integer
CtVal = CtVal + 1
Ct = CtVal
End Sub

The following is the systematic of visual basic project scope.

Global Items
Declared with PUBLIC

Form

Form – Level variables


Declared in General

Private variables
Available to this form only

Procedure Procedure
Local Local
Variables Variables

63
lOMoARcPSD|27913987

Global Items Procedure Procedure


Declared with PUBLIC Local Local
Variables Variables

Module

Module – Level variables


Declared in General

Private variables
Available to this module only

The scope of a variable refers to how long it can be used and which routines can see it.
There are three different types of scope a variable can have Global, Module, and Local.

1. Local Scope

Whenever a variable is declared inside a function, subroutine, or event routine, only the
code within that procedure can see that variable. This is referred to as local scope. The
following two routines with local variables defined in them.

Example

Sub routine1 ( )
Dim var1 as Integer
Dim var2 as String
Var1 = 5
Var2 = <Sample
program= End sub

64
lOMoARcPSD|27913987

Sub routine2 ( )
Dim var1 as String
Dim var2 as Integer
Var1= <Sample
program= Var2 = 15
End sub
As it can be seen, the same variable names can be used in separate routines because they
are local to each routine and are not known by the other routine.

2. Module Scope

The next type of scope is called module. A variable can be declared with module scope by
using the private declaration statement. The syntax of the private statement is the same as
a Dim statement except for the keyword private. Any variable declared as private can be
seen in any routine within the module or form where it was declared. The following is the
same as the preceding example except it uses the tern private to define the variables.

Example
Private var1 as Integer
Private var2 as String

Sub routine 1()


Var1 = 10
Var2 = <welcome to
India= End sub

Sub routine 2()


Var2 = <welcome to
India= Var1 = 10
End sub

As seen in the above example, once the variables are declared outside the routine, the
same variables name cannot be used for different data types.

3. Global Scope

The last and most powerful of the scope is global scope. To define a variable as global, the
public declaration statement is used. The syntax of the public statement is the same as a
Dim statement except for the keyword as Public. Any variable defined as public can be
used by any routine in any module, within the program.

The following declaration shows that the variables used in the preceding example. After
this is done, they can be used in any routine as shown in the later part of the coding.

65
lOMoARcPSD|27913987

Example

Sub routine1 ()
Var1 = 15
Var2 = <welcome to
India= End sub
Sub routine2 ()
Var2 = <welcome to
India= Var1 = 15
End sub

CONSTANTS

Declaring Constants

The term constants are nothing but the value cannot be changed during the execution of a
program for particular time period. Declare them all in one place, and then refer to the
constants by name throughout the code instead of hardwiring numeric values in the code.
When its time to change those values, you just change the constants, all in one well-
defined part of the code.

The user can declare constants in Visual Basic with the Const statement:
The general format is

66
lOMoARcPSD|27913987

[Public | Private] Const constname [As type] = expression

The Public keyword is used at the module level to make a constant global. This keyword
is not allowed in procedures. The Private keyword is used at the module or form level to
declare constants that are private, which means only available within the module or form
where the declaration is made. Like the Public keyword, Private is not allowed in
procedures (constants in procedures are always private anyway).

The constname identifier is the actual name of the constant. The type identifier is the data
type of the constant, which may be Byte, Boolean, Integer, Long, Currency, Single,
Double, Date, String, or Variant. The expression identifier holds the value you want for
this constant. It may be a literal, other constant, or any combination that includes all
arithmetic or logical operators (except the Is operator).

You can use a constant anywhere you can use any Visual Basic expression, and you
usually use them for numeric or string values that you want to use many places in a
program. That way, when you want to modify the value of the constant, you only have to
change it in its declaration, not in many places around the program. Also, constants don t
change their values, which can make them more useful than variables in certain
circumstances.

Here is an example showing how to declare and use a constant:

Private Sub Command1_Click ()

Const Pi = 3.14159

Dim Radius, Area

Radius = 15

Area = Pi * Radius * Radius

Print ("Area = " & Str (Area))

End Sub

Note:

From the above program is that the value of pi is assigned in global as a constant for
particular period of time. When the statement executes the value of pi is assigned as 3.145
and then it do calculations for further steps. The term constant is nothing but value cannot
be changed for particular time duration.

67
lOMoARcPSD|27913987

DATA TYPES

The different data types available in visual basic represent the types of data that visual
basic uses are given below in the table.

Any of these different data types can be declared as a variable. The default storage types
for a variable are Variant. If the data type is not specified, then variant will be used for
processing.

Data type Description Declaration Character Range


Byte 1 byte None 0 to 255
Boolean 2 bytes None True or False
Integer 2 byte integer % -32 768 to 32,768
Long 4 byte integer & 2,147,483,648 to
-2,147,483,648
Single 4 byte floating ! 3.402823E38 to
point number -3.402823E38
Double 8 byte floating # 1.79769313486232D308 to
point number -1.79769313486232D308
Currency 8 byte number @ 922,337,203,685,477,5808 to
with fixed decimal -922,337,203,685,477,5808
Object 4 bytes None Any object reference
Date 8 bytes None 1/1/100 to 12/31/9999
String String of characters $ Through characters 65,500
Variant Date / Time None Can contain numeric data in
Floating point the range as a double, or any
Numbers or strings string character.

Note:

Variant is the most flexible type of variable that can be used. It can be used to work with
most of the other data types, except for fixed – length strings. However, there are some
problems with using that variant data type. For example, one could have two variant
variables, one that is a string and the other that is number. Visual basic does not allow the
arithmetic operations of these two variables together because they are different data types.

1. String
The string data type holds characters. User can have a single character in a string or many.
A variable holding a string is called, naturally enough, a string variable. One method of
identifying variables of this type is to place a dollar sign ($) at the end of the variable
name

68
lOMoARcPSD|27913987

Example
Stringvariable$.
Once users add the dollar sign, that variable can only hold strings. String variable can
theoretically hold about 2 billion characters. On a specific computer, though the variable
may hold less, due to memory constraints.
One of the most common uses of string variables is to pick up the information contained
in a text box. For example if user has text box named as test1, then

Test1$ = text1.text.
Here it assigns the string contained in the text box to the variable named as test1 on the
left hand side of the assignment.

2. Integer
Integer variables hold relatively small integer values (between -32,768 to 32, 768). Integer
arithmetic is very fast but is restricted to these ranges. One way to make sure that a
variable will only be capable of holding integers is to use the percent sign (%) at the end
of the variable name.

Example
Test% = 5

3. Long Integer
The long integer variable holds integers between 2,147,483,648 to -2,147,483,647. The
identifier can use for your variables is the ampersand (&). Long integer arithmetic is also
fast, and there is very little performance on modern machine.
Example
Test& = 123456789

4. Single Precision

The least accurate is called single precision. They have a decimal point, but user can be
sure of the accuracy of only seven digits. The accuracy is limited; the size (range) of these
numbers is up to 38 digits.
For single precision numbers, the identifier user can use to make sure a variable will only
hold a single precision number is an exclamation point (!).
Example
Test! = 12.456

4. Double Precision
The double precision data type is used when user need numbers with up to 16 places of
accuracy; they will also allow user can have ore than 300 digits. Double precision

69
lOMoARcPSD|27913987

variables are mainly used in scientific calculations in visual basic. The identifier used for
double precision variables is a pound sign (#). The user has to use the Pound # symbol at
the end actual number.

Example
Test# = 12.5435000000000

5. Currency

Currency variables are type that will be new to programmers. They are designed to avoid
certain problems inherent in switching from binary fractions to decimal fractions.
The currency type can have 4 digits to the right of the decimal place and up to 15 to the
left of the decimal point. Arithmetic will be exact within this range. The identifier is an
<at= sign (@).

Example
Test @ = 12.45668

6. Date
The date data type gives you a convenient way to store both the date and time information
for any time between midnight on January 1, 100 to midnight on December 31, 9999.

Example
Test = # January 1, 2008#
Test = # Jan 1, 2008#
Test = # 1 / 1 / 2008#

7. Byte

The byte data type can hold integers between 0 to 255. This is a great convenience when
you need to save space, and it makes certain arrays much smaller than they would have
been in earlier version of VB.

8. Boolean
The Boolean type when user needs data to be either true or false. It is considered good
programming practice to use this data type rather than integers for true or false values.

9. Variant

The variant data type is designed to store all the different possible VB data received in one
place. It does not matter whether the information is numeric, date / time, or string; the
variant type can hold it all.

70
lOMoARcPSD|27913987

UNIT – III

Lesson – 5
Functions
Writing a simple functions
User defined function with example
Procedures

Lesson - 6
Define control Structures
If concepts
IF..THEN ..Else
IF..THEN…ElseIf
Switch – Select
For looping
For…Next statement
Step statement
Exit For statement
Nested For…Next
While looping
Do – While loop
Do – Until loop
Lesson – 7
Arrays
User defined data types
Data type conversions
Lesson – 8
Operators
String functions
String handling functions
Date and time functions

71
lOMoARcPSD|27913987

LESSON-5
FUNCTIONS

FUNCTIONS

Writing a simple function

PROCEDURES

There are actually two kinds of general procedures in visual basic:


Function procedures and Sub procedures.

Function procedures or user defined functions are simply ways of going beyond the built
in visual basic functions. Sub procedures on other hand are smaller helper program that
are used as needed. Sub procedures are thus generalizations of the event procedures.
The point is that sub and function procedures do one or more of the following

Help you break down large tasks into smaller ones.


Automate repeated operations Make it clearer what it is you are trying to accomplish by
<naming= a piece of code. All these features can dramatically reduce debugging time.

Writing a simple function

Before writing the user defined function the user has to make some settings in the visual
basic. First click Tools menu  Add procedure, and then user will get the Add procedure
dialog box like as follows. In that dialog box consist of following options for further
processing

1. Name
2. Type - Sub , Function, Property, Event
3. Scope - Public , Private
4. Ok button
5. Cancel button

72
lOMoARcPSD|27913987

From the above dialog box user have to type the name of the function. And also select the
type as sub, property, function, events. After that user has to select the scope of the
function may be public or it may be private. Finally has to click te ok button in the dialog
box. Then the user will get the following type of window for writing coding for processing
the user function.

The following is the general format for writing user defined functions as a separate block
in your coding area.

Public / private function function_name (parameters)


Statement or block of statements
End function

73
lOMoARcPSD|27913987

Example

Public function random(x) as integer


Random = int(x * rand) + 1
End function
The output of the above is that the value of x is assign as random values form the memory
and it9s incremented by one, for time of execution of the grouping statement.

Note: The first line of the function (line containing the name) is called as the header of
the function. The keywords public or private are called as access specifier. Here the
variable X is called as formal parameters.

While naming the function name the user must following some condition or rules would
be same as the variables name rules.

Example
Public function random( X )
Public function random( X ) as integer
In both the cases visual basic will the know that function returns integer values.

Body of the function

Random = int ( x * rnd ) + 1

Note: Next come to the body of the function – code that actually defines the functions
power. This assignment statement is how the function gets its value, then it depends on the
x that occurs both here and in the header of the function. Here the variable called actual
parameters and it also called as place holders.

The following are concept of parameters used in different types in functional statement.
1. Public function random (X) as integer
2. Public function random (X as integer) as integer

From the above two types of defining function statements, in that first one the parameter is
a variant because we have not used any type identifier. If user want to ensure that only
integers to the function we should like a statement two.

Example
a = 2 , b= 10
and the function statement followed by
r= random ( a * b + 5)

74
lOMoARcPSD|27913987

this will effect same as the following type by


r= random (25)
Here in the above two type of functional statement is that process is the same, but in first
statement the expressions is passing as a parameter. In second statement, instead of
parameters the constant value is passing directly for further processing.
Function with more than one parameter

Example
The following is a function concept consists of more than one parameter or two parameter.
Public function test(x as integer, y as double)
Functional statements
End function

Note:

1. Here the function name is test


2. The function is declared as public access specifier
3. It consist of two variables or parameter like a and y
4. Then used defined programming statements.
5. Finally the function ends with end function keyword.

Further more on User defined function with example

The following is the simple form of defining the user defined function is as follows
Public function fun_name( parameter1, parameter2)
Statements
Function name= expression1
Function name = expression2
Statements
End function

Here parameter1 and parameter2 are referred to as the arguments or variables in the
function. Then the expression1 and 2 is assigned to its corresponding variables or function
name for further processing.
Example

In code window
Dim A as integer
Pubic sub command_click ()

75
lOMoARcPSD|27913987

A = val( text1. text)

Test (A) // This is calling statement

End sub

Public function Test(x as integer) // the X gets the value of A

Test = x + 10 // here it calculate the value of x and 10

Print <the result is <, test // finally it print the result value

End function // end of the function

Example

In code window

Dim A, B as integer

Pubic sub command_click ()

A = val( text1. text)


B = 10
Test (A, B) // this is calling statement for function with two parameters

End sub

Public function Test(x as integer, y as integer)


// the X gets value of A and Y gets B

r= test( x + 10) // here it calculate the value of x and 10

m = test(y * 5) // calculate the value for m

Print <the result for R <, r // finally it print the result value for r

Print <the result for M=, m // it print the value of M

End function // end of the function

Output:

76
lOMoARcPSD|27913987

Consider the value of A is given in text box is 15 and value of B is already assigned the
value as 10. So the value of A and b is assigned to the variable X and y by calling a
function called test.
In test function the value of X is added with 10 and its value is assigned to the variable
R and also the value of Y is multiplied by 5 and assigned in variable the M. Finally the
value of R and M is printed using print statement. The result of R is 25 and the result of
M is 50

5.2 SUB PROCEDURES

To define the sub procedure execute as same way as the function click on tool menu 
add procedure. The following is the general format for sub procedure concept.

Public sub nameof_sub (parameters)


Statements
End sub

Note:
First line of the above block is that called as header of the sub procedure. Along with that
the access specifier is mentioned in that statement. The private or public keyword s used.
In header section the name of the sub procedure is highlighted. Then followed by
statements for processing and finally end with the end sub.

Pubic sub comman_click()

a = val(text1.text)

call test( a) // calling statement for sub procedure

end sub // end of the main block

public sub test ( x as integer ) // x receives the value of a.

res= test(x + 10) // calculate the value of res

print <the result evaluate in sub procedure <, res //print the result

end sub // end of sub procedure

77
lOMoARcPSD|27913987

The following are the type to call the sub procedures


1. name of procedure( argument1, argument2)
2. call name of procedure ( argument1, argument2)

Example

Public Sub form_click()


Dim a as integer
For x = 1 to 5

Call test ( x ) // call for sub program,

Next X
Print < The result in block
main= End sub
Sub test ( x as integer) // sub program starts executes here.
Print <result in outer loop or sub program=, x
End sub

Output
From the above program is that while at the time of form load event will execute and the
first time for loop starts executes it first execution and its assign the value of X is 1 and its
calls the sub procedures called test. In sub procedure the using print statement print as
<result in outer loop or sub program <with value of x.

<Result in outer loop or sub program < 1


<Result in outer loop or sub program < 2
<Result in outer loop or sub program < 3
<Result in outer loop or sub program < 4
<Result in main block=

Advanced concept of function and sub procedure

The advanced concept of function and sub procedure consists of following concept

When user calls a function or procedure, there are actually tow ways to pass in variables
as arguments. These are called

 Passing by reference
 Passing by value

78
lOMoARcPSD|27913987

When you pass argument variables by reference, any changes to the corresponding
parameter inside the procedure will change the value of the original argument when the
procedure finishes. When you pass an argument by value, then original variables retains
its original value after the procedure terminates – regardless of what was done to the
corresponding parameter inside the procedure.

Example

Sub form_load()

Dim A as integer

A = Val (text1.text) // consider A = 5


Print <value of A in main block <, A

Test (A)

End sub

Sub test ( x as integer)

R = test ( x + 25 )

Print < result in sub block <,

R End sub

Output
A is assigned a value as 5
Then it prints as in same block using print statement.
Again the value of A is passing to the sub program and its value is incremented by 25.

<Value of A in main block < 5


<Result in sub block < 30

Note:
When the program starts running and visual basic executes the above statements
the variable named A is passed by reference to the parameter X.

A=5 Here the value a = 5 is assigned first

79
lOMoARcPSD|27913987

Here the value of x = 5 is referred the variable A


X=5

Example

Dim a, b as integer

a=5
b =15
print test ( a, b) // call sub program
print < the value of A is <, a
print < the value of B is <,

b end sub

Sub block

Public function test( x as integer , y as integer)

Res = test( x + y + 15)// calculation of a and b

Print <the result after addition of two values A and B=, res

End sub

Note:

From the above program is that value of a = 5 and b = 15 is assigned first then its value is
passed to the variable called x and y. Through this value of x and y the result is evaluated.
Finally the result value is displayed as output.

Output
The value of A is 5
The value of B is 15
The result after addition of two values A and B 35

80
lOMoARcPSD|27913987

LESSON-6
DEFINE CONTROL STRUCTURES

Define control Structures


If concepts
IF..THEN ..Else
IF..THEN…ElseIf
Switch – Select
For looping
For…Next statement
Step statement
Exit For statement
Nested For…Next
While looping
Do – While loop
Do – Until loop

DEFINE CONTROL STRUCTURES

When designing a new application, the developer needs to control the different sections of
code that would be executed depending upon the data being processed. This process is
commonly referred to as conditionally executing the program code.
In order to execute certain sections of code conditionally the program, should respond to a
condition or test. If the condition is true, then the code will processed. This process is the
basis of every program that is written.

Thus in visual basic looping or control structures divides into two types are
1. Determinate loop
2. Indeterminate loop

In Determinate loop the following concept are included


1. For.. Next
2. Nested For..Next

81
lOMoARcPSD|27913987

For Indeterminate loop consists of


1. do …While loop
2. do. ..Until loop

Among this the If..then else concept is different from other type of loping concept.
Because the If..then concept will execute it for specified conditions. Based on the
conditions the control will transfer the flow in programming statements.

If consist of two type


1. IF..then …else
2. IF.. then … Elseif ..endif
3. Nested IF..then concept

IF CONCEPTS

Although there are many different ways to perform this test process, there is one primary
way of doing it. The visual basic statement for performing these tasks is the If…
then…….End if Statements.
Before going to the If…then … else concept, in visual basic we have a simple if…then
concept without else part section.

The general format is

IF (condition) then do action for true statements


Other wise it execute the next statement in program

Example

If ( a > 10 ) then print < A is greater than 10=


Endif
Next statements in programming block

Note:
From the above example is that it checks for condition that value of A is compared with
10, i.e value A is greater than 10 then it executes the true part of then part section. If it is
the conditions is set to failure of condition then it execute the next statement belongs to
the programming statements.

82
lOMoARcPSD|27913987

Example

IF( a = b) then
Msgbox (<A value is equivalent to value B=)
End if
Next statements belongs to the programming block
Note:
From the above example is that the value of A is compared or checks for equivalent value
of B, then it is true means then it execute the statements called true part will be executed.
It gives the result in message box as a message. Other possible out come is that the
condition is false the control is transfer to the outside of the loop and it execute the
statement belongs to the programming statements.

IF..THEN ..Else

Even though IF statement is very powerful, it can test only one condition at a time. If is
required to test more than one condition at a time, there is a way to use the If statement to
check multiple conditions. This can be done adding the Else and Else IF statement for
further processing in the programming blocks.

The following is the general forma t for IF..then Else statement.

IF (Condition) then
True block statements
Else
False block statements

Example

Visual basic to check greatest of two numbers between A and B

A = val ( text1.text)
B = val (text2.text)

If (A > B) then
Msgbox ( <The Greatest number is A <, A)
Else
Msgbox ( <The Greatest number is B <, B)
End if

83
lOMoARcPSD|27913987

Note:
From the above program the value of text box1 is assigned to the variable to the A and
same as the value of text box2 is assigned to the variable to the B. Then the value of A and
B check for greatest value among two numbers. First it checks that A > B then, if the
condition is true then it executes the message box with the message of <The greatest
number is A=. If the condition is false then it executes the statement regarding false
section. It displays the message called <The greatest number is B=.

The key aspect while using If…then …else concept then its compulsory to that close the
concept with End if keyword.

Example
The program to check for two conditions in same statement

A = val ( text1.text)
B =val (text2.text)
C =val (text3.text)
If ( A > B and A > C ) then
Label1.caption = <A is greater among three numbers=
Else
Label1.caption = <The A is not a greater value among three numbers=
End if

Note:

From the above program is that the value of text box 1, 2 and 3 is assigned to the
corresponding variables like a, b and c. Then using if then else concept user is checking
that two conditions at a same statement. If both the condition is true then it executes the
true block statements. And it displays the output label1 in caption property. If the
condition is false value then it displays that caption value of label1as A is not a greater
value among three numbers.

Output
Consider the following types of values to get the different output
1. A = 15 , B=10, C= 5
<A is greater among three
numbers= Another combination of
value
2. A = 5 , B=15 , C= 25
<The A is not a greater value among three numbers=

84
lOMoARcPSD|27913987

IF..THEN…Else If

The If…then concept is used to check for two conditions, but user want to check for more
than two conditions then user can use the If…then Else if concept to reach the specific
goal. At the end of the loop must end with key word called end if. Here only one block
able to execute for processing based on the condition is satisfied.

The following is the general format for IF…then ….Else If

Syntax
IF (Condition) then
Statements
Else if (conditoin2) then
Statements
Else if (condition 3) then
Statements
Else if (condition 4) then
Statements
Else
Statements
End if

Example

A = val (text1.text)
If ( A = 5 ) then
Msgbox < A is equal to 5=
Else if ( A = 10 ) then
Msgbox < A is equal to
10= Else if ( A = 20 ) then
Msgbox < A is equal to
20= Else if ( A = 25 ) then
Msgbox < A is equal to
25= Else
Msgbox < A is not equivalent to any groups of above=
End if

Note:
From the above program is that the value of text box1 is assigned to the variable A. First
the value of input given by user is assigned variables A. Then the value of A is checks for
condition is A= 5 , if the condition is true then it displays the message as <A is equal to 5=
and exit the loop immediately. If the first condition is not satisfied then it checks for
second condition in else if statement i.e. A = 10 then if it true then it displays a message as
<A is equal to 10= and exit the loop.

85
lOMoARcPSD|27913987

Similarly the other condition also will be checked one by one and executes the
corresponding statements. if non of the condition is satisfied then it finally control transfer
to the else part that is false part in the loop. After the execution of false part it exits the
loop.

Output
Consider that value of text box is 5 then output is <A is equal to 5= is displayed in message
box. Else the value of A = 10 then it displays a message <A is equal to 10= and so on.
Finally no condition is matched then it displays the <A is not equivalent to any groups of
above= in message box.

The following is the logical diagram for if…then...Else condition concept.

If
Condition
Checks

Statements in Statements in
Else part True part

Example

X = val (text1.text)
If ( X > 5 and X < 10 ) then
Msgbox <The value range between 5 and 10=
Else if ( X >10 and X < 20 ) then
Msgbox <The value range between 10 and 20=
Else if ( X > 20 and X < 30 ) then
Msgbox <The value range between 20 and 30 <
Else
Msgbox <The value is not belongs to any range data=
End if
Note:
From the above program is that value of text box one is assigned to variable x. Then the
value is checked for multiple conditions and based on that the statements will execute.

86
lOMoARcPSD|27913987

First it checks for x is greater than 5 and x is less than 10 then it displays the output in
message box as <the value is rage between 5 and 10. By the same procedure it checks for
other conditions. Once if the condition met a true then it execute the corresponding
statement and exit the loop immediately. Through out the looping condition, no condition
is matched then it automatically it executes the else part statements.

SWITCH – SELECT CASE

Another method that can be used to perform conditional processing is the select case
statement. It is very useful when one must check a single variable or expression for ore
than one value.
The concept of If…then...else if concept is use for multiple conditions, from that one part
will be executed. By using the if…then …else if concept leads the user to confusion and
also the output is not exactly correct.
To over come the problems in If concept, the select case concept will full fill the requirements
of user needs. Using select case one can specify the expression that needs to be tested and than
list all the possible cases or values that are to be responded with special action.

The following is the general format for Select…case concept

Select case (expression / variable)


Case numbers / variable
Statements for first case
Case numbers / variable
Statements for second case

Case else
Statement for case else part.
End select

Note:
Here the select case starts with select case statement and it consists of variable or
expression is passed as a arguments. Then based on the arguments the Case will execute
and displays the output. Finally no cases is matched then the default or case else will be
executed. If any case is matched means, it executed the case block statement and it comes
out of the loop.

87
lOMoARcPSD|27913987

Example
Visual basic program using Select case concept to display the variables component of
computer name.
X = val(tex1.text)
Select case ( x )
Case 1:
Print <The input value of x is one=
Print <The one value is equivalent is motherboard=
Case 2:
Print <The input value of x is two=
Print <The two value is equivalent is processor=
Case 3:
Print <The input value of x is three=
Print <The three value is equivalent is RAM=
Case 4:
Print <The input value of x is four=
Print <The four value is equivalent is Hard disk=
Case 5:
Print <The input value of x is five=
Print <The five value is equivalent is ROM
Case else
Print <The input value of x is out of range=
Print <Please enter the value between 1 and 5 <
End select

Note:
From the above example is that input value is given in text box is assigned to variable X.
Then the variable is passed to the function called Select case concept. If the input value is
one then the select case function will match the first case and it displays the output. If it is
two means it executes second case statement. If none of the cases is matched means that it
executes / matched the case else part and it displays the output.

Output
If user input is x = 1
<The input value of x is one=
<The one value is equivalent is motherboard=

If user input is x = 2
<The input value of x is two=
<The two value is equivalent is processor=

If user input is x = 3
<The input value of x is three=
<The three value is equivalent is RAM=

88
lOMoARcPSD|27913987

If user input is x = 4
<The input value of x is four=
<The four value is equivalent is Hard disk=

If user input is x = 5
<The input value of x is five=
<The five value is equivalent is ROM

If user input is x = 6 or 7 or more


<The input value of x is out of range=
<Please enter the value between 1 and 5 <

Example
Visual basic program using Select case concept to display the variables component of
computer name.

Dim x as string
X = Val (tex1.text)
Select case ( x )
Case 8M9
Print <The input value of x is M=
Print <The one value is equivalent is motherboard=
Case 8P9
Print <The input value of x is P=
Print <The two value is equivalent is processor=
Case 8R9
Print <The input value of x is R=
Print <The three value is equivalent is RAM=
Case 8H9
Print <The input value of x is H=
Print <The four value is equivalent is Hard disk=
Case 8O9
Print <The input value of x is O=
Print <The five value is equivalent is ROM

Case else
Print <The input value of x is out of range=
Print <Please enter the character like M, H, O, R, and P <
End select

89
lOMoARcPSD|27913987

Note:
The example consists of select case concept with character as an input for processing the
block. Here the user is giving the input in the form of character type in text box. The input
given in text box is assigned to the character variable x and it is passed to the function
called select case.

If the user is giving input as X = 8H 8 then it execute the corresponding case statement and
it displays the output as hard disk information. If input is R then it displays the output as
RAM information. If the input is M then it displays the output as motherboard details.
Like the way all other cases will executes. If none of the case is not matched for input
value then the control is automatically executes the default / else case statement will
process for output.

The important point while discussing the select case concept in character based input is
that is case sensitive one. The capital letter has a different meaning compared to the lower
case letters. So users have to consider the upper case and lower case letter while giving
input.

Example

Consider that the user input value of x is 8h9 in above example, then complier checks for
all cases and it displays only the case else because the input value in lower case letter
called 8h9. But in the case statements we have only coded as <H=. So the complier will not
match the corresponding statement.

Output
If user input is 8M9
<The input value of x is M=
<The one value is equivalent is motherboard=
If user input is 8P9
<The input value of x is P=
<The two value is equivalent is
processor= If user input is 8R9
<The input value of x is R=
<The three value is equivalent is
RAM= If user input is 8H9
<The input value of x is H=
<The four value is equivalent is Hard
disk= If user input is 8O9
<The input value of x is O=
<The five value is equivalent is ROM
If user input is other than M, P, R, H, O character means then
<The input value of x is out of range=
<Please enter the character like M, H, O, R, and P <

90
lOMoARcPSD|27913987

FOR LOOPING

For…Next statement

In an application much of the processing may be repetitive in nature. To perform these


tasks, one would use one of the several forms of loop statements available in visual basic.
A loop comprises of instructions that are executed repeatedly until some specific condition
is satisfied.

This type of loop is called a counter – style loop process. It is done by incrementing a
counter as part of the loop processing. The syntax of the For…next statement is as
follows.

For counter = start to end [ step value ]


Statements
Next [ counter ]

Looking at the different parts of the FOR statement, one can see that the keyword FOR
begins the loop process. The variable counter contains the current iteration of the loop
during its execution. The start value represents the beginning value of the counter, and
End specifies the number at which point the loop will terminate. The option al parameter
step enables the specification of the value that is added to the counter after each iteration
of the loop.

The final statement in the loop process is Next statement, which informs visual basic that
it should increment the counter and return to the top of the loop. This statement also
checks to see whether the counter value has reached or passed the End value specified, if it
has the loop will not be repeated and execution to the next statement after the loop.

The following is the logical diagram for FOR…..NEXT concept in visual basic.

91
lOMoARcPSD|27913987

Set counter
Variable to
Starting value

If Counter YES
Greater
Value

NO

Body of
Loop

Increment
Counter
Variable

Move to
statements
After the body
Of loop

92
lOMoARcPSD|27913987

Example

For I = 1 to 5 // beginning of loop with step value as one

Print (<Welcome to FOR…NEXT Concept=)


Print (<Statements inside the looping=)
Next I // increment the value of i by one

Note
From the above example is that consist of For…Next concept. First it starts executes from
I = 1 and it check the condition for less than 5, if the condition is true then it executed the
body of the loop. Then after one time execution its counter variable <I= is increment by
default one. Then again the value of i is check the came condition in for loop and
continues the same till the condition becomes false.

Output
Welcome to FOR…NEXT Concept
Statements inside the looping
Welcome to FOR…NEXT Concept
Statements inside the looping
Welcome to FOR…NEXT Concept
Statements inside the looping
Welcome to FOR…NEXT Concept
Statements inside the looping
Example

For…next in default it checks condition in less than value and executes in


sequential order. The same way another format of for…next statement executes in
reverse order.
For I = 5 to 0
Print= Executes the loop in reverse order <
Print= The counter variable value decrease by one in default=
Next i

Note: From the above program is that the variable <I= value start execute from 5 and it
checks for greater than condition, if it is true then it execute the statements in body
of the loop.
After the execution of one iteration then the counter variable <I= is automatically
decrement value by -1. Then again it checks for condition and repeat the loop
same, till the condition becomes false.
The step value for reverse type of For…next concept is – 1 and also user can
mention the step value by -2, - 3 etc.

93
lOMoARcPSD|27913987

Output
Executes the loop in reverse order <
Print= The counter variable value decrease by one in default=
Executes the loop in reverse order <
Print= The counter variable value decrease by one in default=
Executes the loop in reverse order <
Print= The counter variable value decrease by one in default=
Executes the loop in reverse order <
Print= The counter variable value decrease by one in default=

Step statement
The step statement of the For…next loop is optional one. However, it ca be useful
depending on what a particular loop process is required to do. A step value need
not be defined while writing a for loop.
The following two statements are identical because of eh default value of step
parameter.

For I = 0 to 5
Both the statements are same action.
For I = 0 to 5 step 1

The step statement enables to skip over certain numbers or elements in an array by
changing the value by which the counter is incremented.

Sometimes there will be a need to start at the largest value and work backwards. This is
also done using the step statements. by specifying a negative value for the step, the
counter will be decreased by that value.

The step value plays an important role in for..next statement. Based on that value of step,
the control or flow of the execution of loop will be changed.

Example
For I = 10 to 0 step - 5
Print= Executes the loop in reverse order <
Print= The counter variable value decrease by user view of -5=

Next i
Output
Executes the loop in reverse order
The counter variable value decrease by user view of -5
Executes the loop in reverse order
The counter variable value decrease by user view of -5

94
lOMoARcPSD|27913987

Note:

From the above program is that the user mentioned the step value as -5. For first time the
loop starts from I = 10 then it checks for conditions and if it true then control transfer in to
body of the loop. Then it reaches the end of the loop. Through next I statement is that the
value of I is 10, that is decrement by 5 with the instruction given by step keyword. The
again it checks for another condition and if it is true then again it starts execute the body
of the loop. If the condition is false then it comes out of the loop and starts execute the
next statement in a main program.

For I = 0 to 10 step 3

Msgbox= Executes the loop in order=


Msgbox= The counter variable value increase by 3 for each execution=

Next i

Output
Executes the loop in order
The counter variable value increase by 3 for each execution
Executes the loop in order
The counter variable value increase by 3 for each execution

Executes the loop in order


The counter variable value increase by 3 for each execution

Note:
From the above program is that loop will execute or iterate till the value of I reaches 10
and for each time the step value is incremented by 3 and process for all values. Finally
comes out of the loop when it reaches false condition.

Exit For statement

For loops can be exited before the counter reaches the end point. By using the Exit for
statement, one can leave the for loop at ay point in the process, skipping over any code
after the Exit for statement and resuming after the next statement in the code.

For statement is generally used in conjunction with some type of conditional code, such as
the IF statement. The following is example program using Exit for statement.

95
lOMoARcPSD|27913987

Example
For I = 0 to 100
If aary( I ) = <test=
then Msgbox <found
test= Exit for
End if
Next I

Nested For…Next

The term nesting is nothing but the For …next consist of another For loop as an inner loop
of outer for loop.

Example
For I = 0 to 4
For j = 0 to 3
Print= Inner loop=
Next j
Print <Outer loop=
Next I

Output
Inner loop
Inner loop
Inner loop
Outer loop
Inner loop
Inner loop
Inner loop
Outer loop
Inner loop
Inner loop
Inner loop
Outer loop
Inner loop
Inner loop
Inner loop
Outer loop

96
lOMoARcPSD|27913987

Note:
From the above VB program consist of nesting for loop concept. First it starts executes the
outer loop for once then the condition is true then, control entered in to inner for ….next
loop. Then again another condition is checked in inner loop, if it is true then entered in to
body of inner loop.
Once the inner gets active, then after the one iteration is over in inner loop then the control
will again checks for another condition in inner loop. It repeats starts execution of inner
loop completely. Then control is transferred to outer loop again.
The second condition is checked again in outer loop then; control is transfer to inner loop
again. This process repeat again and again till the condition becomes false in out loop.
Totally from the above example is the outer loop executes for 4 times and inner loop
checks for 3 times. Actually the 4 x 3 = 12 time the iteration will be occurred for final
completion.

WHILE LOOPING

Do – While loop

Using the Do loop allows to repeat the code while or until a condition is met. Here we
have two format of placing the condition in looping statements.

 One is placing the condition at the beginning of the loop


 Another one is that placing the condition at the end of the loop

Example
Here the condition is checked at the beginning of the loop
Dim a as integer
a=1
Do while ( a > 5 )
Print( <While loop condition at beginning=
a=a+1
loop

Output
While loop condition at beginning
While loop condition at beginning
While loop condition at beginning
While loop condition at beginning

97
lOMoARcPSD|27913987

Note:
From the above example is that do while concept is that the condition is checked at the
beginning of the loop. Here the value of a= 1 is initialized and starts executes. First it
check the condition and if it false then it enter in to the loop. Each time the value of a = a
+ 1 is increment at the end of the loop. So final the condition reaches it true value means
then it comes out of the loop. The control is transferred to next statement of the program.

Example

Here the condition is checked at the End of the loop

General format
Do
Statements
Loop [ while (condition) ]
Dim a as integer
a=1
Do
Print( <Starts executes the loop before the condition executes=)
Print( <while loop condition at End of the loop=
a=a+1
Loop while ( a > 5 )

Output
Starts executes the loop before the condition executes
While loop condition at End of the loop
Starts executes the loop before the condition executes
While loop condition at End of the loop
Starts executes the loop before the condition executes
While loop condition at End of the loop

Note:

From the above looping concept is that the condition is checked at the end of the loop.
First it start initialize the value of a to 1. Then it starts executes the looping statement
without considering the condition and after the execution the body of the loop. At the end
of the loop the condition is checked if it is true it comes out the loop. If it is false then
starts executed the same process for specified umber of times.

98
lOMoARcPSD|27913987

The key aspect of keeping the condition at the end is that the loop will execute at least
once the looping statement will execute before the condition checks.

The following is a logical diagram for do loop concept for checking condition at the
beginning of the loop.

If Yes
Condition
check

No
Body
of
Loop

Statements
After the body
Of the loop

The following is a logical diagram for do loop concept for checking condition at the end of loop.

99
lOMoARcPSD|27913987

Body
of
Loop

No
If
Condition
check

Yes

Statements
After the body
Of the loop

From the above logical diagram of the Do … loop concept is that have slight difference in
placing the conditions.
So from that the clear idea is that Do…loop is used for looping concept. But the placing
the condition in area plays an important role in iteration purposes. Finally the key aspects
under the Do…loop concept will solve the problems for much application in easy way.
Do – Until loop
The Do…until concept is also works like as the function of the while loop concept. But
here the function is opposite of the while loop. Here it checks the condition until becomes
false. If it gets true means it starts execute the loop again and again. Finally it comes out
of the loop when its value becomes false.

100
lOMoARcPSD|27913987

General format
Do until (condition)
Statements
Loop
Example
Dim a as integer
a=1
Do until ( a > 5 )
Print <Until loop condition at
beginning= a = a + 1
Loop
Output
Until loop condition at beginning
Until loop condition at beginning
Until loop condition at beginning
Until loop condition at beginning
Note:
From the above example consist of until loop. Here it checks the condition at the
beginning of the loop. First initialize the value of a = 1 then it checks for greatest value, if
it is true then it comes out of the loop and starts executes the next statement in program.
Otherwise the condition is false then it starts executes the body of the loop till it reaches
the true value.
General format
Do
Statements
Loop until (condition)
Example
Dim a as integer
a=1
Do
Print (<Until loop condition at the end of the loop=
a=a+1
Loop until ( a > 5 )
Output
Until loop condition at the end of the loop
Until loop condition at the end of the loop
Until loop condition at the end of the loop
Until loop condition at the end of the loop
Note:
From the above visual basic program is that first initialize the variable a =1 is assigned.
Then the control directly entered in to body of the loop without any conditions. After the
execution of body statements then checks for conditions, if it is true then control is
transferred to next statement of the program. If it is false the control is transferred to the
beginning of the loop and precedes the same till the condition becomes true value.

101
lOMoARcPSD|27913987

LESSON-7
ARRAYS

Arrays
User defined data types
Data type conversions

7.1 ARRAYS

Normally the user uses Dim statement called as standard arrays and that of Redim is called
as dynamic arrays. The static arrays that do not change when between calls to the
procedure. Private and public keyword acts as an access specifier.
The private – arrays private to the form or module.
Public - arrays global to eh whole program.
Type – for arrays of user – defined types.

Normally the Dim statement used to declare the standard arrays.

Dim [ with events ] varname [subscripts] as new type, varname as new type.

The with events keywords is valid only in class modules. This keywords specified that
varname is an object variable used to respond to events triggered by an activeX object.
The varname identifier is the name of the variable you are declaring. The use of
[subscript] to declare the array.

The new keyword eables creation of an object. If the user uses the term new when
declaring the object variable, a new instance of the object is created on first reference to it.

The type arguments specifies the data type of the variable ,which may be Byte, Boolean,
Integer, Long, Currency, Single, Double, Date, String , Object, Variant. If any type is not
used then the default is Variant type is used.

Some examples for standard arrays


Dim strings(25) as string
Dim twoarrays( 15, 10) as integer
Dim test (35)
Dim num (45) as integer.

102
lOMoARcPSD|27913987

Dynamic arrays

The user can use the Dim statement to declare an array with empty parenthesis to declare a
dynamic array. Dynamic arrays can be dimensioned or redimensioned as with the ReDim
statement.

Redim [ preserve ] varname [subscripts] as type , varname [subscript ] as type

The term preserve keyword to preserve the data in an existing array when user changes the
size of the last dimensions. The varname argument holds the name of the arrays to re –
dimensions. The subscript term specifies the dimensions of the array.

The type argument specifies the type of the array. The type may be Byte, Boolean, Integer,
Long, Currency, Single, Double, Date, String, Object, Variant.

Example

Private sub form_click()


Dim string1 as String
Redim string1(15)
string1 = < welcome=
Redim string1( 35)
string1 = <Welcome to visual basic programming=
End sub

Definition:
An array is a consecutive group of memory locations that all have the same name and the
same type. To refer to a particular location or element in the array, we specify the array
name and the array element position number.

Arrays have upper and lower bounds and the elements have to lie within those bounds.
Each index number in an array is allocated individual memory space and therefore users
must evade declaring arrays of larger size than required. We can declare an array of any of
the basic data types including variant, user-defined types and object variables. The
individual elements of an array are all of the same data type.
The Dynamic Array
The programmer specifies the array type and the number of elements required by the array
so that the compiler may reserve the appropriate amount of memory. Arrays may be
declared as Public (in a code module), module or local. Module arrays are declared in the
general declarations using keyword Dim or Private. Local arrays are declared in a
procedure using Dim or Static. Array must be declared explicitly with keyword "As".

103
lOMoARcPSD|27913987

There are two types of arrays in Visual Basic namely:

 Fixed-size array: The size of array always remains the same-size doesn't change
during the program execution.
 Dynamic array: The size of the array can be changed at the run time- size changes
during the program execution.
When an upper bound is specified in the declaration, a Fixed-array is created. The upper
limit should always be within the range of long data type.
Declaring a fixed-array

Dim numbers (5) As Integer

In the above illustration, numbers is the name of the array, and the number 6 included in
the parentheses is the upper limit of the array. The above declaration creates an array with
6 elements, with index numbers running from 0 to 5.
If we want to specify the lower limit, then the parentheses should include both the lower
and upper limit along with the keyword. An example for this is given below.

Dim numbers (1 To 6) As Integer

In the above statement, an array of 10 elements is declared but with indexes running from
1 to 6.
A public array can be declared using the keyword Public instead of Dim as shown below.
Public numbers ( 5 ) as integer

Multidimensional array
Arrays can have multiple dimensions. A common use of multidimensional arrays is to
represent tables of values consisting of information arranged in rows and columns. To
identify a particular table element, we must specify two indexes: The first (by convention)
identifies the element's row and the second (by convention) identifies the element's
column.
Tables or arrays that require two indexes to identify a particular element are called two
dimensional arrays. Note that multidimensional arrays can have more than two
dimensions. Visual Basic supports at least 60 array dimensions, but most people will need
to use more than two or three dimensional-arrays.
The following statement declares a two-dimensional array 50 by 50 array within a
procedure.

Dim AvgMarks (50, 50)

104
lOMoARcPSD|27913987

It is also possible to define the lower limits for one or both the dimensions as for fixed size
arrays. An example for this is given here.

Dim Marks (101 To 200, 1 To 100)

An example for three dimensional-arrays with defined lower limits is given below.
Dim Details (101 To 200, 1 To 100, and 1 To 100)

Dynamic array
There will be e a situation when the user may not know the exact size of the array at
design time. Under such circumstances, a dynamic array can be initially declared and can
add elements when needed instead of declaring the size of the array at design time.
Dynamic arrays are more flexible than fixed-arrays, because they can be resized anytime
to accommodate new data. Like fixed-sized arrays, dynamic arrays have Public (in code
modules), module or local scope. Module dynamic arrays are declared using keyword Dim
or Private. Local dynamic arrays are declared with either Dim or Static.

e.g.: Dim dynArray ( )

The actual number of elements can be allocated using a ReDim statement. This example
allocates the number of elements in the array based on the value of the variable, x.

ReDim dynArray (x + 1)

The Redim Statement can appear only in a procedure, which is an executable statement.
The same way of declaration as used for fixed arrays is used for declaring Redim
statements also. Redim is an executable statement. The lower an upper limit for each
dimension can also be specified explicitly as in a fixed size array. An example for this is
given below.

Redim FirstArray (4 to 12)

Each time on executing the ReDim statement, the current data stored in the array is lost
and the default value is set. But if we want to change the size of the array without losing
the previous data, we have to use the Preserve keyword with the ReDim statement. This is
shown in the example given below.

ReDim Preserve dynArray (50 To 200)

When the Preserve keyword is used, only the upper limit of the last dimension in a
multidimensional array can be changed. No other dimensions or the lower limit of the last
dimension can be changed.

105
lOMoARcPSD|27913987

7.2 USER DEFINED DATA TYPES

Variables of different data types when combined as a single variable to hold several
related information is called a User-Defined data type. A Type statement is used to define
a user-defined type in the General declaration section of a form or module. User-defined
data types can only be private in form while in standard modules can be public or private.

In Visual Basic, you can declare you own types or classes in a module or form. This will
then behave as any other object in Visual Basic, except it only has properties. For
example, the Screen object in Visual Basic exposes a number of properties, including
FontCount and ActiveControl. These can be accessed by entering Screen. Font Count.
You can create a custom version of this, which will allow you to define various elements
that can store values. For example:

Type Employee Record ' Create user-defined type.


ID As Integer ' Define elements of data type.
Name As String * 20 ' Fill with 20 spaces
Address As String * 30 ' Fill with 30 spaces
Phone As Long
Hire Date As Date
End Type

This user-defined type has 5 properties. At the moment you cannot access them, as Visual
Basic requires that you declare another variable that is referenced to this user-defined
type:
Dim MyRecord As EmployeeRecord
Note that if you want to declare a Type in a form, it must be declared as private. So, the
following code fills a few values into this user-defined type:
Private Type EmployeeRecord ' Create user-defined type.
ID As Integer ' Define elements of data type.
Name As String * 20 ' Fill with 20 spaces
Address As String * 30 ' Fill with 30 spaces
Phone As Long
HireDate As Date
Private End Type

106
lOMoARcPSD|27913987

' Reference variable to user-defined type


Dim MyRecord As EmployeeRecord ' Declare variable.

' Comment1_Click event.


Sub Command1_Click()
' Assignment to EmployeeRecord variable must occur in a procedure.

MyRecord.ID = 12003 ' Assign a value to an element.


MyRecord.Phone = 1813670690
End Sub
A user defined type, or UDT, is a VB technique for defining a data type that exactly meets
the needs of your program. A UDT can contain two or more individual data items that can
be of different types, such as String and Integer. A UDT can even contain other UDTs and
arrays. You can also create arrays of a UDT.
To define a UDT, use the Type...End Type statement, which must appear in the
declarations section of a code module. Within the statement, you define the individual
items, or members, that the UDT will contain.
Here's an example of a UDT you might create for keeping track of employee data:
Public Type Employee
FirstNameAs String
LastName As String
DateOfHire As Date
Salary As Currency
EmployeeNumber As Integer
End Type

Once you define the type, you can create instances of it just like any other data type, like
so:
Dim OneEmployee As Employee
Dim AllEmployees(500) As Employee

To access the members of a UDT, you use the Name.Member notation. Here are some
examples:
OneEmployee.FirstName = "Jack"
OneEmployee.LastName = "Sprat"
AllEmployees(1).FirstName = "Maria"
AllEmployees(1).LastName = "Sanchez"

107
lOMoARcPSD|27913987

Nesting UDTs can be useful in some situations. Here's an example:


Public Type Person
FirstNameAs String
LastName As String
End Type

Public Type Employee


Name As Person
DateOfHire As Date
Salary As Currency
EmployeeNumber As Integer

End Type

7.3 DATA TYPE CONVERSIONS

Visual Basic functions either to convert a string into an integer or vice versa and many
more conversion functions. A complete listing of all the conversion functions offered by
Visual Basic is elucidated below.

Conversion To Function
Boolean Cbool
Byte Cbyte
Currency Ccur
Date Cdate
Decimals Cdec
Double CDbl
Integer Cint
Long CLng
Single CSng
String CStr
Variant Cvar
Error CVErr

108
lOMoARcPSD|27913987

A conversion function should always be placed at the right hand side of the calculation
statement.

Common Data Conversions in Visual Basic


Conversion Functions Example
Integer ANSI to String Chr Chr(66) ' returns "B"
Number to String Format, Str Format(99e2, "###,###") ' returns "9,900"
Format(Now, "mmmm yyyy") ' returns
Date to String Format
"August 1999"
DateValue,
String to Date CDate("09/99") ' returns 09/1/99
CDate
String to Number Val Val("-1.098e3") ' returns -1098

After you determine what kind of value a Variant variable or a control holds, you can
convert that argument to its associated datatype. The conversion functions shown in Table
and describe the conversions you can perform.

The data conversion functions.

Function Description
Asc() Converts its string argument to the ASCII number that matches the first (or only)
character in the string
CCur() Converts the argument to an equivalent Currency datatype
CDbl() Converts the argument to an equivalent Double datatype
CInt() Rounds its fractional argument to the next highest integer
CLng() Converts the argument to an equivalentLong datatype
CSng() Converts the argument to an equivalent Single datatype
CStr() Converts the argument to an equivalent String datatype
CVar() Converts the argument to an equivalent Variant datatype
Fix() Truncates the fractional portion
Int() Rounds the number down to the integer less than or equal to its arguments
Hex() Converts its numeric argument to a hexadecimal (base-16) value
Oct() Converts its numeric argument to an octal (base-8) value

109
lOMoARcPSD|27913987

LESSON-8
OPERATORS

Operators
String functions
String handling functions
Date and time functions

OPERATORS

In each and every language concepts the operator plays an important role for execution of
any expression or any statement. For example
Operands (variables)
A=b+c

Operator ( + )
From the above example is that, if any expression or any statement wants to evaluate the
result or value means we need operator. So without the operator for any expressions, user
can9t able to find the result for a particular expression. In given example is that user is
assigning a value for b= 5 and c = 10.

To get the result we need + operator for complete evaluation.


Result is A = 5 + 10
The output is A = 15 (we need operator called <+=)

Example
Result = (grade1 + grade2 + grade3 / nostudents)

In visual basic evaluates the expressions in parenthesis fro left to right, using pairs of
operands and their associated operator. So it adds first two grades together first. Instead of
adding the final grade, it first divides that grade by nostudents, because the division
operation has higher precedence than addition.

Consider the value is ( 4 + 10 / 2 )


=( 4 + 5 )
Result is 9
In general such expression are evaluated from left to right , when it comes to contest
between two operators , the operator with the higher precedence is used first.

110
lOMoARcPSD|27913987

The following is table displays the information for operator and operator precedence.

Arithmetic operators
1. Exponentiation - ^
2. Negation - --
3. Multiplication and division - *,/
4. Integer division - \
5. Modulus arithmetic - Mod
6. Addition and subtraction - +, -
7. String concatenation - &

Comparison operators

1. Equality - =
2. Inequality - <>
3. Less than - <
4. Greater than - >
5. Less than or equal to - <=
6. Greater than or equal to - >=

Logical operators

1. Not
2. And
3. Or
4. Xor
5. Equ
6. Imp
7. Ls

When expression contain operators from more than one category means that the arithmetic
operators are evaluated first, comparison operators are evaluated next, followed by logical
operators. All comparison operators actually all have equal precedence, which means they
are evaluated in the left to right order in which they exist in expressions. The parenthesis
operator precedence is also maintained.

STRING FUNCTION

In visual basic there are two kinds of strings are variable – length and fixed – length
strings. The user has to declare the variable length string by following way Dim
strvariable as String

111
lOMoARcPSD|27913987

A variable length string can contain up to approximately 2 billion characters, and it can
grow or shrink to match the data you place in it.
Next is that the user has to declare the fixed – length string with the help of an asterisk
character ( * ) followed by the strings length.

Dim strfixed as String * 10


From the above type of fixed length of string 10 characters. A fixed length string can
contain 1 to approximately 64 K characters.

The following table consists of various strings handling function used for different
purpose in visual basic string contents.

Strcomp Compare two strings


StrConv Convert strings
Format, Lcase, Ucase Convert to lowercase or uppercase
Space, String Create string of repeating character
Len Find length of the string
Format Format a string
Lset, Rset Justify a string
InStr, Left, Ltrim, Mid, Right, RTrim, Trim Manipulate strings
Option Compare Set string comparison rues
Asc, Chr Work with ASCII and ANSI values

Example

Consider that a string variable A$ = <welcome to coimbatore=


= len ( A$)
The output is 21 (including the blank spaces)
Thus the length function will count the each character and gives the output in numeric
value. It includes the blank space, special symbols are also considered for counting the
length of the string.

The following table consist of string function that are most common string handling
function in visual basic string function.

Function Description
Asc Returns the character code corresponding to the first letter in a string
InStr Returns the position of the first occurrence of one string within
another

112
lOMoARcPSD|27913987

InStrRev Returns the position of the last occurrence of one string within
another.
Join Lets you build a larger string out of smaller strings
Lcase Converts a string to lowercase
Left Finds or remove a specified number of character from the beginning
of a string
Len Gives the length of a string
LTrim Removes spaces from the beginning of a string
Mid Finds or removes character from the string
Replace Allows you to replace one or more occurrence of as string inside
another.
Right Finds or remove a specified number of character from the end of a
string
RTrim Removes spaces from the end of a string
Split Allows you to break up a string at specified places.
Str Returns the string equivalent of a number
StrComp Another way to do string comparisons
StrConv Converts a string from one to another
String Returns a repeated string of identical characters
Trim Trims spaces from both the beginning and end of a string
UCase Converts a string to uppercase

Sgn Function
Sgn (number) - Returns a Variant of subtype Integer that represents the
sign of a given number.

Shell Function

Shell(pathname[, window style])

Runs the executable program specified by the pathname argument and returns a Variant of
subtype Double that represents the program's task ID. If Shell is unsuccessful, it returns
zero. The optional window style argument determines the style of the window in which
the shelled program runs.

113
lOMoARcPSD|27913987

Sin Function

Sin(number) - Returns a Double value that represents the sine of a given angle (as
specified by the number argument).

SLN Function

SLN (cost, salvage, life)


Returns a Double value that represents the straight-line depreciation of an asset when
given its initial cost, salvage value at the end of its useful life, and life span.

Space Function

Space (number)
Returns a Variant of subtype String that contains a number of spaces.

Spc Function

Spc (n)

Inserts a specified number of spaces (n) when writing or displaying text using the Print #
statement or the Print method.

Sqr Function

Sqr(number)
Returns a Double value that represents the square root of a given number.

Static Statement

Static varname[([subscripts])] [As [New] type] [, varname[([subscripts])]


[As [New] type]

Declares one or more static variables, which retain their values as long as the program is
running. The varname argument is the name of the variable, and the optional As [New]
type indicates its data type. If the New keyword is used, then an implicit creation of the
object is made. The optional subscripts are the dimensions of an array variable.
Stop Statement
Stop - Suspends program execution.

114
lOMoARcPSD|27913987

Str Function

Str (number)

Returns a Variant of subtype String that is a representation of a given number.


StrComp Function
StrComp (string1, string2[, compare])

Returns a Variant of subtype Integer that indicates the result of a comparison between
two strings (string1 and string2). The optional compare argument specifies how
strings are to be compared, with 0 for a binary comparison and 1 for a noncase- sensitive
textual comparison.

StrConv Function

StrConv (string, conversion)


Returns a Variant of subtype String that has been converted from an original string as
specified by the conversion argument. The conversion argument can use several VB
constants to specify the type of conversion, such as vbUpperCase, vbLowerCase, and
vbProperCase.

String Function

String(number, character)
Returns a Variant of subtype String that is of the length specified by number and is filled
with a given character.

SYD Function

SYD(cost, salvage, life, period)

Returns a Double value that represents the sum-of-years' digits depreciation of an asset
when given its initial cost, salvage value at the end of its useful life, life span, and period
for which depreciation is calculated.

8.3 DATE AND TIME FUNCTIONS

Visual basic has many built – in function to read the information contained in the system
clock about time, day and the year. The date function returns a date of eth form month –
day – year (mm - dd – yyyy) for the current date.

115
lOMoARcPSD|27913987

By assigning a string to date in one of the following forms,


Date = <mm – dd – yyyy
< Date = <mm/dd/yyyy=

Where mm are numerals between 01 to 12, dd are days between 01 to 31 and yyyy are
years between 100 to 9999.

The user can also read the time in the system clock or temporarily reset it with the time
function. The time function returns an eight – character date of the form hh:mm:ss.

Example

Time = <hh= - sest the hour; minues and seconds are set to 0
Function Description
Now returns the date and time as stored in the system
clock
Date returns the current date
Time returns the current time

The following is table displays the date expression to display information contained in
number using format function.

Form Display
Format(Now, <m/d-yy=) 1/1/99
Format(Now,=hh:mm=) 23:05
Format(Now, <hh:mm AM/PM=) 10:05 PM
Format(Now,=hh:mm AM/PM mm/dd/yy=) 10:05 PM 05/04/99

Finally in general that the following table consists of various function in Date and Time
functions.

Function Description
Date Returns the current date from the system clock
DateAdd Lets add a specified interval to a date
DateDiff Lets subtract a specified interval from a date
DateSerial Returns a date corresponding to the specified day, month,
year
DateValue Take a string and returns a date
Day Tells you what day a string or number represents
Hour Tells you what hour a string or number represents

116
lOMoARcPSD|27913987

Minute Tells you what minute a string or number represents


Month Tells you what month a string or number represents
Now Returns the current time and date
Second Tells you what second a string or number represents
Time Tells you the current time in the system clock
TimeSerial Returns a variable of date type for the given time
Weekday Tells you what day of the week a date corresponds to
Year Tells you what year a date corresponds to

Formatting Dates and Times

Format (Now, <m/d/yy=)

Returns a format like this : [ (month)-(day)-(year) ] where the all values are in 2 digits.
Example: (5-19-06)

Format (Now, <dddd, mmmm, dd, yyyy=)

Returns a format like this: [ (day of week)-(month in words)-(day)-(year) ] where the


month is in alphabets , day is in numbers , year is in four digit number.
Example: (Thursday, April, 15, 2006)

Format (Now, <d-mmmm=)


Returns a format like this: [ (day)-(month in words) ] where the day is in digits , and
month is in words.

Example: (15 April)

Format (Now, <d-mmm-yy=)


Returns a format like this : [ (day)-(month in words)-(year) ] where days , years are in
numbers ( as discussed) and month is in 3 letter words.

Example: (15-APR-06)

Format (Now, <hh:mm AM/PM=)


Returns a format like this : [ (hour of day)-(minute of hour)] where , hour of day is in
AM./PM mode as AM/PM has been written in the format option.

Example : (08:30 PM)


if you do not specify this , it will come in a format (20:30)

117
lOMoARcPSD|27913987

Format (Now, <h:mm:ss A/P=)


Same as above, but with a little difference, here instead of AM / PM; A , P
will appear
Example : (08:30 P)

Format (Now, <d-mmmm h:mm AM/PM=)


Returns a format like this : [ (day)-(month in words)-(hours)-(minutes)-
(AM/PM) ]
Example : (15 April 8:30 PM)

Date and time functions.

Function Description
Date Returns the current date.
DateSerial(intYr, intMo, Returns an internal date value for the three arguments.
intDay)
DateAdd(strIntrvl, intN, Adds the intN value to the date specified by dteDate for the
dteDate) given strIntrvl.
DateDiff(strIntrvl, dte1, Returns the number of time intervals (specified by strIntrvl)
dte2) between the two dates.
DatePart(strIntrvl, dteDate) Returns the strIntrvl portion of the dteDate.
Now Returns the current date and time in the date format.
Time Returns the current time.
Timer Returns the number of seconds since midnight.
TimeSerial(hour, min, sec) Returns the current date and time in the internal date format
for the time specified.
Most of the time your application simply needs to know the current date or time to display
the date or time on a form or report. Use Date, Time, or Now (for both) to return the
current date, time, or both.
Note
The returned value is the internal Date data type format Visual Basic uses for variables
declared as Date data type variables. You can assign and work with dates returned from
Date, Time, and Now by assigning them to and from variables declared as Date data type
variables. When you print the value, Visual Basic respects your computer's International
Windows settings and prints the date or time in your country's format.
The serial date and time functions let you convert a three-part date into a date that matches
the internal Date data type so that you can work with variables that hold dates you specify.
For example, if you want to store the value July 18, 1998, in a Date data type variable
named dteDue, you can do so like this:

118
lOMoARcPSD|27913987

dteDue = DateSerial (1998, 7, 18)

If the year falls within the 20th century, you can omit the 19 before the year. If you try to
store a value that doesn't correspond to a proper date or time value, the IsDate() function
will return False to let you know that a bad date or time appears in the Date data type
variable.
In a similar manner, TimeSerial() returns an internal Date data type when you specify the
three time parts, like this:
dteTimePaid = TimeSerial(14, 32, 25) ' Stores 2:32:25 P.M.

The time works on a 24-hour clock, so 14 represents 2:00 in the afternoon. The Date data
type holds dates, times, and date and time values, so your Date variable will hold whatever
date or time combination you send.
The DateSerial() and TimeSerial() functions let you specify expressions inside their
argument lists to manipulate specific date and time portion values. For example, the
expression DateSerial(1998, 7, 18-31) returns the date 31 days before July 18, 1998.
Therefore, you don't have to worry about the number of days in a month or anything else.
Such calculations are useful for aging accounts receivable balances. Use an expression
inside TimeSerial () to eliminate worry with going past midnight, as in this example:
TimeSerial (14-20, 30, 16). Such an expression represents 20 hours before 2:30:16 p.m.
DateAdd(), DateDiff(), and DatePart() require a special string interval value that comes
from Table.The interval tells these date functions how to process the date argument.

Date and time interval string values.

Interval Description
h Hour
d Day
m Month
n Minute
q Quarter
s Second
y Day of year
w Weekday
ww Week
yyyy Year
Suppose the user entered a date value into a control or variable and you needed to work
with a date 30 days after that date to remind the user after 30 days that a project is due.
You can add 30 days to a date value without worrying about days in each month or year
changes (as would happen if the date fell in late December) by specifying the following

119
lOMoARcPSD|27913987

expression that adds 20 days to the date and returns another date 20 days in the future:
DateAdd("d", 20, dteUserDate). You can subtract 20 days using a negative interval.
Suppose you want the date one year from the user's date? Code this expression anywhere
you need the future date in a year and you don't have to worry about leap year:

DateAdd ("yyyy", 1, dteUserDate).

The DateDiff () function uses Table interval string value to return the number of intervals
between two dates. For example, the following expression returns the number of weeks
between two date values: dateDiff ("ww", dteUser1, dteUser2).
DatePart ("d", dteUserBDay).

Visual Basic includes three additional functions that strip off the day, month, and year
values from a Date datatype variable: Day(), Month(), and Year(). If you want to work
with the current year, you can strip off the year from the current date like this:
intYear = Year(Date) ' Get this year

120
lOMoARcPSD|27913987

UNIT – IV
Lesson – 9
Using Standard controls
Forms
Label
Text Box
Command button
Check box
Option button

Lesson - 10
Other controls
List box
Combo box
Picture box
Image controls
Scroll bars
Directory concepts
Drive List box
Directory List Box

Lesson – 11
Timer controls
Frame
Shape and Line controls
Control Arrays
Dialog boxes
Single Document Interface (SDI)
Multiple Document Interface (MDI)
Menus
Menu Editor
Menu Creation

121
lOMoARcPSD|27913987

LESSON-9
USING STANDARD CONTROLS

Using Standard controls


Forms
Label
Text Box
Command button
Check box
Option button

USING STANDARD CONTROLS

Forms

Forms are the names for windows in visual basic originally user will called windows
under design forms, and the actual result when running a window, but common usage has
named both forms. And you user can add controls to forms in the Integrated Development
Environment (IDE).

In that IDE window, at the top of the form window is title bar, which displays the form9s
title, as in default as form1. At the right in the title bar is the control box, including the
minimizing, maximizing buttons and also the close button. These are controls the user
takes for granted in most windows.

After the title bar comes the menu bar, if the user has created any menu in that form. If not
the menu will not be displayed in the form. After the menu bar the toolbar will be placed
in your form based on the user convenience.

The main area of the form is that area where everything takes place is called as client area.
In visual basic codes work with controls in the client area and leave the rest of the form to
visual basic.

122
lOMoARcPSD|27913987

The form window is used to design the different forms an application will contain an
application can have one or more forms. And each form can have many controls or tool
from toolbox that perform various function for user requirements. The forms window can
be resized to whatever size is required.

As it is resized, its new size will be displayed in the right most co –ordinate section of the
standard toolbar. The form window is an important part in IDE window. Through this
form only the user can able to design any type of application and finally getting their
objective. For each platform the work area is important one like the way the form window
is an important one in visual basic application.

Setting the title bar text in form

In default the title value or text in the form will be named as form1. If the user wants to
change the title value to the required name by using the property called caption option in
property window.

Example: If the wants the form with the title value as <My First program=

123
lOMoARcPSD|27913987

Property  caption  My First program

The form comes with minimizing and maximizing button in default at the upper right
corner of the form. If user doesn9t want the buttons means that click the property called
control box set to false. The following form is displayed with out the button for usage.

Setting form9s border

To set a form9s border style with its border style property, following are the possible
values for that property.

 0 - None
 1 - Fixed Single
 2 - Sizable
 3 - Fixed Dialog
 4 - Fixed tool widow
 5 - Sizable tool window

Adding toolbars to form

124
lOMoARcPSD|27913987

Toolbars provide buttons that corresponds to menu items and give the user an easy way to
select the commands those items corresponds.

The following is the procedure to add toolbars in to your form for easy access of user
operations.

1. Click Project  component to get the dialog.


2. Click Microsoft windows common controls box and click ok button
3. Double click the new toolbar tool in the toolbox.
4. Right click the toolbar and select the properties item.
5. Click buttons tabs in the property page and click insert button to insert a new button
in to the toolbar.
6. Give the new caption and set key property to the button.
7. Add other buttons and close the property window.
8. Double the toolbar and ready to write the coding for each option in that toolbar.

Referring the current form

While using writing the coding related to form, the user has to use the form name for
refereeing the form. For example

Form1. caption =
<welcome9 Form1. height =
150

Thus the above format is used for changing the caption and height value. Instead of that
name as form1 can be replaced as ME keyword is used for current form.
Me. Caption =
<welcome= Me. Height =
150
Note:

Thus the ME is an implicit variable, always available and stands for the current object.

Measurement in Forms

The default measurements units of forms are twips, nut the project design board want the
data entry- forms are look like real screen.

Get the dimensions of a forms client area with these properties

 Scalewidth - The width of the client area


 Scaleheight - The height of the client are a
lOMoARcPSD|27913987

125
lOMoARcPSD|27913987

 Scaleleft - The horizontal coordinate of upper left of client


area.
 Sclaetop - The vertical coordinate of upper left of client
area.

Get the overall dimensions of the form using these properties

Width - The width of the form


Height - The height of the form
Left - The horizontal coordinate of the form
Top - The vertical coordinate of the form

The scale property to set forms

0 - User defined
1 - Twips
2 - Points
3 - Pixles
4 - Characters
5 - Inches
6 - Millimeters
7 - Centimeters

Label

Label tool

The label control is used to display text that the user wants. Use can use the control to
display text that labels other parts of the form that have own captions. Despite their name,
label controls are not static. User can change the text in a label at runtime by setting its
caption property. This control will exist in toolbox, as second left in order of other tools.

126
lOMoARcPSD|27913987

To add labels

Simple click the tool, click and drag in the form. Another way is that simply double the
tool in tools box, the label with default caption as label1 is appeared in the form. Then
click the tool and select the caption property option and change the caption value to user
requirements.

To change the size of the label use size handlers that appear around a label when you
select it or use top, left, width and height properties.

In some situation user need to use the text box for displaying result, in such a cases user
can omit the text box. Instead of that user can use label tool also.

Example
A = val(text1.text)
B = val(text2.text)
C= A + B
Label1. caption = val(C)

Formatting the text in labels

Label control properties are


Autosize - makes the label size itself to fit the text
WordWrap - Enables word wrap if lines of text are too long
FontBold - makes the font bold
FontItalic - makes the font Italic
Fontname - Font style names
FontStrikethru - It strike the content
FontUnderline - It underline the contents

Aligning the text in labels

The align property of label tool using the following options

VbLeftJustify - 0 - text is left aligned


vbRightJustufify - 1 - text is right aligned
VbCenter - 2 - text is centered

127
lOMoARcPSD|27913987

Text Box
The text box is the primary input method for getting input and displaying output in visual
basic. Here name property is used for while writing coding for that tool.

Aligning the text box

The following types are the properties for aligning the text box are as follows
0 - Left justified
1 - Right justified
2 - Centered

Multiline

Click the text box in the form and go to property called multiline to true, converting a text
box into a multiline text box, complete the word wrap. The following is the example form
consists of text box and also the text box with mulitline option.

Adding Scrollbars to text boxes

In case of multiline texts used in text box the scroll bar is need for the processing. The
scroll bar property will change the display setting for text box as follows

0 - None
1 - Horizontal
2 - Vertical
3 - Both

128
lOMoARcPSD|27913987

Note:

The scroll bar property is applicable only the property called multiline property also in
state of true.

Thus the following sample window consist of that, one actual text box and the second text
box have scroll property true and multiline  true.

Locking the text box


The term lock refers that the user cannot access the particular text box for some time
period. Use the property called locked  true. This property makes the text box, that the
user cannot enter the text into the text box except under your program control.

Disabling the text box

The user can disable text box by setting the Enabled  false. It means that the user can9t
enter text in to text box; it also means the text in the box appears grayed. Disabling the
better method to indicate that the control is nit accessible.

Accessing text in text box

The user can directly enter the input value to the text box for further processing. In some
cases the user no need to enter the data directly in to the text box. Instead by help of the
coding the user can assign the content to the respective text box exist in the form.
Example

The following is the example consists of for have a text box. In that user is not typing the
content or not giving input to the text box directly. Instead they are writing the coding,
that if the user clicks the command button the content will appear in the respective text
box for further processing.

129
lOMoARcPSD|27913987

Selecting and replacing text in text box

To work with the part of the text box, user select the text you want these three properties.

SelLenght - returns or sets the number of characters selected


SelStart - returns or sets the starting point of selected text.
SelText - returns or sets the string containing the currently
selected text.

Creating password control

To hide the information in our program user can use the password control exist in visual
basic. To convert a standard text box in to password box, assign some characters to the
password char.
Property  password = < + <

130
lOMoARcPSD|27913987

The another example is that password for text box with the symbol is @ instead of using <
*<.

Command button

Command button allows the user to simply click them to perform actions. When the user
chooses the button, it not only carries out the appropriate action, it also looks as if it is
pushed and released. Whenever the user clicks a button, the click event procedure is
invoked. The code for the click event procedure can be placed to perform the desired
action.

To add a command button to the form, these steps are followed

1. Double click the icon in toolbox. This will place a new command button in the form.
2. Right click on the control and get the properties option and modify its name to user
requirements.
3. Change the properties caption = &test for user shortcuts
4. Now double the command button. Vb brings the user to code window and in that
code window, user have to write the respective coding for further actions.
5. Finally execute the form by pressing F5 and the command button will perform the
task properly for user conditions. By pressing F5 and the command button will
perform the task properly for user conditions.

Setting button caption

After the button is added in to form then, click the property window and set the caption to
user requirements. If not by writing coding also user can change the caption value for
button.

131
lOMoARcPSD|27913987

Private sub form_load)


Command1.caption = <click
here= End sub

The above coding will affect the command button to user view as follows

Caption = <click here= is added to command button while eh form load event is activated.

Setting background and text color

To change the back color of the command button is that back color property  any color
name and also style property  graphical one.

The colors available in visual basic are Button face, button shadow etc. and a palate of
colors. And the user can mention the color name by having values like RGB (Red, Green,
and Blue). The each color value range from 0 to 255.

Example
Command1.backcolor = RGB(25, 100, 200)
Command1.backcolor = RGB(2, 200, 10)
Command1.backcolor = RGB(200, 0, 50)

To user can set the color of a button caption using the button fore color property.
Example
Fore color to the button at design time

Private sub form_load()


Command1.forecolor = RGB(100, 50, 25) Not possible
Note]
The above concept of giving fore color is not possible in command button tool.

132
lOMoARcPSD|27913987

Setting button font style

To format the command button use property called  font. If the user clicks font option in
property window user will get the following dialog box.

From the above dialog box user can make change or select the required options to make
the command to formatting one.

Giving shortcut to key in buttons

The user can able to use the program or to execute the program without mouse operation
means that shortcut is available while dealing with command buttons.
The following procedure is that to access the shortcut for particular button
1. Select the button
2. Go to property option in caption
3. Type or include & symbol before the caption value
4. Then access the shortcut by using alt key + that particular alphabet

Example

Caption = <& Click here=

133
lOMoARcPSD|27913987

Short Cut to access the command button use ALT + C

Setting buttons tab order

To make your buttons easier to operate from keyboard use tab order available in visual
basic.

TabStop - indicates if this button ca accept the focus when the user
tabs into
TabIndex - is the index of the current button in the tab order.
Default - is true for one control on a form only.

Disabling and hiding the buttons

The use can disable the button by setting its enabled property to  false.

Example
Private form_load()
Comnad1.enabled = false
End sub

To hide the button in a form use the following coding in form load event

Example
Private form_load()
Comnad1.visible = false
End sub

Adding tool tips to buttons

134
lOMoARcPSD|27913987

The term tool tip is nothing but it display help information while the mouse pointer moves
over the button.
Example

The above example consists of tool tip for button, when the mouse is over the button.
Coding is done in property tool tip  content (user wants)

Check box

Option button and check box are similar to the command button control. But making them
fully functional in an application requires some additional programming.

A check box is like a light switch, it is either on or off. Option buttons work very mush the
same way because they are either on or off. However, when two or more option buttons
are on the same form, only one option can be on at one time. But the check box can able
make operate or make use one more than one at a time.

The check box is examined its value by property  value as 0, 1, 2

Here the value 0 - Unchecked


1 - Checked
2 - Grayed

Working with check box

A check box offers an option for the user. It might appear by itself as follows in dialog
box. In that dialog if the check box is clicked there will be a display check mark. If it is
again clicked the check mark will disappear. It is two state value called on / off.

If the tick is appear in the check box means that the box is assumed to present for
condition. If the tick mark is not present there means that the box is not included for
condition.

The only advantage of using the check box is that the user can select more than one box to
be considered for processing. But the option button is not applicable for this type of
conditions.

135
lOMoARcPSD|27913987

Creating a Check box

Although the basic check box has been in almost every windows application there is a
second type of check box that can be used by simply changing the style of the check box
control.
The two styles of check boxes are listed below as follows.

 Standard check boxes use the familiar box that is either empty or contains a check
mark.
 Graphical check boxes look just like a command button. However, when the
checkbox is deselected, the button is up and when the check box is selected, the
button is down.

The following shows the appearance of each of the two check box styles with actual and
graphical type.

136
lOMoARcPSD|27913987

Standard check box Graphical Check box

Note:

The method for changing the standard check box to graphical check box is that, first
property  style  graphical .Then select the down picture property and select one picture
to display in the graphical check box.

Changing the appearance of standard checkbox

When using the standard check box style, there are several properties that can be modified
to change its appearance.

 Change the font properties for the caption


 Modify both the fore color and back color
 Create either a Flat or 3D look with the appearance property
 Choose the side of the box where the caption is to displayed
 The standard check box can be disabled y setting the Enabled property of the control
to false.
These properties allow customizing the look of any form that uses check boxes.

Option button

Working with option button


Visual basic also comes with the option button control for many purposes for users. This
control lets the user select from one of several choices. However, unlike the check box,
the user can select only one option button at a time. This type of interaction is the same as
a multiple – choice test.

137
lOMoARcPSD|27913987

The way this control works, if the user selects another option button, the one that was
selected will be deselected automatically and the new one will be selected.

Note

The above for consist of option button, this button also have two state on and off, but user
can select only one option button at a time.

The option button has the same capabilities as a check box for controlling the appearance
of a single option button. The option button also is displayed as either a standard button or
as a graphical button as follows.

138
lOMoARcPSD|27913987

Standard button Graphical button

Note:
As like check box, the option buttons also have two types. To change the standard option
button to graphical type, first property  style  graphical. Then select the property 
down picture and select any picture in to that location for displaying the picture in option
button. In graphical type of option button has two state called up and down.

Setting option state

The value property for option button has true and false.

Example
Private sub form_load()
Option1.value = true
Msgbox(<welcome to visual
basic=) End sub

Option buttons groups using frames

The method to create button groups on the same form is to use a container control, which
holds other control within its frame or border.

139
lOMoARcPSD|27913987

Any control that is placed within a container control will be treated as part of that
container. When option buttons are added to a container, they will be treated as a single
group of buttons in that container. The most common container control used with option
buttons is the frame control. The frame control is used to group the different sets of option
buttons. This allows the placement of as many different sets of option buttons on a single
form as needed.

140
lOMoARcPSD|27913987

LESSON-10
OTHER CONTROLS

Other controls
List box
Combo box
Picture box
Image controls
Scroll bars
Directory concepts
Drive List box
Directory List Box

OTHER CONTROLS

List box

The List box and Combo box controls present a set of choices that are displayed vertically
in a single column. The list box control occupies a specified amount of space on the form.
If the number of items that are entered in the List box exceeds the value that can be
displayed in the area of the box, scroll bars will automatically appear on the control, which
can be scrolled up and down or left or right through the list. Users cannot enter data in the
list; they can only select items, which will be manipulated by the application.

The simple List box

The simple list box control enables to display a list from which the user can select one or
more items. To add items to the list box control, visual basic provides the AddItem
method. The list will be initialized when the form is initially loaded by using form_load()
subroutine.

The subroutine executes before the form is actually displayed. The following is the coding
for adding items to list box.
Private Sub Form_Load()
List1.AddItem ("Sirumugai")
List1.AddItem ("Coimbatore")
List1.AddItem ("Erode")

141
lOMoARcPSD|27913987

List1.AddItem ("Chennai")
List1.AddItem ("Tirchy")
List1.AddItem ("Madurai")
List1.AddItem ("Mettupalayam")
End Sub
The coding will add the items to the list box and display the window as follows.

The following coding is added to the list box click () event routine to displays the selected
item from the list box to the text box.
Private Sub List1_Click ()
Text1.Text = List1.Text
End Sub

Visual basic uses an index value to reference each item in the list. These are assigned in
the order in which the items are added to the list. The index value starts at 0 and increases
through the number of items in the list.

Two special properties are available to help the usage of the item in the list. Listcount ()
provides a current count of the items in the list. List Index () returns the index value of the
currently selected item.

142
lOMoARcPSD|27913987

An item can be removed using the RemoveItem() method. This method requires knowing
the item9s index value. For example to remove the fifth item in a list box, the code as
follows

List1. remoeitem (4)

If all the items in a list are to be removed, visual basic offers the clear method, which
invokes as

List1.clear ()
If the user wants to select more than one data item from the list, the control has a Multi –
Select property that enables the users to press CTRL key and select more than one item at
a time.

Note:

The data items placed in the list is not in order. So to make it in order use the property
name sorted that when set to true causes visual basic to reorder the list after each add or
remove operation. This means that the items can be added to the list in any order, and they
are stored in the list in proper alphabetical order.

Combo box

The combo box control also contains multiple items but occupies less space on the screen.
The combo box control is an expandable list box control; the user can expand it to make a
selection and retract it after the selection is made. The real advantage of using combo box
control is that the user can enter a new data to the list, rather than being forced to select
only the items listed.

The combo box has three formats that can be chosen from when adding this control to the
form.

 Drop down combo box - style - 0


 Simple combo box - style - 1
 Drop down List combo box - style - 2

Drop down combo box

A drop down combo box can be created by adding a combo box to the form. The drop
down combo box style is 0. The default is 0 formats. The difference between the list box
and combo box is that this combo box takes up less room and displays the list items, only
when called upon. The following is example for drop down combo box.

143
lOMoARcPSD|27913987

Simple combo box


To get the simple combo box is that style property  1. By default simple combo box do
not display their list box. In order to display the list box, the height property of the simple
combo box control must be increased to a higher value. However the list needs to be
shown all the time to allow the user to enter new values.

Note:

The important one is that the height property is to be increased to maximum, based on the
number of item exist in the simple combo box.

144
lOMoARcPSD|27913987

The Drop – Down List combo box

The only difference between the drop – down list combo box and drop down combo box
that user cannot add entries to the list or enter a value not on the list.
The drop down list simple combo box can be created by adding a combo box t to the form
and modifying the style property of the control to 2 - drop down list simple combo.

Note:
The drop down list combo box in this type of combo box the new entry or new data item is
not supposed to add in to the list at run time.

Picture box

Picture boxes are more complete controls than image controls. The user can load images
in to picture box. The picture box acts as a container for other controls. First to load a
picture in to picture box, we have two method one by property and another by coding.
1. Property  picture  locate a picture (path)
2. By writing coding as

Example

Private sub form_load ()


Picture1.picture = load picture (<Path of the picture <)
End sub

145
lOMoARcPSD|27913987

The user wants picture box to resize itself to fit the picture you will load into it, set its
Auto size property  true. The picture content to be refreshed when needed set its Auto
redraw property  true.

The picture box is very versatile and can display images from bitmap, icon, metafile,
JPEG, GIF files. To adjust the picture box to contents use the properties like Left, Top,
Height, and Width.
The picture boxes have an align property is used place the picture box at top, bottom or on
a side of the form. The possible values are
0 - Align none
1 - Align bottom
2 - Align left
3 - Align right

Handling picture box events

Responding to targeted mouse clicks in an image means creating a image map, and you
can create one with a picture box. Picture boxes have click events, but click events handles
only tell you that the picture box was clicked, not where it was clicked.

146
lOMoARcPSD|27913987

Example
Private sub picture1_click ()
Statements
End sub

The click event is useful if you want to use picture boxes as sort of image bearing buttons.
However, if you want to know where in a picture box the user clicked the mouse, use
Mouse down events. The picture boxes also support key events like KeyDown, KeyPress
and etc.

Image controls

The image control uses fewer system resources and repaints faster than a picture box.
However it supports only a subset of the picture box properties, events, and methods.

To install an image control, just use the image control tool in the toolbox. After adding the
image control to your form, just set its picture property to the image file you wan to
display.

By default, image controls shape themselves to the image you display; if you want to
stretch the image to fit the image control and not the other way around, set the image
controls stretch property to true.(default is false).

147
lOMoARcPSD|27913987

Note:

The key feature of the image tool is that have stretch property  true, means that it make
the picture in to compressed form to fit the size of the image tools.

Scroll bars

When user place a large document in the text box, only part of which is visible at once.
Using scroll bars, users can manipulate the document, moving through it as you like. User
can manipulate that document by dragging the small box in the scroll bar, which is called
the scroll bars thumb.

In visual basic have vertical and horizontal scroll bars in the toolbox. If the user adds the
tool in to the form, the use max, min properties to set the possible range of values user can
set, then read the value property to get the controls setting to change event handler.

The following is the window consists of vertical and horizontal scroll frequently used in
the visual basic.

After the scroll bar added in the form, first thing is that to set a range of possible values by
default is 0 to 32767. The maximum value a scroll bar can be set to is stored in it9s by
Max property, and the minimum value is set by min property.

Next is that the Largechange property is used when the user clicks the scroll bar itself, not
the thumb and not tan arrow button. The same way is that when the user clicks an arrow
button, the thumb moves by an amount stored in the Smallchange property. The small
change property will applied in the design tie or at runtime.

The value property holds values that can be in the range spanned by the values in the min
and max properties. When the user makes a change in a scroll bar, user will get the new
setting from the value property when the change event is triggered.

148
lOMoARcPSD|27913987

Example

Private sub form_load ()


Vscroll.min = 1
Vscroll.max= 50
Vscroll.largechange = 25
Vscroll.smalchange = 2
Vscroll.value = 40
Hscroll.min = 1
Hscroll.max= 100
Hscroll.largechange = 20
Hscroll.smalchange = 1
Hscroll.value = 50

End sub
By using enabled property is used to disable them by setting the property by false status.
The user can make a scroll bar disappear by setting its visible property to false. Both the
property is of two statuses called true and false.

Adding scroll bar to text boxes


When the text box have multiline property is to true, then it says confirmed that text box
have automatically the scroll bars will be added.
Next is that what kind of scroll bars user want to add on the text box; are horizontal ,
vertical or both, by setting the scrollbar property to the options

vbSBNone - 0 no scrollbars (default)


vbHorizontal - 1 Horizontal
vbVertical - 2 Vertical
vbBoth - 3 both vertical and horizontal

DIRECTORY CONCEPTS

Drive List box

Normally the user uses the common dialog file open and file save to get file name and file
paths from the user, but sometimes they don9t want it.
Consider for example users have a program where you want to let the user select files but
don9t want to use the dialog boxes. In such similar cases user can use the visual basic
controls called the drive list box and directory list box, and the file list box.

The drive list box tool appears as the seventh tool down on the right in the toolbox.

149
lOMoARcPSD|27913987

The user can get the currently selected drive in a drive list box by using its drive property,
and when the user change the drive in that control, a change event is generated.

Example
Sub drive1_change ()
Dir1.path = drive1.drive
End sub

Directory List Box

The directory list box control displays directories as hierarchical set of folders. This
control is one of the file controls that are intrinsic to visual basic; its tool appears as the
eighth tool.

150
lOMoARcPSD|27913987

To add a directory list box a form, just use its tool in the tool box. The important property
of the directory list box is the path property, which holds the path of the current directory
.when the user changes the current path, a change event is generated. For example, when
the user makes a change in a directory list box, dirt1 we can pass the new path to a file list
box.

Example
Sub dir1_change ()
File1.apth = dir1.path
End sub

Creating and deleting directories


User can create a new directory with Mkdir statement and remove a directory with the
Rmdir statement.

Example
Private sub command_click ()
MkDir < c:\test =
End sub

Private sub command_click ()


RmDir < c:\test =
End sub

Changing the directories


To change the default directory, use ChDir. For example where we change the default
directory to <path <

chdir. Example

Private sub command_click ()


ChDir < c:\test2
= End sub

151
lOMoARcPSD|27913987

LESSON-11
TIMER
CONTROLS

Timer controls
Frame
Shape and Line controls
Control Arrays
Dialog boxes
Single Document Interface (SDI)
Multiple Document Interface (MDI)
Menus
Menu Editor
Menu Creation

TIMER CONTROLS

One of the simplest and most misunderstood controls included with visual basic is the
Timer control. This control can be used to provide any type of time – related processing
within an application.

152
lOMoARcPSD|27913987

If Microsoft word or most other word processors are used, the user would have probably
seen something called auto save. This is when the application will periodically save what
the user is working on.

Only very little needs to be done when using the timer control. After it is placed on the
form as like above form. It appears as a small icon that invisible in runtime. There are only
three properties that should be modified.

The properties are


 The Name property
 The Interval property
 The Enabled property

As good programming practice, the timer should be named as something that related to its
task, such as clock tick, if it will be used to update a clock display. To use the control, one
needs only set the interval property to the number of milliseconds that the timer has to
wait before executing the code in its timer event routine. When the ser interval time
expires, the timer event is executed. The only way to turn off the timer is to set its enabled
property to false.

Example
Private sub form _load ()
Timer.interval = 5000 // 5000 = 5 seconds in milliseconds
Timer.enabled = true
End sub

Private sub timer_timer ()


If me.backcolor = &H800000F then
Me.backcolor = vbRed
Else
Me.backclor = &G0000000F
End if
End sub

FRAME

The method to create button or picture box groups on the same form is to use a container
control, which can hold controls within its frame or border. Visual basic comes with
several container controls that can be used for thus purpose, including the following:

153
lOMoARcPSD|27913987

 Frame
 Picture
 SSTab
 Shape

Any control that is placed within a container control will be treated as part of that
container. When option buttons are added to a container, they will be treated as a single
group of buttons in that container. The most common container control used with option is
the frame control. This allows the placement of as many different sets of option buttons on
a single form as needed.

Although the user can select only one option button from the set that is displayed on a
form, probably there is a need to present several different groups of option buttons to the
user.

To set the text that appears at upper left in a frame, you set the frame9s caption property
and also you can change the caption at runtime by setting this property. User can make
frames appear flat or 3D (by default) by setting their appearance property. And also user
can give frames tool tips i.e the explanatory text that appears in a small yellow widow
when the mouse cursor rests over a control by setting the tootip property.

154
lOMoARcPSD|27913987

Setting frame size and location

Setting a frame height and width is easy – just set the frame height and width properties at
design time or runtime. User can set the frame location in its container with its left and top
properties or by using its Move method.

Example
Private sub command1_click ()
Frame1.move frame1.left + 1000
End sub

SHAPE AND LINE CONTROLS

The user uses the shape control at design time to draw shapes on a form or picture box.
The shapes can draw are rectangles, squares, ovals, circles, rounded rectangles, and
rounded squares.

At runtime user can access and change the shape control9s properties like left, top, width,
height, backcolor, fillstyle or fill color and use the methods like move or refresh.

T o draw a shape using the shape control tool, which exist in visual basic toolbox. Simply
click and draw any shape and using the shape property user can change the style or object
to user requirements.

The shape property as follows

VbShapeRectangle - 0 (Default)
VbShapeSquare - 1
VbShapeOval - 2
VbShapeCircle - 3
VbShapeRoundedRectangle - 4
VbShapeRoundedSquare - 5

155
lOMoARcPSD|27913987

The user can set the width of the shape9s drawing line with the borderwidth property and
fill the shape using the Fillcolor and Fillstyle properties. The border style property lets you
select the style of the shape9s drawing line, including using dots and dashes.

Line control

The line control and the shape control available in visual basic can be very effectively
utilized to create very attractive graphical user interfaces.

A line control is a straight – line segment that is drawn at design time. The position,
length, color and style of the line control can be positioned to customize the look of an
application.

156
lOMoARcPSD|27913987

CONTROL ARRAYS

The controls in a control array share common properties but, just like an array, use an
index to distinguish among them. This index parameter identifies the specific control and
gives you the flexibility you will need to organize information at run time. Control arrays
also were the traditional method of adding new controls to a form at runtime and are still
useful for this task.

The following is an example consists of control array concept automatically generated in


the visual basic application. Suppose if the user adds first one text box as text1 is the name
of it. Then again adding the second text box with default name as text2, but if the user is
trying to change the name as text1 means, the visual basic immediately displays the
message box for control arrays. The following is the control array dialog box is displayed
as follows

Note:
The key aspect in control array is nothing but, to add the thing in to the list done by Load
command and to remove the thing from the list, is done by unload command.

157
lOMoARcPSD|27913987

DIALOG BOXES

The common dialog control can displays five different dialog boxes – open a file, save a
file, set a color, set a font, and prints a document. Adding a windows common dialog
control to your program is easy by following steps.

1. Select the project  component


2. Select control tab and select Microsoft common dialog control and click ok button
3. Double click the tool and add the add the code you want to open the dialog box and
make use of values the user sets.

To displays various dialog boxes use the common dialog methods are as follows.
Showopen - show open dialog box
Showsave - show save as dialog box
Showcolor - show color dialog box
Showfont - show font dialog box
Showprinter - show printer or print options dialog box
Showhelp - invokes the windows help engine

The user can set the common dialog action property to do the same thing. Here are the
values you can place in the action property.

158
lOMoARcPSD|27913987

0 - No action
1 - Displays open dialog box
2 - Displays save as dialog box
3 - Displays Color dialog box
4 - Displays Font dialog box
5 - Displays Print dialog box
6 - Runs win help 32.exe

SINGLE DOCUMENT INTERFACE (SDI)

To switch to the Single document interface (SDI)

1. Choose tools  options


2. Click on the advanced tab
3. Select the SDI development Environment check box.

159
lOMoARcPSD|27913987

MULTIPLE DOCUMENT INTERFACE (MDI)

The MDI stands for multiple document interface for windows environment in which one
widow, usually called MDI container or MDI parent form, contains many other windows,
usually called child forms.
Multiple document interface frame windows can display multiple child windows inside
them; in fact, the visual basic IDE itself is a Multiple Document Interface window.
For example, if you already have a program based on a single form called Form1, and you
want to make that into Multiple document interface
(MDI) window inside MDI fame, follows these steps.

1. Add a new MDI form to the project using the Project  Add MDI form item.
2. Select MDIChild property of the form you want to use as the MDI child form to true.
3. Run the program; the form you have made into the MDI child form appears in the
MDI form.

Note:

The one of the nicest features of visual basic MDI forms is that the menus of the parent
form change according to which child form has the focus. This lets work with specific
menus for each child form. What happens is that the menu for the child form that has the
focus appears on the menu bar of eh MDI parent form – replacing whatever menu was
previously there. The user only sees the menu for the child form when that child has the
focus.

160
lOMoARcPSD|27913987

Arranging MDI child windows:


The user could arrange the MDI child forms with their Left, Top, Width, and height
properties, but there is an easier way user can use MDI form method called Arrange().
For example, if the user adds a menu item to an MDI for named say <Testarrange= and use
the Arrange () method to arrange all the windows in the form in a cascade this way.
Private sub testarrange ()
Me. arrange vbcascade
End sub

MENUS

Designing the right kind of menus will make the application much more user – friendly.
In VB user can build up to six levels of menus. Menus that contain submenu are usually
called hierarchical menus. Using three levels is best for easy access of program, if more
than the four levels it exceeds means that will leads you to confusion. The user knows that
a sub menu lurks below a given menu item if there is a  following the menu item.

161
lOMoARcPSD|27913987

The above is an example for menu sample format for file menu exists in visual basic IDE
window.
The menu names in a program appear in the menu bar – usually just under the title bar -
and when the user selects a menu, that menu opens like an above menu.
Each menu usually contains items arranged in a vertical list. These items are often
grouped into functional groups with menus separators, or thin horizontal rules. When the
user select a menu item, that item appears highlighted; pressing enter ort releasing the
mouse button opens that item. Menu item can also be disabled (also called grayed out). A
disabled item is not accessible to the user and does nothing if selected.

Each item should have a unique access characters for users who choose commands with
keyboards. The user reaches the menu or menu item by pressing ALT key and the access
characters. The access characters should be the first letter of the menu title, unless another
letter offers a stronger link, no two menus or menu items should use the same access
characters.

MENU EDITOR

User can create menu in visual basic by using Menu editor window available by choosing
tools  menu editor (ctrl + e) whenever form is showing. The following is the windows
will displays the various options exist in menu editor window for menu creation.

162
lOMoARcPSD|27913987

The following are the various options exist in the menu editor window for various
functions for different requirements of the users.

The options are


1. Caption text box
2. Name text box
3. Ok and cancel button
4. Index box
5. Shortcut box
6. Window List check box
7. Help context ID box
8. Checked check box
9. Enabled check box
10. Visible check box
11. Arrow buttons
12. Next button
13. Insert button
14. Delete button

Example

The user wants the menu based on the following condition are
Menu 1 Show  picture1, picture 2

Menu 2 Dimension  height  Increase and decrease


Dimension Width  Increase and decrease

By using the above condition user first enter in to the menu editor window and then type
the content in caption and name textbox. Then use the arrow keys for creating sub menus
for main menu. If user needs any other options means that options will be used based on
requirements. Base on above conditions the coding in menu editor and output menu is
displayed in the following windows.

163
lOMoARcPSD|27913987

Coding done in menu editor

The output menu created in form

164
lOMoARcPSD|27913987

UNIT – V

Lesson – 12

Using Data controls


Data Access objects - DAO

Lesson - 13

Record set
Creating a Record set
Adding Records
Editing Records
Updating Records
Moving Records
Deleting Records
Sorting Records
Finding / Searching Records

Lesson – 14
Data Report
Data Environment
Report and Designer
Connection object
Command object
Data Report Controls

165
lOMoARcPSD|27913987

LESSON – 12
USING DATA CONTROLS

USING DATA CONTROLS

The database are exploring the difference between the Microsoft programming objects
sets: Data Access objects (DAO), Remote data objects (RDO), and ActiveX Data Objects
(ADO).

In Visual basic, three data access interfaces are available. They are

1. ActiveX Data Objects (ADO)


2. Remote Data Objects (RDO)
3. Data Access Objects (DAO)

A data access interface is an object model that represents various facets of accessing data.
Using visual basic, one can control the connection, statement builders and return data for
use in any application through program codes.

The reason for the existence of three data access interfaces in Visual basic is that data
access technology is constantly evolving and each of the three interfaces represents state
of the art at different times. The latest in the evolution is ADO, which features a simpler –
yet more flexible – object model than either RDO or DAO. For new projects, it is
preferable to use ADO as the data access interfaces.

Visual basic only supported DAO, which connected to the Microsoft Jet database engine
i.e. the database engine in Microsoft access. Then come to that there are other databases
types available, Microsoft created the open database connectivity ODBC standard and
supported ODBC with Remote Data Objects in Visual Basic.

There are two ways to work with the DAO, RDO, and ADO object sets in Visual basic.
The first way is working with special controls that support them; the data control supports
DAO, the remote data control supports ODBC, and the ADO data control supports ADO.
The user can use the controls to connect to and move through databases, but they don9t
actually display data, but the bound controls handle directly in code.

The second way is working with the three database object sets directly in code, without
controls like data control or the ADO data control. Next is that how to create and edit
them with the visual basic visual basic manager tool. And examine the data control,
remote data control and the ADO data control to connect to database.

166
lOMoARcPSD|27913987

Databases

The transition from a table on paper to one in a computer is natural; with a computer user
can sort, index, update and organize large tables of data in an easy way. User can connect
tables together, creating relational databases. Each individual data entry in a table, such as
students name, goes into a field in the table. A collection of fields together, such as name
and grade fields in table make up a record. Each record gets its own row in a table, and
each column in that row represents a different field.

A database is a collection of one or more tables. In DAO, those collections are called the
workspace, and in RDO, and ADO they are referred to as the data environment. One
popular way is to use Structured Query Language (SQL) , is used to set up a query in
which applied to a database gives you a record set.

The second type of database as well: relational databases. Relational data bases are called
relational because they are set up to relate the data in multiple tables together. To make a
table relational that certain fields to be primary keys and foreign keys. The primary key in
a table is usually the most important one – the one you might use to sort on, for instance.
The foreign key usually represents the primary key in another table, giving you access to
that table in an organized way.

The date control

The data control enables you to move around in a database from record to record and to
display and manipulate data from the records in bound controls. This control displays a set
of arrow buttons the user can manipulate to move through a database, and the records
from that database are displayed in bound controls. In many situation user can perform the
data access operations using the data control – without writing any code.

Data bound controls automatically displays data from one or more fields for the current
record, and the data control performs all operations on the current record. If the data
control is made to move to a different record, all bound controls automatically pass any
changes to the data control to be saved in the database. The data control then moves to the
requested record and passes back data from the current record to the bound controls is
displayed.

Visual basic uses data control properties to open selected databases, create a DAO
database object, and create a Record set object. The data controls Database and Record set
properties refer to those databases and record set objects and user can manipulate the data
using those properties.

167
lOMoARcPSD|27913987

Direct Access Object

In visual basic fist started working with database, it used the Microsoft jet database
engine, which is that Microsoft access uses. Using the jet engine represented a
considerable advance for visual basic, because it works with all kinds of data formats in
the fields of a database; text, numbers, integer, longs, single, doubles, dates, binary values,
OLE objects, currency values, Boolean values, and even memo objects. The jet engine
also supports SQL, for database programmers found attractive.

To support the jet database engine, Microsoft added the data control to visual basic and
you can use that controls to open jet database (.mdb) files. Microsoft also added a set of
Data Access Objects (DAO).

DBEngine - The jet database engine


Workspace - An area can hold one or more databases.
Database - A collection of tables.
TableDedf - The definition of a table
QueryDef - The definition of a query
Record Set - The set of records that make up the result of a
query
Field - A column in a table
Index - An ordered list of records
Relation tables - Stored information about the specific
relationship between tables.

Remote Data Object

Remote data object (RDO) connects to databases using ODBC. The user can set up the
ODBC connections to databases using ODBC item in the windows control panel, and then
use one of those connections with RDO objects. The remote data objects are designed in
parallel with the data access objects.

The remote data control is instructed to move to a different row, all bound controls
automatically pass any changes to the remote data control to be saved to the ODBC data
source. The remote data control then moves to the requested row and passes back data fro
the current row to the bound controls is displayed.

The remote data control behaves like the data control in most respects, with some
differences. Here SQL property like data controls record source property cannot accept the
name of a table by itself unless user populates tables collected.

168
lOMoARcPSD|27913987

ActiveX Data Object

ActiveX data objects (ADO) data access in database server through any OLEDB provider.
ADO is intended to give you a consistent interface for working with a wide variety of data
source, from text files to ODBC relational database to complex groups of databases.

The Microsoft implements connection to all those data sources is with the OLE db set of
com interfaces, but that standard is a very complex one. A set of objects with properties,
events and methods.

 Connection - Access from your application to a data source is through a


connection, the environment necessary for exchanging data.
The connection object is used to specify a particular data
provider and any parameters.
 Command - A command issued across an established connection
manipulates the data source is some way. The command
object lets ADO make it easy to issue commands.
 Parameter - Commands can require parameters that can be set before you
issue the command. If user requires a debit from a charge
account, user would specify the amount of money to be
debited as a parameter in parameter object.
 Record set - if user command is a query that returns data as rows of
information in a table, and then those rows are placed in local
storage in record set object.
 Field - A row of a record set consists of one or more fields, which
are stored in field objects.
 Error - Errors can occur when your program is not able to establish
a connection, execute a command, or perform an operation,
and ADO supports an error object to hold the resulting error.
 Collection - ADO provides collections, an object that contains other
objects of a particular type. ADO provides four types of
collections; the connection object has error collection, the
command object has the parameters collection, the record set
object has the fields9 collection, and the connection,
command, record set, and fields objects all have properties
collections.
 Events - ADO uses the concept of events, just like other interface
objects in visual basic. There are two types of events:
connection events where the commands are executed and
connection start or end. Record set event used to report the
progress of data changes

169
lOMoARcPSD|27913987

ADO also includes the remote data services (RDS), user can move data from a server to a
client application or webpage, manipulate the data on the client ad return updates to the
server in one round – trip.

The ADO data control is similar to the data control and the remote data control. The ADO
data control is designed to create a connection to a database using Microsoft ActiveX Data
Objects (ADO). At design time user create a connection by setting the connection string
property to a valid connection string, and then set the record source property to statement
appropriate to the database manger.

Use ca set the connection string property to the name of a file that defines a connection.
User then connect the ADO data control to a data bound controls such as the grid, data
combo, or data list control by setting its data source properties to the ADO data control. At
the runtime user can set Provider, connection string, and record source properties to
change the database.

Adding control to a program

In visual basic three data access object sets: DAO, ADO, and RDO. The first simplest
method: connecting that database to a data control in a visual basic program and using that
data control with data – bound controls.

The data control is the only intrinsic database control – in the toolbox. This control tool
appears as the tenth tool down in the toolbox. After adding the tool to the form then give
the name as caption property to the name of the database table user is working.

170
lOMoARcPSD|27913987

Opening a database with data control

To connect a data control to a database, set the data control database name property to the
path and name of the access / jet database file user want to open. Users have to select the
table you want to work with in that file with the data controls record source property.
After connection database, the drop down list box for the record source property in the
properties window.

To connect a text box to a data control, data source property to the name of the data
control. To display a particular field in the text box, place that fields name in the text box
data filed property.

Data Access objects - DAO

Working with DAO, user can use the database and record set data access objects in your
procedures. The database and record set objects each have properties and methods of their
own, and you ca write procedures that use these properties and methods to manipulate
your data.

To open a database in DAO, users just open a database object or create a new one. This
object can represent a Microsoft jet database (.mdb) file, or an ODBC database connected
through the Microsoft jet database engine. When the database object is available, user
create record set object and use that object9s methods like Movefirst and Movenext to
work with the database.

DAO also supports a client / server connection mode called ODBC Direct ODBC direct
establishes a connection directly to an ODBC data source, without loading the Microsoft
jet database engine into memory. In the ODBC diect object model, the connection object
contains information about a connection to an ODBC data source, such as the server
name, the data source name.

DAO creating a database

In the Microsoft DAO object library, to add a reference to that library, select the project 
reference menu item, select the Microsoft DAO object library and click ok to close the
reference dialog box.

Now we can make use of the data objects in that library to create a new database using
Create Database. Create database is a method of the DAO workspace object i.e. There are
a collection of workspace objects in the DAO DB engine objects workspaces collection.

171
lOMoARcPSD|27913987

The following windows are that used for initial process for creating a database for further
steps.

The following is the statement for creating a new database concept by using the given
format

Set database = workspace .createdatabase (name, locale [options])

The following is the arguments for createdatabase

 Name - a string up to 255 characters long that is the name of the database
files that you are creating. It can be the full path and file name,
such as c:\vb\text.mdb. The default extension is .mdb.
 Locale - A string that specifies a collating order for creating the database,
like dblanggeneral and dblanggreek.
The following are the possible settings for arguments.
 dbEncrypt - creates an encrypted database
 dbVersion10 - creates a database that uses the jet engine version 1 file format.
 dbVersion11 - creates a database that uses the jet engine version 1.1 file format.
 dbVersion20 - creates a database that uses the jet engine version 2 file format.
 dbVersion30 - creates a database that uses the jet engine version 3 file format.

172
lOMoARcPSD|27913987

Creating a table with TableDef object

The user can append the new table definition to a database by tabledef collection. After
the creation of a new database with DAO, the DAO project can have to create a new table
using the new table item in the file  menu.

From the above dialog box is that the user can enter name of the new table to create in the
text boxes in the new table dialog box. User can also use the information to create a new
tabledef object td, which we declare as a form –wide variable.

Dim td as tabledef
Sub createtable ()
Set td = db.createtabledef(tableform.text1.text)
Statements
From the above code will help to create a new tabledef named called td.

Adding fields to a TableDef object


The user can use that objects createfield method to do that, passing method the name of
the new field and a constant indicating that fields type

173
lOMoARcPSD|27913987

General format
Tabledef. Createfield (Field name, field type)

The following are the constant specifying the possible field types.

 dbBigInt
 dbBinary
 dbBoolean
 dbByte
 dbChar
 dbCurrency
 dbDate
 dbDecimal
 dbDouble
 dbFloat
 dbGUID
 dbInteger
 dbLong
 dbLongBinary
 dbMemo
 dbNumeric
 dbSingle
 dbText
 dbTime
 dbTimeStamp
 dbVarBinary

The following things user has to specify the names they want to give new fields in the new
table dialog boxes.
Sub createtable ()
Set td = db.createtabledef (tableform. Text1.text)
Set fields(0) = td.createfield(tableform.text2.text.dbtext)
Statements

Adding an index to a TableDef object

Use can create an index with the Dao createIndex method. The createIndex method creates
an index object, and you can make one of the fields in a table that table9s index with that
index objects createfield method.

Dim dbindex as Index

174
lOMoARcPSD|27913987

Sample

Sub createtable ()
Set td = db.createtabledef (tableform. Text1.text)
Set fields(0) = td.createfield(tableform.text2.text.dbtext)
Statements

Set dbindex = td.createindex (tabelform.text2.text & <index=)

dbindex.fields.append index field


td.indexes.append db index

Sample Code
Sample of using ADO Stream object to access BLOB data from a MySQL database.
'CREATE CONNECTION OBJECT AND ASSIGN CONNECTION STRING
Dim conn As ADODB.Connection
Set conn = New ADODB.Connection

conn.ConnectionString = "DRIVER={MySQL ODBC 3.51 Driver};" _


& "SERVER=127.0.0.1;" _
& "DATABASE=test;" _
& "UID=testuser;" _
& "PWD=12345;" _
& "OPTION=" & 1 + 2 + 8 + 32 + 2048 + 16384

conn.CursorLocation = adUseClient
conn.Open

'CREATE TABLE FOR SAMPLE CODE


conn.execute "CREATE TABLE files(" _
& "file_id SMALLINT UNSIGNED AUTO_INCREMENT NOT NULL
PRIMARY KEY," _
& "file_name VARCHAR(64) NOT NULL," _
& "file_size MEDIUMINT UNSIGNED NOT NULL," _
& "file MEDIUMBLOB NOT NULL)"

OPEN RECORDSET FOR WRITING

Dim rs As ADODB.Recordset
Set rs = New ADODB.Recordset

Dim mystream As ADODB.Stream


Set mystream = New ADODB.Stream

175
lOMoARcPSD|27913987

mystream.Type = adTypeBinary

rs.Open "SELECT * FROM files WHERE 1=0", conn, adOpenStatic, adLockOptimistic

rs.AddNew
mystream.Open
mystream.LoadFromFile "c:\myimage.gif"

rs!file_name = "myimage.gif"
rs!file_size = mystream.size
rs!file = mystream.read
rs.Update
mystream.Close
rs.Close

OPEN RECORDSET TO READ BLOB

rs.Open "Select * from files WHERE files.file_id = 1", conn


mystream.Open
mystream.Write rs!File
mystream.SaveToFile "c:\newimage.gif", adSaveCreateOverWrite
mystream.close
rs.close

OPEN RECORDSET FOR UPDATE OF BLOB COLUMN

rs.Open "Select * from files WHERE files.file_id = 1", conn, adOpenStatic,


adLockOptimistic
mystream.Open
mystream.LoadFromFile "c:\updateimage.gif"
rs!file = mystream.Read
rs.Update

mystream.Close
rs.Close

OPEN RECORDSET TO READ UPDATED IMAGE

rs.Open "Select * from files WHERE files.file_id = 1", conn


mystream.Open
mystream.Write rs!file
mystream.SaveToFile "c:\newupdatedimage.gif", adSaveCreateOverWrite

mystream.Close
rs.Close

176
lOMoARcPSD|27913987

conn.execute "DROP TABLE files"


conn.Close
msgbox "Success! Check your C:\ directory for newimage.gif and newupdatedimage.gif"

ADO (ActiveX Data Object) data control

The ADO (ActiveX Data Object) data control is the primary interface between a Visual
Basic application and a database. It can be used without writing any code at all! Or, it can
be a central part of a complex database management system. This icon may not appear in
your Visual Basic toolbox. If it doesn9t, select Project from the main menu, then click
Components. The Components window will appear. Select Microsoft ADO Data Control,
and then click OK. The control will be added to your toolbox.

The data control can be used to perform the following tasks:


1. Connect to a database.
2. Open a specified database table.
3. Create a virtual table based on a database query.
4. Pass database fields to other Visual Basic tools, for display or editing. Such tools are
bound tools (controls), or data aware.
5. Add new records or update a database.
6. Trap any errors that may occur while accessing data.
7. Close the database.
Data Control Properties:
Align - Determines where data control is displayed.
Caption - Phrase displayed on the data control.
ConnectionString - Contains the information used to establish a
connection to a database.
LockType - Indicates the type of locks placed on records during
editing (default setting makes databases read-only).

177
lOMoARcPSD|27913987

Recordset - A set of records defined by a data control9s


ConnectionString and RecordSource properties. Run-
time only.
RecordSource - Determines the table (or virtual table) the data control
is attached to.
As a rule, you need one data control for every database table, or virtual table, you need
access to. One row of a table is accessible to each data control at any one time. This is
referred to as the current record.
When a data control is placed on a form, it appears with the assigned caption and four
arrow buttons:

The arrows are used to navigate through the table rows (records). As indicated, the buttons
can be used to move to the beginning of the table, the end of the table, or from record to
record.
The Database Design
1. Open up MS Access (Start - Programs - Microsoft Access)
2. Pick "Start a blank database" from the wizard that pops up
3. Pick a spot to save the mdb file and a name for it (mine was "CDCollectionA.mdb")
4. You'll get to the following window, where you double click on "Create a table in
design view:"

the database design main window


5. When you double click that "create table in design view" you get to this window:

178
lOMoARcPSD|27913987

The table design view window


6. You want to follow the following steps to get the table

1. Make a field called ArtistName whose type is Text


2. Make a field called AlbumTitle whose type is Text
3. Make a field called Tracks whose type is Number (just a long integer is cool
enough)
4. Select the rows in the design view (as pictured above) that have ArtistName
and AlbumTitle.
5. Right-click on that selection, and pick Primary Key from the menu you get.
This will make both fields into primary keys. The idea is that they can be
primary because you'll never have identical artist names and album titles.

7. Once you've got your table built, just close that window. You'll be automatically
prompted to save changes to the table design and to give the table a name
8. Once that's all done, you can either add a couple entries to the database by double
clicking the CDs table from the database design main window and inputting them
manually.

Software Design

1. Go to the Project menu and select Components (near the bottom). You want to add
two new controls to your project:
o The Microsoft ADO Data Control (OLEDB) and
o Hierarchical Flex Grid

2. First thing first, start up VB with a Standard Exe project

179
lOMoARcPSD|27913987

3. The following stuff to your main form:


1. Change the caption of your main form to something hip and jive ...
2. Add a Hierarchical FlexGrid to your form by picking the tool and drawing it on
your main form.
3. Add an ADO data source control to the form using the tool and drawing on the
form. Change its visibility property to False.
4. Add two frames to the form using the tool and drawing them on the form.
 Change for one frame:
 its caption to Add Entry
 its (name) to fraAddEntry
 Change for the other (second) frame:
 its caption to Remove Entry
 its (name) to fraRemoveEntry
5. Draw the following controls in the Add Entry frame (yes, actually in the
frame):
1. A text box with the (name) txtArtistName
2. A label above that text box with the caption Artist Name
3. A text box with the (name) txtAlbumTitle
4. A label above that text box with the caption Album Title
5. A text box with the (name) txtTrackCount
6. A label above that text box with the caption Number of Tracks
7. A command button with the (name) cmdAddEntry and the caption Add this info
6. Now, to the Remove Entry frame, add the following controls:
0. A command button with the (name) cmdRemoveEntry and the caption
Remove Selected
1. A label with the caption Select the entry you want to remove and click the
button:

180
lOMoARcPSD|27913987

4. Now, the most complicated part is formatting the Hierarchical Flex Grid

1. the AllowBigSelection property was set to False


2. the AllowUserResizing property was set to 0
3. the FixedCols property was set to 0 while the FixedRows property was set to 1
(this is recommended for pretty displaying of stuff)
4. the FocusRect property was set to 0
5. the HighLight property was set to 1
6. the ScrollBars property was set to 2
7. the ScrollTrack property was set to True
8. the SelectionMode property was set to 1

5. In the form design window, double click the form, which should bring up the code
window with a blank Form_Load() subroutine.
o You'll notice this time that we do the data and database hookup in code instead
of in the property sheet.
o For the ConnectionString property of the ADO Data Control, you can build it
in the property sheet. There's a wizard in there that will do it from scratch for
you, but it's pretty annoying to surf through. That's why I just included this
string instead (it was built in the wizard though)
o You need two global variables, and they appear right above the Form_Load()
method.
o For the FlexGrid DataSource, note that the Set command/directive/whatever is
used!! Here's the code:

Option Explicit

Dim MinHeight As Long


Dim MinWidth As Long

Private Sub Form_Load()


// Set up the database connectivity for the ADO data control
With Adodc1
ConnectionString = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" & _
App.Path & "\CDCollection.mdb;Persist Security Info=False"

//8the record source just tells the data control what and how
//to pull out of the database.
RecordSource = "select * from CDs order by ArtistName"

//Set the Flex Grid data source to be the ADO data control.

181
lOMoARcPSD|27913987

Set MSHFlexGrid1.DataSource = Adodc1


//set up the format string for the flex grid.
MSHFlexGrid1.FormatString = "Artist Name | Album Title | Track Count"
//Position all the controls happily and store the form minimum size
MinHeight = Form1.Height
MinWidth = Form1.Width
Call Form_Resize
End Sub

Private Sub Form_Resize()

//check to see if the form is getting too small (Note: this is just to avoid

If MinHeight > Form1.Height Then


Form1.Height = MinHeight
Exit Sub
ElseIf MinWidth > Form1.Width Then
Form1.Width = MinWidth
Exit Sub
End If

'//esize the flexgrid to fit nicely on the screen


MSHFlexGrid1.Width = Form1.ScaleWidth
MSHFlexGrid1.Height = Form1.ScaleHeight / 2

// resize the happy columns to look pretty (40% for each text column, 20% for Track)

MSHFlexGrid1.ColWidth(0) = 0.4 * MSHFlexGrid1.Width


MSHFlexGrid1.ColWidth(1) = MSHFlexGrid1.ColWidth(0)
MSHFlexGrid1.ColWidth(2) = MSHFlexGrid1.Width –
(MSHFlexGrid1.ColWidth(0) * 2) - 60

fraAddEntry.Top = (Form1.ScaleHeight / 2) + 100


fraAddEntry.Height = (Form1.ScaleHeight / 2) - 150
fraAddEntry.Width = (Form1.ScaleWidth * 0.64)
fraRemoveEntry.Height = (Form1.ScaleHeight / 2) - 150
fraRemoveEntry.Top = (Form1.ScaleHeight / 2) + 100
fraRemoveEntry.Width = (Form1.ScaleWidth * 0.36) - 100
fraRemoveEntry.Left = fraAddEntry.Width + 100
End Sub

182
lOMoARcPSD|27913987

Private Sub cmdAddEntry_Click()


//add a new entry to our table.

With Adodc1.Recordset
.AddNew
!ArtistName = txtArtistName
!AlbumTitle = txtAlbumTitle
!Tracks = txtTrackCount
.Update
.Requery

End With

Private Sub cmdRemoveEntry_Click()


//delete an entry from the database

With Adodc1.Recordset
.Move (MSHFlexGrid1.Row - 1) ' we minus one because row zero is
the header row
.Delete
.Requery
End With

183
lOMoARcPSD|27913987

LESSON-13
RECORD SET

Record set
Creating a Record set
Adding Records
Editing Records
Updating Records
Moving Records
Deleting Records
Sorting Records
Finding / Searching Records

RECORD SET

Creating a Record set


After defining the database table with DAO tabledef object, user can append that object to
a database object, which adds that table to that database. User can use the openRecordset
method to open a record set and start working with data.

Set recordset = database.openrecordset (source, type, options, lockedits)


The arguments for openRecordSet
 Source - A string specifying the source of the records for the new
recordset object. The source can be tablename, a query
name, or an SQL statement that returns records.
 Type - Indicates the type of record set to open.
 Options - combination of constants that specify characteristics of the
new record set.
 Lockedits - constant that determines the locking for recordset.

The following are the possible settings for type

 dbOpenTable - Opens a table – type recordset object


 dbOpenDynamic - opens a dynamic – type recordset object, which is like an
ODBC dynamic cursor.

184
lOMoARcPSD|27913987

 dbOpenDynaset - opens a dynaset – type recordset object, which is like an


ODBC keyset cursor.
 dbOpenSnapshot - opens a snapshot – type recordset object, which is like a
ODBC static cursor.
 dbOpenForwardOnly- opes a forward ony – type recordset object.

The following are the possible settings for options

 dbAppendonly - allows users to append new records to the recordset but


prevents them from editing to deleting existing records.
 dbSQLpassthrough - passes an SQL statement to Microsoft jet connected ODBC
data source for processing.
 dbSeechanges - generates a runtime error if one user is changing data that
another user is editing.
 dbDenyWrite - Prevents other users from modifying or adding records.
 dbDenyRead - Prevents other users from reading data in table.
 dbForwardOnly - Creates a forward – only record set.
 dbReadOnly - prevents users from making changes to the record set.
 dbRunAsyn - Runs an asynchronous query
 dbExecDirect - Runs a query by skipping SQL prepare and directly calling
SQLExecDirect.
 dbInconsistent - Allows only consistent updates.

The following are the possible settings for lockedits

 dbReadonly - prevents users from making changes to the record set.


 dbPessimistic - uses pessimistic locking to determine how changes are made
to the recordset in multi user environment.
 dbOptimistic - uses optimistic locking to determine how changes are made
to the recordset in multi user environment.
 dbOptimisticvalue - uses optimistic concurrency based on row values.
 dbOptimisticbatch - enables batch, optimistic updating

185
lOMoARcPSD|27913987

Adding Records
To add a new record to a Dao record set, you use the Addnew method. After you have
updated the fields of the current record, you save that record to the database with the
update method.

Example
When the user clicks the add button in your Dao code, the daocode project, we execute the
Addnew method on the program record set and clear the two data field text boxes.

Private sub commnad1_click ()


dbrecordset. Addnerw
text1.text = < <
text2.text = < <
End sub

Editing Records
In some situation is that the user adding new record to the database, due wrong input data,
user wants to change in the existing data called editing. For such condition user wants to
edit the existing data in whole database. To do that user use the Edit method like DAO
code example

Example
Privaate sub command_click ()
Dbrecordset.Edit
End sub
After users edit the data in the records fields i.e. by entering new data in the text fields in
the dao code project. They must update the database with new data, and they do that in
that sample project by clicking the update database button. That update button will update
the content in existing database.

Updating Records

When the user changes the data in record or adds a new record, we must update the
database to record that change, and you the record set update method to do that

186
lOMoARcPSD|27913987

General format
Recordset.update ( [type [, force]] )
The following are the arguments for this function
 Type - constant indicating the type of update, as specified in
settings.
 Force - Boolean value indicating whether or not to force the
changes into the database, regardless of whether the
data has been changed by another user.

Example
Private sub commnad1_click ()
dbrecordset.fields (0) = text1.text
dbrecordset.fields (1) = text2.text
End sub
After loading the data into current records fields, we save that record to the database using
the update method.

Private sub command2 _ click ()


dbrecordset.fields (0) = text1.text
dbrecordset.fields (1) = text2.text
dbrecordset. Update
End sub

Note:
The term update is nothing but changing the existing data in to newer one for any data.
But while updating the user must consider the data and what will happens due to changes
in existing data. If not considering the whole data base data will leads to confusion and
cause whole damage to original data in the database.

Moving Records

The move term is nothing but user can move the data record value from database to any
other position. The move command performs in the following types
1. Move to first record
2. Move to last record
3. Move to next record
4. Move to previous record

187
lOMoARcPSD|27913987

To make the first record in a record set the current, the user use the Movefirst method.
Here the user wanst to move to the first record when the user clicks appropriate buttons in
DAO coding.

Example
Private subcommand4 _ click ()
Dbrecordset.MoveFirst
Statements
End sub

After moving to the first record, we display that records fields in the two text boxes.

Private sub command5_ click ()


Dbrecordset.MoveFirst
Text1.text = dbrecordset . fields(0)
Tex2.text = dbrecordset . fields(1)
End sub

To make the last record in a record set the current record, user use the Movelast method.
Here we want to move to the last record when the user clicks the appropriate button in
DAO coding.

Example
Private subcommand6 _ click ()
Dbrecordset.MoveLast
Statements
End sub

After moving to the first record, we display that records fields in the two text boxes.

Private sub command7_ click ()


Dbrecordset.MoveFirst
Text1.text = dbrecordset . fields(0)
Tex2.text = dbrecordset . fields(1)
End sub

188
lOMoARcPSD|27913987

To make to the next record in a record set, making that record the current record, user will
use the MoveNext methiod. Here in DAO project coding is used to move the next record
when the user clicks the appropriate button

Private subcommand8 _ click ()


Dbrecordset.MoveNext
Statements
End sub
Here if we check for end of the record set with EOF property is true. We should move
back one record.

Private subcommand8 _ click ()


Dbrecordset.MoveNext
If dbrecordset.EOF then
Dbrecordset.MovePrevious
Statements
End sub

If the record we have moved to is a valid record, we display its fields in the program into
text boxes.

Private subcommand8 _ click ()


Dbrecordset.MoveNext
If dbrecordset.EOF then
Dbrecordset. MovePrevious
Else

Text1.text = dbrecordset.fields(0)
Text1.text = dbrecordset.fields(0)
End if
End sub

To move to the previous record in a record set, making that record the current record, user
use the MovePrevious method. In DAO coding will mopve to the previous record when
the user clicks the appropriate button.

189
lOMoARcPSD|27913987

Private subcommand9 _ click ()


Dbrecordset.MovePrevious
Statements
End sub

If we have gone past the beginning of the record wet with the BOF property is true. We
should move forward one record.

Private subcommand10 _ click ()


Dbrecordset.MovePrevious
If dbrecordset.BOF then
Dbrecordset.MoveNext
Statements
End sub
On theother hand, if the record we have moved to is a valid record, we display its fields in
the program for corresponding text boxes.

Private subcommand11 _ click ()


Dbrecordset.MovePrevious
If dbrecordset.BOF then
Dbrecordset. MoveNext
Else

Text1.text = dbrecordset.fields (0)


Text1.text = dbrecordset.fields (0)
End if
End sub

Deleting Records
To delete a record in a DAO record set, use the Delete method, and then you update the
record set. For example when the user clicks the Delete button in our DAO coding. We
clear the two text boxes text1, and text2, that display the data for the current record and
delete that record.

190
lOMoARcPSD|27913987

Private sub command12_ click ()


Text1.text = < <
Text2.text = < <
Dbrecordset.Delete
End sub

Sorting Records

To sort a record set, you can install the index you want to sort with in the record set index
property. For example, user want to sort the record set in our DAO coding with the index
we have created this way.

Example
Sub sort _ click ()
Set dbindex = td.Indexes (0)
Dbrecordset.index = dbindx.name
Statements
End sub

After the record set is sorted, we display the first record in the two text boxes given.
Sub sort _click ()
Set dbindex = td.Indexes (0)
Dbrecordset.index = dbindx.name
Text1.text = dbrecordset.fields (0)
Text2.text = dbrecordset.fields (1)
End sub

Finding / Searching Records

User can search a record set with an index; just set its Index property to the index we want
to search and then set its Seek property to the string we want to search for. When the user
selects the search menu item in DAO coding method. We install the index based on the
first field in the record set.

191
lOMoARcPSD|27913987

Private sub search_ click ()


Set dbindex = td.indexex (0)
Dbrecordset.index = dbndex.name
Searchform.Show
End sub

After the user dismisses the search, we retrieve the text to search for that the text box and
place that text in the record sets Seek property, along with the command < = = which
indicates we want to find exact matches to the search text.
Sub searchTable ()
Dbrecordset.Seek < == . searchform. Text1. Text
Statements
End sub

Beside = , you can also search using <, > ,< =, >=. When the search is complete, we
display the found record in the text boxes.

Sub searchTable ()
Dbrecordset.Seek < == . searchform. Text1. Text
Text1.text = dbrecordset.fields(0)
Text2.text = dbrecordset.fields(1)
End sub

192
lOMoARcPSD|27913987

LESSON-14
DATA REPORT

Data Report
Data Environment
Report and Designer
Connection object
Command object
Data Report Controls

DATA REPORT

Using Crystal Reports

'Crystal Reports' is a popular third party package that is included with Visual Basic, which
allows you to create reports for your application. The package consists of a designer - where you
can design and test the reports, Crystal Reports API calls and Crystal Reports control.
Note: Crystal Reports is shipped and installed as part of the VB installation package except in VB6. This can
be found in \common\tools\crysrep double click on crystl32.exe to install.

To access the Crystal Report Designer, select the Report Designer from the Add-In menu in the
VB environment. Following is the sample screen for crystal report.

193
lOMoARcPSD|27913987

While you are in design mode you can draw and arrange the data fields on the report. This
is done in a similar way to creating controls on a form in VB.
Start the Crystal Reports Designer Create a new report by choosing File menu - New and
the Create New Report dialog box will appear (see picture below)

Click on the Custom button to display the Choose Report Type and Data Type frames.
Select the Custom Report and click on the Data File.
Specify the location of the BIBLIO.MDB Access database
Select which tables from the database you want. For this example we will need the authors
table and the Title table.
Check that the joins are correct in the Linking Export

194
lOMoARcPSD|27913987

Drag and drop the fields you want on to the report. So that it looks like the report above.
Now if you run it by selecting Print Preview, you can see what the report looks like. Now
save the report and we have a template that now can be used in VB.
Note: Turn off the Save Data with report option if you want the data to contain new
information each time the report is used. Going to the File menu, selecting Options and
clicking on the Reporting Tab sets the option
There are many options in the Crystal Reports and but one important thing to do is to get
specific data. This is done by a selection formula (i.e. the Where clause of a SQL statement).

DATA ENVIRONMENT

Using the Data Environment Designer


The Data Environment provides a way for you to handle multiple Connection Objects that
are associated with your programming project. The Data Environment Designer (DED)
provides you with a visual interface for managing an instance of the Data Environment.
Through the DED you can add, modify and delete the connections to data sources within
the project. In addition, the DED provides an easy method of creating the Command
objects that provide the links to specific sets of records in the data sources identified by
the Connection objects. Finally, the DED provides the simplest way of creating the
parent/child queries that are necessary for use with the Hierarchical Flex Grid and with
master/detail data screens.

195
lOMoARcPSD|27913987

The first step in using a Data Environment in your program is to add an instance in your
project. You do this by selecting the Data Environment item from the More ActiveX
Designers submenu of the Project menu. (You can also select this option from the Add
button on the main toolbar.) This menu item adds an instance of the Data Environment to
your project and opens the DED window, as

Figure 1: The Data Environment Designer.

If you look at the project references for your project, you will notice that adding the Data
Environment adds a reference to the Microsoft Data Environment Instance 1.0 and to the
Microsoft ActiveX Data Objects 2.0 Library, as shown in Figure 2. The Data Environment
is based on ADO, and you will need some ADO code in many of your applications.

Creating a Connection in the Data Environment


The DED starts out with a single Connection object in the Data Environment. This
Connection object enables you to create a link to a single data source, such as a Jet

196
lOMoARcPSD|27913987

database or SQL Server data source. You set up the link to the data source by setting
properties of the Connection object. Activity 1 walks you through the process of creating
the link to a Jet database.

Activity 1
1. Start a new Standard EXE project.
2. Add a new Data Environment to the project by choosing the Add Data Environment
item from the Project menu. If this option is not available, choose the Components
item from the Project menu and click the Data Environment option on the Designers
page of the Components window to make this item appear on the project menu.
3. Open the instance of the Data Environment in the project by double-clicking the
object in the Project window.
4. Right-click the Connection1 objects in the DED and select Properties from the pop-
up menu to bring up the Data Link Properties dialog box for the connection.
5. On the first page of the properties, select the Microsoft Jet 4.0 OLE DB Provider for
the connection.
6. After selecting the provider, click the Connection tab of the Data Link Properties
dialog box. This page of the dialog enables you to select the specific source of the
data for the connection. The content of this page varies depending on the data
provider that you need. For the Jet data provider, you select the name and path of the
database to which you are connecting. You may also need to provide the security
information for the database if it is secured. For this activity, select the Nwind.mdb
database that comes with Visual Basic.
7. After selecting the database name, test the connection by clicking the Test
Connection button on the dialog. This creates a temporary connection to the database
to ensure that all necessary parameters have been specified correctly. If everything is
OK, you should receive the "Test connection succeeded" message. Otherwise, you
receive an error message describing the problem.
8. Close the dialog by clicking the OK button. Your connection to a database is now set
up.
9. You will probably notice that the DED gives the first connection a default name of
Connection1. To change this name, click the connection to the DED and type a new
name, or change the Name property of the connection in the Properties window in
Visual Basic.

197
lOMoARcPSD|27913987

REPORT AND DESIGNER

The Sample Database


Consider the folllowing sample database used for creating data report.
EMPLOYEE.MDB contains three tables: EmpMast, DeptMast, and JobMast. The tables
are structured as follows:

EmpMast table:
Field Name DataType Comments
EmpNbr AutoNumber Primary Key. Uniquely identifies each
employee in the database.
EmpFirst Text (50) Employee's first name
EmpLast Text (50) Employee's last name
DeptNbr Number (Long Integer) Foreign Key to PK of DeptMast table.
Identifies which department the
employee works in.
JobNbr Number (Long Integer) Foreign Key to PK of JobMast table.
Identifies the employee's job.
HireDate Date/Time Date the employee was hired
HrlyRate Number (Single) Employee's hourly rate
SchedHrs Number (Single) The number of hours per week the
employee is scheduled to work.

DeptMast table:
Field Name DataType Comments
DeptNbr Number (Long Integer) Primary Key; uniquely identifies each
department in the database.
DeptName Text (50) The name of the department.
Location Text (50) The department's location (could be a
building, suite number, floor, etc.)

JobMast table:
Field Name DataType Comments
JobNbr AutoNumber Primary Key; uniquely identifies each job
in the database.
JobTitle Text (50) The job title (description).
MinRate Number (Single) The minimum hourly rate that somebody
working in this position is usually paid.
AvgRate Number (Single) The average hourly rate that somebody
working in this position is usually paid.
MaxRate Number (Single) The maximum hourly rate that somebody
working in this position is usually paid.

198
lOMoARcPSD|27913987

Designing the Reports

From the above databses the following two types of reports will be developed and named
as : "Annual Salary Expenses by Department" and "Annual Salary Expenses by Job".

For the Annual Salary Expenses by Department report, you want to show various fields
from the employee database tables grouped and subtotaled by department. You also want
to show a grand total at the end of the report. A sketch of the design might look something
like the following:

Annual Salary Expenses by Department

JOB WKLY HRLY


EMP # EMP NAME # JOB TITLE HIRE DATE HOURS RATE ANN SALARY

DEPT XXXX XXXXXXXXXXXXXXXX


XXX XXXXXXXXXXXXXXX XXX XXXXXXXXXX XX/XX/XX XX.XX XX.XX
$XXX,XXX.XX XXX XXXXXXXXXXXXXXX XXX XXXXXXXXXX XX/XX/XX XX.XX
XX.XX $XXX,XXX.XX DEPT XXXX XXXXXXXXXXXXXXXXXXXXXXXX TOTALS:
$XXX,XXX.XX

GRAND TOTALS: $XXX,XXX.XX


The design of the Annual Salary Expenses by Job report is similar, except that you want to
show various fields from the employee database tables grouped and subtotaled by job.
You might sketch the design as follows:

Annual Salary Expenses by Job

DEPT WKLY HRLY


EMP # EMP NAME # DEPT NAME HIRE DATE HOURS RATE ANN SALARY

199
lOMoARcPSD|27913987

JOB XXX XXXXXXXXXXXXXXXX


XXX XXXXXXXXXXXXXXX XXXX XXXXXXXXXX XX/XX/XX XX.XX XX.XX

$XXX,XXX.XX XXX XXXXXXXXXXXXXXX XXXX XXXXXXXXXX XX/XX/XX XX.XX

XX.XX $XXX,XXX.XX JOB XXX XXXXXXXXXXXXXXXXXXXXXXXX TOTALS:

$XXX,XXX.XX

GRAND TOTALS: $XXX,XXX.XX


The following is he step-by-step process for designing the first report, "Annual Salary
Expenses by Department". Once that is done, it will be a simple matter to copy that report
and modify it to create the Annual Salary Expenses by Job report. With the report designs
in mind, open Crystal Reports (Report Designer) from the VB Add-Ins menu:

A registration form appears. Click the Cancel button.

200
lOMoARcPSD|27913987

From the Crystal Reports File menu, select New:

The Create New Report dialog box appears. Click the Standard button.

The Create Report Expert dialog box appears with the


Step 1: Tables tab open. Click the Data File button:

The Choose Database File dialog box appears. Navigate to the directory where your
database file resides, then click the name of the database file so that it appears under "File
Name:". Click the Add button, then click the Done button.

201
lOMoARcPSD|27913987

Step 2: Links tab then appears, showing you a diagram similar to that of Access'
Relationships diagram.

202
lOMoARcPSD|27913987

Step 3: Fields tab.


The "3: Fields" tab initially looks like this:

Using the "Add ->" button, select the desired fields from the "Database Fields" listbox so
that they appear in the "Report Fields" listbox. Select the fields based on the initial design.
For fields that are involved in a primary key and foreign key relationship, only select one
of those fields from either table (for example, select the DeptNbr field from either the
DeptMast table OR the EmpMast table, but not both).
Select the following Database Fields:
Select DeptNbr and DeptName from the DeptMast table.
Select EmpNbr From the EmpMast table.
Skip down to the JobMast table and select the JobNbr and JobTitle.
Jump back up to the EmpMast table and select the HireDate, HrlyRate, and SchedHrs.
Your screen should look like this:

203
lOMoARcPSD|27913987

You can specify column headings by selecting each of the Report Fields in turn, and
giving them a heading by typing the desired text in the "Column Heading:" textbox (by
default, the column heading is the same as the field name).
Specify the column headings as follows:

Report Field Column Heading


DeptMast.DeptNbr Dept #
DeptMast.DeptName Dept Name
EmpMast.EmpNbr Emp #
JobMast.JobNbr Job #
JobMast.JobTitle Job Title
EmpMast.HireDate Hire Date
EmpMast.HrlyRate Hrly Rate
EmpMast.SchedHrs Wkly Hours

Click the Formula button. The "New Formula" dialog box appears. Type EmpName in the
textbox and click OK

204
lOMoARcPSD|27913987

The "Edit Formula" dialog box appears. In the "Formula text" area, type: TrimRight
({EmpMast.EmpLast}) + ", " + TrimRight ({EmpMast.EmpFirst}
Your screen should look like this:

Note: Crystal Reports has its own formula syntax, which differs from the syntax of VB
and Access expressions. You can scroll the "Fields", "Functions", and "Operators"
listboxes above the Formula text entry area to see what's available. Also, instead of typing
everything directly into the text entry area, you can double-click on a listbox selection and
the text of that selection will appear in the Formula text box.

Step 4: Sort tab


Select DeptMast.DeptNbr from the "Report Fields" list and click the "Add->" button.
DeptMast.DeptNbr then appears in the "Group Fields" list. Repeat this process for
@EmpName.

205
lOMoARcPSD|27913987

Step 5: Total tab.

Within this Total tab, an inner tabbed dialog appears, with one tab for each field selected
in the sort. On the "DeptMast.DeptNbr" tab, remove all items except "@AnnSal" from the
Total Fields list, as shown below. What we are saying is that we want to print a subtotal
for the annual salary every time there is a change, or break, in the department number.

Still in the step 5: Total tab, click the "@EmpName" tab and remove all items from the
Total Fields list i.e We don't want to print subtotals after every employee name.

206
lOMoARcPSD|27913987

We don't need to do anything in tab 6,


Step 7: Style tab. For the title, type "Annual Salary Expenses by Department".

Click the Preview Report button. At this time, the "Create Report Expert" is finished and
you can't go back to it, but you can make any desired changes in the Crystal Reports
interface. Following is the screen that is initially displayed after you click the Preview
Report button from Step 7 of the Expert:

207
lOMoARcPSD|27913987

208
lOMoARcPSD|27913987

CONNECTION OBJECT
Visual Basic 6 obsoletes the previously used database access technology provided by Jet
and provides a new one known as ADO or Active Data Objects. This technology allows
users to access data easily from many existing databases (such as Access or Paradox) or
from ODBC compliant databases like Oracle or MS SQL Server. Using ADO is quite
simple and allows programmers to provide flexible database front ends to users that are
reliable and include many features. As a VB6 programmer ADO is important to know as
most commercial VB programming exercises involve providing a front end to some sort of
database.
Following are some of the key objects found in the ADO object model and some of their
key methods and properties.

Connection Object
This object represents an open connection to the data source. This connection can be a
local connection (say App. Path) or can be across a network in a client server application.
Some of the methods and properties of this object are not available depending on the type
of data source connected to.
Key Properties

Name Data Type Description


Defines in string form the location of the data source
you wish to connect to. Key fields in the string you
will use are the "Provider=" and the "Data Source="
fields. You may also use the "Mode=" field. See
descriptions of those properties for a more detailed
view of each one. Some examples of connection
strings follow:
ConnectionStrin g Data Source=c:\test.mdb;Mode=Read|Write;Persist
String
- Connects to an Access database with read/write/persist
permissions

driver={SQL Server)
server=bigsmile;uid=sa;pwd=pwd;database=p ubs -
Connects to an SQL Server database called bigsmile as
user sa with password pwd to
database pubs.

A string defining the provider of a connection


object. An example follows:
Provider String Provider=Microsoft.Jet.OLEDB.4.0 -This string
connects to a MS Jet 4.0 compliant database (an
Access DB for example.)
Mode connectModeEnum Sets (or returns) the permissions for modifying

209
lOMoARcPSD|27913987

data across the open connection. Available


permissions include Read, Write, Read/Write, and
various Share/Deny types.

Sets the location of the cursor engine. You can


select client side or server side, for simpler
CursorLocation cursorLocationEnum
databases (like Access) client side is the only
choice.
Time in seconds that a connection will attempt to be
ConnectionTimeout Long opened before an error is generated.
Time in seconds that an command will attempt to be
CommandTimeout Long executed before an error is generated.

Key Methods

Name Description
Close Closes an open connection.
Opens a connection with the settings in the
Open Connection String property.

COMMAND OBJECT

A command object specifies a specific method you intend to execute on or against the data
source accessed by an open connection.

Key Properties

Name Data Type Description


Defines the Connection
conConnection as
ActiveConnection object the command
ADODB.Connection belongs to.
Contains the text of the
command you want to
execute against a data
source. This can be a
table name, a valid
SQL string, or the
CommandText String
name of a stored
procedure in the data
source. Which one you
use is determined by
the CommandType
property.

210
lOMoARcPSD|27913987

Defines the type of the


command. The three
most commonly used
would be adCmdText,
adCmdTable, and
adCmdStoredProc. The
setting adCmdText
causes the
CommandText string
to be evaluated as an
SQL string. The setting
adCmdTable causes
CommandType commandTypeEnum the CommandText
string to be evaluated
as a table name and
will return the all of
the records and
columns in a table. The
setting
adCmdStoredProc
causes the
CommandText string
to be evaluated as a
stored procedure in the
data source.

Key Methods

Name Description
Executes the query, SQL statement, or stored procedure
Execute specified in the Command Text property and returns a
Record Set object.

ADO and the Command Object

The place of the command object in relation to the other objects in the ADO object model.
The command object can query the data source and return a RecordSet Object. By
providing the name of a parameterized query, or the name of a table in the database, or a
stored procedure, the command object can be used to execute instructions and also return
the results of the execution.
The picture shown next also shows that the Parameters collection and Parameter object
are related to the Command object. While the command object can execute a query
repeatedly, it can also execute multiple queries.

211
lOMoARcPSD|27913987

Properties and Methods of the Command Object

Provide a reference to ADO 2.8 library

Before looking at any of the ADO objects, it is necessary to add a reference to the ADO
library. By default, it may already have been added (ADO2.1) and it will be necessary to
change it to a version higher than 2.5.
The following window may be accessed by clicking on the Components drop-down menu
when you click the menu item Tools when you are in the Microsoft Visual Basic screen.

212
lOMoARcPSD|27913987

However, if you learn to use the command object right from the start, you'll find that it
makes manipulating recordsets much simpler and gives you more options. First, you must
create the command object. You do this with the following piece of code:

'Create Command Object


Dim objCmd 'Declare the command variable
Set objCmd = Server.CreateObject("ADODB.Command")
Set objCmd.ActiveConnection=objConnect
objCmd.CommandType = adCmdText

213
lOMoARcPSD|27913987

Note that you set the command object's ActiveConnection property to your connection
object, which you created above. Also note that, in this case, our CommandType is text.
This allows us to send SQL commands directly to the database server. If you are using
SQL Server as your database, the other command types may prove useful, but for most
third party databases, such as Oracle or Informix, you are best off sticking with
adCmdText.

Also note that adCmdText is a constant. The numeric equivalent is 1. The ADO constants
are in a file called adovbs.inc. If you have not already included this file in your current
page, locate it copy to your web directory and rename it adovbsinc.asp. Finally, add this
line to the very top of your ASP page:

<!--#INCLUDE VIRTUAL="/yoursubdirectory/adovbsinc.asp"-->

The reason for renaming it is for security purposes -- malicious users can more easily
access a file on your server ending in .inc than one ending in .asp. Although this file is
rarely changed and most ASP developers know its contents, it's just good practice not to
have any of your code visible to web users.

DATA REPORT CONTROLS

One way of creating a data report is to:

1. Create a Data Environment designer containing a hierarchy of Command objects.

2. Set the DataSource property of the Data Report designer to the Data Environment
designer.

3. Set the DataMember property to the topmost Command object.

4. Right-click the Data Report designer and click Retrieve Structure.

After retrieving the structure, an appropriate number of Group headers and


footers will be created, and each header/footer pair is assigned a name that
corresponds to a Command object.

5. Drag Command objects from the Data Environment designer to the


corresponding section on the Data Report designer.All of the data fields
contained by a Command object are automatically created on the data
report as TextBox controls on the section where the Command object is
dropped. The DataMember and DataField properties of each TextBox are
set in accordance with the Command object and its data fields.

214
lOMoARcPSD|27913987

6. Drag TextBox controls from the section where each was created onto a
different section of the Data Report designer.

7. Add Function controls as needed to the report. When the data report is bound
to a data environment, the rules for placement of controls on the report are not
immediately apparent. This topic explains how the hierarchy created in the data
environment relates to the system of group headers and footers constructed in the
data report.

Hierarchy versus Headers, Footers, and Detail

The following picture shows a schematic view of the Data Environment designer with four
Command objects, each in a parent/child relationship with at least one other command.
The data fields that belong to the table are not shown.

The Data Report designer, on the other hand, is constructed as a series of sections. And
each section can be categorized into one of four types: Report header/footers, Page
header/footers, Group header/footers, and the Detail section. For the purposes of
instruction, we can disregard the Report and Page header/footer pairs. This leaves the
Group headers/footers and the Detail section.
The Detail section, the innermost section of the designer, corresponds to the lowest-level
Command object. As you go up through the hierarchy, the Detail section is bracketed by
pairs of sections, with each pair associated with a single Command object. The figure
below correlates the Command objects with the sections:

215
lOMoARcPSD|27913987

Sections Corresponding to Command Objects

Thus the figure shows that the hierarchy of the data environment actually corresponds to
an expanding series of brackets, with the innermost (Detail) section corresponding to the
lowest level of the hierarchy, and the outermost corresponding to the highest-level
Command object.

Controls Can Be Placed in Any Section in a Lower Level

The placement of a control is governed by what section (or pair of sections) it belongs to.
A control can be placed in the section where it originates, and in all sections that are at a
level lower than itself. For example, if a control belongs to the Command1 section pair, it
can also be placed in the section pairs for Commands 2, 3, and 4. A second example: A
control that originates in section 3 can also be placed in section 4, but not in sections 1 and 2.

Placing the Function Control


The Function control has three exceptions to the above guidelines regarding control
placement. The Function control is not directly bound to the record set, as is the TextBox
control. Instead, the Function control calculates its value as the report is generated. For
this reason, a Function control can only be placed in Footer sections of the report.
A second exception for the Function control: it can only be placed in any section pair that
is one level above its own. For example, if the Command 3 object contains a Quantity
field, you can place a Function control that sums the Quantity values onto the footer
section for Command 2, or the footer section for Command 1.
The third exception concerning the Function control is this: unlike the other data-bound
control (the TextBox control), the Function control can be placed in the Report Footer
section. When you do so, the scope of the control's calculation will be increased to include
the whole report. For example, a Function control placed in the Report footer to calculate
the sum of the Quantity field will calculate the sum of every Quantity control on the
report.

216
lOMoARcPSD|27913987

The Exceptions: Grouping and Grand Total Aggregate


With two exceptions, every Command object in the Data Environment corresponds to a
pair of group headers and footers. The first exception occurs when you use the Grouping
feature of the Data Environment designer.

Grouping Fields

When you create grouping fields, the Data Environment designer creates two folders
under a single Command object. The first contains the grouping fields, and the second
contains the Detail fields. Even though a new Command object is not created for the
grouping fields, you must create a new group header/footer pair on the data report and this
requirement qualifies it as an exception.

Grand Total Aggregate Fields

The second exception occurs when you create a Grand Total aggregate field in the data
environment. As happens when creating a grouping field, a new folder is created for the
Command object. The new folder contains any Grand Total aggregate fields created, and
you must add a new group header/footer pair to the data report.

217

You might also like