SDVB Notes
SDVB Notes
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
UNIT
III
5 Functions 72
7 Arrays 102
8 Operators 110
UNIT
IV
9 Using Standard Controls 122
UNIT
V
12 Using Data Controls 166
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
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.
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
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:
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).
6
lOMoARcPSD|27913987
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 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.
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
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 file sharing has both unique benefits and unique risks.
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
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
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.=
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
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.
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
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.=
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
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.
Transition costs training. Here are some numbers published by Forrester Research, Inc., a
Cambridge, Massachusetts consultancy. These costs include training and lost productivity:
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:
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
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.
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
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.
21
lOMoARcPSD|27913987
Components of the client server computing can be grouped into four categories of
architecture.
Business solutions architecture
Application architecture
Platform architecture
Technical architecture
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
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
Business solutions
Application Architecture
Infrastructure
Technical Architecture
System software
Platform
TYPES OF ARCHITECTURE
23
lOMoARcPSD|27913987
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
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.
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.
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
30
lOMoARcPSD|27913987
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
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.
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
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
36
lOMoARcPSD|27913987
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
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.
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:
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).
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.
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.
Global Items
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)
42
lOMoARcPSD|27913987
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.
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
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 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.
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 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
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.
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
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.
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
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.
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.
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.
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.
54
lOMoARcPSD|27913987
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.
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.
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.
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.
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.
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.
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 example shows a routine in visual basic using DIM statement.
Output
This is demo welcome to India
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
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
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:
Global Items
Declared with PUBLIC
Form
Private variables
Available to this form only
Procedure Procedure
Local Local
Variables Variables
63
lOMoARcPSD|27913987
Module
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
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
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.
Const Pi = 3.14159
Radius = 15
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.
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
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
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.
73
lOMoARcPSD|27913987
Example
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.
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
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:
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
End sub
Print <the result is <, test // finally it print the result value
Example
In code window
Dim A, B as integer
End sub
Print <the result for R <, r // finally it print the result value for r
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
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.
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.
a = val(text1.text)
print <the result evaluate in sub procedure <, res //print the result
77
lOMoARcPSD|27913987
Example
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.
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
Test (A)
End sub
R = test ( x + 25 )
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.
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.
79
lOMoARcPSD|27913987
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
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
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
81
lOMoARcPSD|27913987
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 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.
Example
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.
IF (Condition) then
True block statements
Else
False block statements
Example
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.
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.
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.
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.
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
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
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.
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
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
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
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
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.
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.
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
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.
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.
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.
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
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
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
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.
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.
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.
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.
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.
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.
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
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:
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
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
End Type
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.
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.
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.
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.
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.
The following table consists of various strings handling function used for different
purpose in visual basic string contents.
Example
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
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
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
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 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
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
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.
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
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
Returns a format like this : [ (month)-(day)-(year) ] where the all values are in 2 digits.
Example: (5-19-06)
Example: (15-APR-06)
117
lOMoARcPSD|27913987
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
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.
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:
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
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.
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
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.
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
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.
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.
125
lOMoARcPSD|27913987
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)
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.
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.
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.
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.
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
To work with the part of the text box, user select the text you want these three properties.
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.
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.
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
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.
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
132
lOMoARcPSD|27913987
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.
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
133
lOMoARcPSD|27913987
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.
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
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.
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
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
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.
When using the standard check box style, there are several properties that can be modified
to change its appearance.
Option button
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
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.
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
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 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
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.
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
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 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
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
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
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.
DIRECTORY CONCEPTS
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
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
Example
Private sub command_click ()
MkDir < c:\test =
End sub
chdir. Example
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.
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
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 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
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.
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.
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.
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
159
lOMoARcPSD|27913987
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
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.
Example
The user wants the menu based on the following condition are
Menu 1 Show picture1, picture 2
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
164
lOMoARcPSD|27913987
UNIT – V
Lesson – 12
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
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
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 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
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).
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 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.
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.
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
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.
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.
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
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
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.
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
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.
174
lOMoARcPSD|27913987
Sample
Sub createtable ()
Set td = db.createtabledef (tableform. Text1.text)
Set fields(0) = td.createfield(tableform.text2.text.dbtext)
Statements
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.CursorLocation = adUseClient
conn.Open
Dim rs As ADODB.Recordset
Set rs = New ADODB.Recordset
175
lOMoARcPSD|27913987
mystream.Type = adTypeBinary
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
mystream.Close
rs.Close
mystream.Close
rs.Close
176
lOMoARcPSD|27913987
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.
177
lOMoARcPSD|27913987
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:"
178
lOMoARcPSD|27913987
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
179
lOMoARcPSD|27913987
180
lOMoARcPSD|27913987
4. Now, the most complicated part is formatting the Hierarchical Flex Grid
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
//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
//check to see if the form is getting too small (Note: this is just to avoid
// resize the happy columns to look pretty (40% for each text column, 20% for Track)
182
lOMoARcPSD|27913987
With Adodc1.Recordset
.AddNew
!ArtistName = txtArtistName
!AlbumTitle = txtAlbumTitle
!Tracks = txtTrackCount
.Update
.Requery
End With
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
184
lOMoARcPSD|27913987
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.
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.
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.
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.
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
If the record we have moved to is a valid record, we display its fields in the program into
text boxes.
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
If we have gone past the beginning of the record wet with the BOF property is true. We
should move forward one record.
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
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
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
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
'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
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
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.
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
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
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:
199
lOMoARcPSD|27913987
$XXX,XXX.XX
200
lOMoARcPSD|27913987
The Create New Report dialog box appears. Click the Standard 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
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:
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.
205
lOMoARcPSD|27913987
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
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
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.
209
lOMoARcPSD|27913987
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
210
lOMoARcPSD|27913987
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.
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
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:
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.
2. Set the DataSource property of the Data Report designer to the Data Environment
designer.
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.
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
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.
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.
216
lOMoARcPSD|27913987
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.
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