Documenti di Didattica
Documenti di Professioni
Documenti di Cultura
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
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 Bars – 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) – Menus – Menu
Editor – Menu Creation.
Unit – V
Data Controls – Data Access Objects (DAO) – Accessing and Manipulating Databases – Recordset
– Types 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
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
A network is set up between client system and server system to communicate with each other is
called client/server network.
Client-Server Models:
Distributed Presentation
Distributed Logic
Remote Data
Distributed Data
Client/server:
The splitting of an application into tasks performed on separate computers connected over a network.
In most cases, the “client” is a desktop computing device (e.g., a PC) or a program “served” by another
networked computing device (i.e., the “server”). Gartner has defined five styles of client/server
computing, based on how presentation, application logic and data management functions are
partitioned between the client and server device — see separate definitions for “distributed
presentation,” “remote presentation,” “distributed function,” “remote data management” and
“distributed data management.”
4.Remote data management: The server handles or controls the entire Database management
5. Distributed database: The server and the client partly handle the Database management
In client/server the client controls part of the activity, but in hierarchical processing the host
controls all activity. A client PC almost always does the following in a client/server environment: screen
handling, menu or command interpretation, data entry, help processing, and error recovery.
The dividing line between the client and a server can be anywhere along a broad continuum: at one
end only the user interface has been moved onto the client; at the other, almost all applications have
been moved onto the client and the database may be distributed. There are atsleast five points along
the continuum:
Distributed presentation:
The presentation is handled partly by the server and partly by the client.
Remote presentation:
Distributed logic:
The application logic is handled partly by the server and partly by the client.
Distributed database:
Database management is handled partly by the server and partly by the client. There are,
In the first application, a vendor designs a system using client/server architecture to facilitate use
of that system to access multiple servers, to facilitate bringing together multiple product lines,
and/or to improve productivity. In the second application, a vendor designs a client to facilitate.
Distributed Presentation:
4
Distributed presentation is often referred to as screen scraping. It is implemented with products which
capture an existing screen image prepared on the server (usually a mainframe 3270 image) and
manipulates it as a GUI at the workstation.
Although it sounds simplistic, current products are highly sophisticated. They can direct a single data
input to several applications, integrate data from several applications in one GUI and interface to data
and products running on the workstation.
When to Use
Remote Presentation
Remote presentation involves the presentation component running on the client and all of the
processing taking place on the server. This architecture is often employed where there are diverse
platforms for client workstations. There are a variety of portable GUI development tools on the market.
This architecture is safe for transaction processing as the actual business processing is at the same
location as the data. It is therefore less at risk from network failure.
When to Use
Distributed Function
This is perhaps the most complex environment to implement due to the need to synchronize processes
running on both client and server. The data remains server based but processing is running on both
client and server.
When to Use
5
The remote data management architecture has all of the application running on the client but the data
remains on the server. It is a common model for new client server applications, driven largely by the
capabilities of common tools.
Depending on the DBMS in use, there may be some business functionality running on the server (in the
DBMS as triggers and stored procedures).
When to Use
- Powerful workstation
Distributed Database
In the distributed database architecture, the data is stored on several servers or it may be split across
the client and the server.
The distribution model used and the complexity of the transactions will determine how complex the
implementation of distributed databases will be.
When to Use
Data Mgt. Data Mgt. Data Mgt. Data Mgt. Data Mgt.
Functions on
Business Logic Business Logic Business Logic
Server Side
User Interface
Data Mgt.
Functions on
Business Logic Business Logic Business Logic
Client Side
User Interface User Interface User Interface User Interface User Interface
Distributed and Remote Presentation -- For people whose roots are embedded in the mainframe IBM
world, client-server is essentially distributed or remote presentation. This style maps a workstation
Graphical User Interface (GUI) front end onto an existing application's text-based screen. In Distributed
Presentation, we are generally looking at a system which uses a dumb terminal at the client side. This is
the extreme of the 'thin' client model (see below).
Distributed Logic -- Here the split occurs in the application functionality, one part going to the client,
other to the server. Distributed Logic applications are the most complex of the three basic typologies
since two separately compiled application programs must be developed. Developers must analyze
where each function should reside and what type of dialog must occur between the two programs. The
underlying communications facilities may implement either a message-based or remote procedure call
(RPC) mechanism for transfer of dialog and data.
Remote Data Management -- In remote data management, the entire application resides on the client
and the data management is located on a remote server/host. Remote Data Management is relatively
easily to program for because there is just one application program.
Distributed Database -- This is when data management and application functions occur at both the
client and server. In this instance, data management at the client would include referential, read-only
data. Data frequently updated or accessed by many users would reside on the server. This is the
extreme of the 'fat' client model.
Client/server architecture:
A network architecture in which each computer or process on the network is either a client or a
server. Servers are powerful computers or processes dedicated to managing disk drives (file servers),
printers (print servers), or network traffic (network servers ). Clients are PCs or workstations on which
7
users run applications. Clients rely on servers for resources, such as files, devices, and even processing
power.
Another type of network architecture is known as a peer-to-peer architecture because each node has
equivalent responsibilities. Both client/server and peer-to-peer architectures are widely used, and
each has unique advantages and disadvantages.
Technical Architecture:
8
Technology that separates computers and application software into two categories clients,
and servers to better employ available computing resources and share data processing loads. A client
computer provides the user interaction-facility (interface) and some or all application processing,
while the a server computer might provide high-volume storage capacity, heavy data crunching,
and/or high resolution graphics. Typically, several client computers are connected through a network
(or networks) to a server which could be a large PC, minicomputer, or a mainframe computer. Every
computer connected to a website acts as a client while the website's computer acts as a server. Also
called client-server environment.
Application architecture:
Application architecture is one of several architecture domains that form the pillars of an
enterprise architecture or solution architecture. Note that the term "application architecture"
(without the s) is commonly used for the internal structure of an application, for its software
modularisation.
Applications Architecture is the science and art of ensuring the suite of applications being used by an
organization to create the composite application is scalable, reliable, available and manageable.
One not only needs to understand and manage the dynamics of the functionalities the composite
application is implementing but also help formulate the deployment strategy and keep an eye out for
technological risks that could jeopardize the growth and/or operations of the organization.
Applications Architecture means managing how multiple applications are poised to work together. It
is different from software architecture, which deals with design concerns of one application.
9
There will be a server application accessing windows service or web service. The client application will
have Multiple Document Interface.
The client application will use socket connectivity with server application so as to get authenticated
from server, and also to track record of client connections over server.
After successful authentication the client application will directly access web service so there will be
no overloading on server.
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.
Two-Tier Architecture:
The two-tier architecture is like client server application. The direct communication takes place
between client and server. There is no intermediate between client and server.
The above figure shows the architecture of two-tier. Here the communication is one to one. Let us
see the concept of two tier with real time application. For example now we have a need to save the
employee details in database. The two tiers of two-tier architecture is
So, in client application the client writes the program for saving the record in SQL Server and thereby
saving the data in the database.
Advantages:
Disadvantages:
Two-Tier Architecture
Three-tier architecture:
Multi-Tiered Architecture:
In 3-tier architecture, each server (tier 2 and 3) performs a specialised task (a service). A server can
therefore use services from other servers in order to provide its own service. As a result, 3-tier
architecture is potentially an n-tiered architecture
13
In 3-tier architecture, there is an intermediary level, meaning the architecture is generally split up
between:
A client, i.e. the computer, which requests the resources, equipped with a user interface (usually a web
browser) for presentation purposes
The application server (also called middleware), whose task it is to provide the requested resources, but
by calling on another server
The data server, which provides the application server with the data it requires
Three-Tier Architecture:
Client layer
Business layer
Data layer
Client layer: Here we design the form using textbox, label etc.
Business layer: It is the intermediate layer which has the functions for client layer and it is used to
make communication faster between client and data layer. It provides the business processes logic
and the data access.
14
Advantages:
Fast communication
Three-tier[3] is a client–server architecture in which the user interface, functional process logic
("business rules"), computer data storage and data access are developed and maintained as
independent modules, most often on separate platforms. It was developed by John J. Donovan in
Open Environment Corporation (OEC), a tools company he founded in Cambridge, Massachusetts.
Presentation tier
This is the topmost level of the application. The presentation tier displays information related to such
services as browsing merchandise, purchasing, and shopping cart contents. It communicates with
other tiers by outputting results to the browser/client tier and all other tiers in the network.
16
Application tier (business logic, logic tier, data access tier, or middle tier)
The logic tier is pulled out from the presentation tier and, as its own layer, it controls an application’s
functionality by performing detailed processing.
Data tier
This tier consists of database servers. Here information is stored and retrieved. This tier keeps data
neutral and independent from application servers or business logic. Giving data on its own tier also
improves scalability and performance.
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:
Increased security, as security can be defined for each service, and at each level
Earlier we saw what is a client/server architecture? and its main difference from peer to peer network,
i.e. in client server there was one powerful computer (known as server) which acts as a provider of
information to other sub-ordinate workstations (called client). Now Let us discuss the benefits and
drawbacks of Server-Client computing over P2P computing :-
1) Centralization : Unlike P2P, where there is no central administration, here in this architecture there is
a centralized control. Servers help in administering the whole set-up. Access rights and resource
allocation is done by Servers.
2) Proper Management : All the files are stored at the same place. In this way, management of files
becomes easy. Also it becomes easier to find files.
17
3) Back-up and Recovery possible : As all the data is stored on server its easy to make a back-up of it.
Also, in case of some break-down if data is lost, it can be recovered easily and efficiently. While in peer
computing we have to take back-up at every workstation.
4) Upgradation and Scalability in Client-server set-up : Changes can be made easily by just upgrading
the server. Also new resources and systems can be added by making necessary changes in server.
5) Accessibility : From various platforms in the network, server can be accessed remotely.
6) As new information is uploaded in database , each workstation need not have its own storage
capacities increased (as may be the case in peer-to-peer systems). All the changes are made only in
central computer on which server database exists.
7) Security : Rules defining security and access rights can be defined at the time of set-up of server.
1) Congestion in Network :Too many requests from the clients may lead to congestion, which rarely
takes place in P2P network. Overload can lead to breaking-down of servers. In peer-to-peer, the total
bandwidth of the network increases as the number of peers increase.
2) Client-Server architecture is not as robust as a P2P and if the server fails, the whole network goes
down. Also, if you are downloading a file from server and it gets abandoned due to some error,
download stops altogether. However, if there would have been peers, they would have provided the
broken parts of file.
4) You need professional IT people to maintain the servers and other technical details of network.
It can the summarized that client-server model is not used in small scale networks and networks where
security is not a big issue.
Online transaction processing, or OLTP, refers to a class of systems that facilitate and manage
transaction-oriented applications, typically for data entry and retrieval transaction processing. The
term is somewhat ambiguous; some understand a "transaction" in the context of computer or
database transactions, while others (such as the Transaction Processing Performance Council) define it
18
in terms of business or commercial transactions. OLTP has also been used to refer to processing in
which the system responds immediately to user requests. An automatic teller machine (ATM) for a
bank is an example of a commercial transaction processing application.
Requirements:
OLTP is a methodology to provide end users with access to large amounts of data in an intuitive and
rapid manner to assist with deductions based on investigative reasoning.
Online transaction processing increasingly requires support for transactions that span a network and
may include more than one company. For this reason, new online transaction processing software
uses client or server processing and brokering software that allows transactions to run on different
computer platforms in a network.
In large applications, efficient OLTP may depend on sophisticated transaction management software
(such as CICS) and/or database optimization tactics to facilitate the processing of large numbers of
concurrent updates to an OLTP-oriented database.
For even more demanding Decentralized database systems, OLTP brokering programs can distribute
transaction processing among multiple computers on a network. OLTP is often integrated into service-
oriented architecture (SOA) and Web services.
Benefits:
Online Transaction Processing has two key benefits: simplicity and efficiency. Reduced paper trails
and the faster, more accurate forecasts for revenues and expenses are both examples of how OLTP
makes things simpler for businesses.
Disadvantages:
As with any information processing system, security and reliability are important considerations.
When organizations choose to rely on OLTP, operations can be severely impacted if the transaction
system or database is unavailable due to data corruption, systems failure, or network availability
issues. Additionally, like many modern online information technology solutions, some systems require
offline maintenance which further affects the cost-benefit analysis.
OLTP (online transaction processing) is a class of program that facilitates and manages transaction-
oriented applications, typically for data entry and retrieval transactions in a number of industries,
including banking, airlines, mailorder, supermarkets, and manufacturers. Probably the most widely
installed OLTP product is IBM's CICS (Customer Information Control System).
Today's online transaction processing increasingly requires support for transactions that span a
network and may include more than one company. For this reason, new OLTP software uses
client/server processing and brokering software that allows transactions to run on different computer
platforms in a network.
19
Online Transaction Processing (OLTP) is a class of program that supports, facilitates and manages high-
transaction-oriented applications. The term may be ambiguous because some understand a
"transaction" in the context of computer or database transactions, while others define it in terms of
business or commercial transactions. OLTP may also refer to processing in which the system responds
immediately to user requests, such as a bank’s automatic teller machine (ATM). For our purposes, we
use the first definition.
The primary features of OLTP are immediate client feedback and a high volume of individual
transactions. For that reason it is typically used for data entry and retrieval transactions in industries
that rely heavily on processing a large number of client transactions efficiently. These include
banking, airlines, online retailers, supermarkets, and manufacturers.
In the transaction server, the client component usually includes GUI and the server components
usually consists of SQL transactions against a database. These applications are called OLTP (Online
Transaction Processing) OLTP Applications typically,
An N-tier architecture uses several "tiers" of computers (servers) to interpret requests and transfer
data between one place and another. The 0th tier is at the source of the data. Each tier is completely
independent of all the other tiers, except for those immediately above and below it. The nth tier only
has to know how to handle a request from the n+1th tier, and how to forward that request onto the
n-1th tier (if there is one), and handle the results of the request.
In our case, we only have 2 (3 if you count the user application as a tier) tiers, with one of them being
the actual database, or the 0th tier. Using a 1st tier (or middle tier), allows the client to be completely
independent of the database. The client simply sends a request to the 1st tier, which interprets it and
puts it in a form the 0th tier will understand, and sends it on to the 0th tier. The 0th tier then sends
the result back to the 1st tier, which interprets it and packages it up in way the client will understand,
and then sends it on to the client. The middle tier(s) does not spend much time interpreting a request
and sending it on (only a couple milliseconds), so adding middle tier servers will not slow down the
transfer (using a caching system in addition to the N-tier architecture actually speeds everything up).
The big advantage to using such an architecture is that the client does not need to know anything
about the database. The client is completely removed from the database. The middle tier (our
Frontier server) contains all the information about how to connect to the database, how to send a
20
request, what the result will look like, etc; as well as information on how to send that result back to
the client.
Another big advantage to using a middle tier is, since all the database connection protocols are in the
middle tier, updates to the database become much easier to implement. Instead of making these
changes in thousands of clients, they only need to be made in a few middle tier servers.
Apart from the usual advantages of modular software with well-defined interfaces, the three-tier
architecture is intended to allow any of the three tiers to be upgraded or replaced independently in
response to changes in requirements or technology. For example, a change of operating system in the
presentation tier would only affect the user interface code.
Typically, the user interface runs on a desktop PC or workstation and uses a standard graphical user
interface, functional process logic may consist of one or more separate modules running on a
workstation or application server, and an RDBMS on a database server or mainframe contains the
computer data storage logic. The middle tier may be multi-tiered itself (in which case the overall
architecture is called an "n-tier architecture").
The following sections define each layer of a n-tier architecture in more detail.
21
The function of components in the Data Access Layer is to separate data access from data storage.
The purpose is to shield the rest of the application from the details of data storage, which makes
applications easier to build and to maintain. For example, you might need to extend an application by
changing the data source from a relational database to flat XML files. Such a change can be
implemented in a single Data Access component rather than in multiple components throughout the
application
The Business Servicing Layer contains the business logic and the processing components of an
application. The components in this layer respond to events by taking certain actions. For example,
when a price change occurs, update listings in a product catalog and notify sales reps.
The components in this layer also enforce business rules. For example, do not process an order if
balance due is over thirty days old. Furthermore, the components in this layer are structured to create
a workflow among related processes.
Presentation Layer
The Presentation Layer is the user interface component of an application. It is the point where an
external user interacts with an application. Interaction can be direct (by data input) or indirect (by
viewing data).
Controller logic that manages the binding between UI components and business logic in the
Business Servicing Layer.
Service elements (or models) that define the contract with the Business Servicing and the Data
Access Layers.
Integration Layer
The Integration Layer is similar to the Presentation Layer. Where the Presentation Layer exposes the
n-tier application to external users, the Integration Layer exposes the application to external systems.
Integration can be data-centric, which involves moving data from one application to another.
Integration can also be functional, which involves exposing an application’s business processes and
logic as a service that can be used by external systems.
A two-tier architecture is where a client talks directly to a server, with no intervening server. It is
typically used in small environments (less than 50 users).
22
A three tier is a client-server architecture in which the user interface is the 1st tier, the functional
process logic ("business rules") is the second tier, the data storage and data access are the 3rd tier.
Each tier is developed and maintained as independent modules, most often on separate servers.
An n-tier architecture is the extension of this concept where finer levels of functionality are
distributed across multiple servers.
For example, are you asking from the perspective of software architecture, the design of a new
communication protocol, etc? I will assume that you are asking about software architectures, as this is
the most common context.
1. Performance: allows for scalability by distributing the computation across multiple servers. Of
course, a downfall of such strategy is when the communication costs are larger than the computation
costs. In the old days, study of the decompositions of architectures was done by using queuing theory.
A classic book in this area is the book by Kleinrock, Theory, Volume 1, Queueing Systems;
2. Security: by decomposition, different security strategies can be applied at each level of the
hierarchy, and hence, this leads if properly designed to better security; and
3. Reliability and distribution: any layer of the architecture can be run in different servers, and
therefore when a failure occurs, if properly designed, then a redirection to another server is possible.
Of course for this to work a robust distributed architecture that often includes persistent transactions
(a transaction that either completes or is roll back) are needed.
Multi-Layered Design:
The following diagram shows the multi-layered design that we will build in this seminar. This design
uses 4 layers divided into Presentation, Business Logic, Data Access, and Data Storage.
Concentric circles are used to demonstrate that the layers only communicate with the adjacent layer
and never skip a layer. That is the presentation layer only communicates with the business logic layer
and the business logic layer only ever communicates with the data access layer.
23
The problem described above leads us to the realization that we need to somehow have a disconnected
access to our data if we are to have an architecture that will scale to web based applications. Now we
could design a connected data architecture for our internal applications and use a different architecture
for any web-based components that may arise in the future, but that would cause us to be using two
differing application architectures and would totally prevent use from leveraging any work we did on the
internal applications for our web requirements.
Instead we could design a disconnected data access mechanism that can be used in both the web-based
environments and in our internal VFP applications. What we need is a data access mechanism that is
disconnected and stateless. The diagram below shows the design we need to achieve.
24
25
1st tier is a Presentation Layer: this is what user sees and clicks.
2nd tier is a Business Logic Layer (BLL): this is a set of rules how system has to behave and process
data.
3rd tier is a Data Access Layer (DAL): this is a set of fuctions for retriving and manipulating data in
database.
4th tier is a database: it contains data scheme, data itself and (if used) stored procedures.
If you have 2-tier or 3-tier architecure it means that some mentioned above layers are implemented
together that borders between them disappeared and can be treated as 1.
In a 2 tier architecture the program (sourcecode and business logic) are separated from the database (
data, tables). Example: a factory application with a server that holds the program, a second server
that holds the database and a socalled consol that is use as an interface to users.
In a 3 tier environment there is also a separate program running on the lokal PC. This program
performs the local activities and communcates with the program running on the application server.
n- tier add an extra level between the PC and the rest. Using the internet is an example. You explorer
is the local program. The server of your provider is the informaten broker. This is the extra level that
holds the logic of combining messages and information from diverent sources and systems into 1
HTML page. For example. You're using a google bar. This part of the page get's it information from the
main program that runs at the Google server, which in it's turn is connected to the google database.
26
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.
STEPS IN VB APPLICATION:
The Visual Basic IDE appears in Figure 1.1, and as a Visual Basic programmer, this is where
you’ll spend most of your programming time. If you’re not already familiar with the parts of the
IDE, you will be in time.
27
The Visual Basic IDE has three distinct states: Design, Run, and Debug. The current state
appears in Visual Basic’s title bar. This chapter concentrates on the Design state. We’ll cover the
Debug state later. (In the Run state, Visual Basic is in the background while your program runs.)
28
The menu bar presents the Visual Basic menus you need to work with. The basic menus with
their features are:
File: contains the commands for opening projects, saving projects, creating executable
files and list of recent project; also used for similar file handling option and printing
option.
Edit: contains standard editing functions like Undo, Copy, Paste plus a number of
commands for formatting and editing your code like Find, Replace and so on.
View: contains commands for displaying and hiding components from windows and
toolbar.
Project: sets project properties, adds/removes forms and modules, and add/removes
references and components.
Format: contains command for aligning or sizing the controls on the Form.
Debug: contains the usual debugging command that starts/stops debugging and stepping
through programs.
Run: contains the commands that start, break, and end execution of the current
application.
Query: consists of the commands that are generally used for handling databases.
Diagram: is used when building database applications to draw database diagrams.
Tools: menu consists of the tools that you may need while building ActiveX components
and ActiveX controls; contains the command to start the Menu Editor and the Options
command, which lets you customize the environment.
Add-Ins: contains Add-In manager, lists add-ins like Application Wizard and API
Viewer.
Window: arranges or selects open windows.
Help: handles Help and the About box.
2. The Toolbar.
The main Visual Basic toolbar appears as in Figure 1.2. This toolbar contains buttons matching
popular menu items, as you can see in Figure 1.2; clicking the button is the same as selecting a
menu item and can save you some time.
29
Figure-1-2-Main Toolbar
Besides the main toolbar, you can also display other dock able 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.
The Standard toolbar is just below the main menu bar and is displayed by default.
The Form Editor Toolbar contains the commands of the Format menu.
Opening and closing of toolbar can be done by choosing View > Toolbar, which then displays a
submenu containing the names of the toolbars.
Figure-1-7-TCS Toolbar
c) Give name to new toolbar (in figure 1.7, it’s TCS Toolbar).
d) Add icons to your new menu from Commands tab, which contains all commands of the IDE’s
menu.
e) Add the toolbar to your IDE and drag commands to the toolbar.
f) Add as many commands icons as necessary, and then close the Customize dialog box.
Project Explorer
Docked on the right side of the screen, just under the toolbar, is the Project Explorer window.
The Project Explorer as shown in figure as a quick reference to the various elements of a project
namely form, classes and modules. All of the object that make up the application are packed in a
project. A simple project will typically contain one form, which is a window that is designed as
part of a program's interface. It is possible to develop any number of forms for use in a program,
although a program may consist of a single form. In addition to forms, the Project Explorer
window also lists code modules and classes.
Properties Window
4. The Properties Window.
Figure-1-9-The-Properties-Window
The Properties Window contains the property settings for the selected objects and controls.
Properties are the attributes of an object and controls, such as its caption, backcolor, forecolor,
size, font, height, and so on. Property Window is used to change the appearance, text/values
displayed on the controls. Some properties can only be changed during design time and some can
also be changed through codes at runtime.
To hide or unhide the Properties Window, choose View > Properties window (F4).
Toolbox
The Toolbox contains a set of controls that are used to place on a Form at design time thereby
creating the user interface area. Additional controls can be included in the toolbox by using the
Components menu item on the Project menu. A Toolbox is represented in figure 2 shown below.
33
Control Description
CommandButton Used to carry out the specified action when the user chooses it.
34
ListBox Displays a list of items from which a user can select one.
Displays the valid disk drives and allows the user to select one of
DriveListBox
them.
Allows the user to select the directories and paths, which are
DirListBox
displayed.
FileListBox Displays a set of files from which a user can select the desired one.
Label Displays a text that the user cannot modify or interact with.
Real world objects are loaded with properties. For example, a flower is loaded certain color,
shape and fragrance. Similarly programming objects are loaded with properties. A property is a
named attribute of a programming object. Properties define the characteristics of an object such
35
as Size, Color etc. or sometimes the way in which it behaves. For example, a TextBox accepts
properties such as Enabled, Font, MultiLine, Text, Visible, Width, etc.
Enables property allows the TextBox to be enabled or disabled at run time depending on
the condition set to True or False.
Font property sets a particular font in the TextBox.
MultiLine property allows the TextBox to accept and display multiple lines at run time.
Text property of the TextBox control sets a particular text in the control.
Visible property is used to hide the object at run time.
Width property sets the TextBox to the desired width at design time.
The properties that are discussed above are design-time properties that can be set at the design
time by selecting the Properties Window. But certain properties cannot be set at design time. For
example, the CurrentX and CurrentY properties of a Form cannot be set at the design time.
A method is an action that can be performed on objects. For example, a cat is an object. Its
properties might include long white hair, blue eyes, 3 pounds weight etc. A complete definition
of cat must only encompass on its looks, but should also include a complete itemization of its
activities. Therefore, a cat's methods might be move, jump, play, breath etc.
performs a very precise action. The TextBox control has other associated methods such as
Refresh, SetFocus, etc.
The Refresh method enforces a complete repaint of the control or a Form. For example,
Text1.Refresh refreshes the TextBox.
The Setfocus method moves the focus on the control. For Example Text1.SetFocus sets
the focus to TextBox control Text1.
Every object, such as a form or control, has a set of properties that describe it. Although this set
isn't identical for all objects, some properties--such as those listed in Table 6.1--are common to
most controls. You can see every property for a given control by looking at the Properties
window in the IDE.
36
Left The position of the left side of a control with respect to its container
Top The position of the top of a control with respect to its container
Enabled The Boolean (True/False) value that determines whether users can manipulate the control
Visible The Boolean (True/False) value that determines whether users can see the control
Another important property to consider is BorderStyle, which determines the window elements
(title bar, Maximize and Minimize buttons, and so forth) a form will have. Table 6.2 summarizes
the six BorderStyle settings; Figure 6.1 shows the same form, displayed with each setting.
0-None No borders, no title bar, not movable. Use this as a backdrop for a splash screen.
Setting Description
1-Fixed Single Not sizable by dragging borders but can have Maximize and Minimize buttons. Use
this for any fixed-size window for which you want a button to appear in the taskbar.
2-Sizable Sizable by dragging borders and by using Maximize and Minimize buttons. Use this for
(default) typical programs.
3-Fixed Dialog Not sizable and no Maximize/Minimize buttons. Use this for simple forms such as a
password dialog.
4-Fixed Similar to 3-Fixed Dialog except that the title bar is shorter and the title bar font and
ToolWindow Close button are correspondingly smaller. Use this for floating toolbars.
5-Sizable Similar to a 4-Fixed ToolWindow except that it's sizable by dragging the border. Use
37
ToolWindow this for windows such as the Visual Basic Properties window.
The BorderStyle property of a form can be set to one of six different styles. Notice that some
styles can look exactly the same as other styles.
Methods are blocks of code designed into a control that tell the control how to do things, such as
move to another location on a form. Just as with properties, not all controls have the same
methods, although some common methods do exist, as shown in Table 6.3.
Events are what happen in and around your program. For example, when a user clicks a button,
many events occur: The mouse button is pressed, the CommandButton in your program is
clicked, and then the mouse button is released. These three things correspond to the MouseDown
event, the Click event, and the MouseUp event. During this process, the GotFocus event for the
CommandButton and the LostFocus event for whichever object previously held the focus also
occur.
Again, not all controls have the same events, but some events are shared by many controls (see
Table 6.4). These events occur as a result of some specific user action, such as moving the
mouse, pressing a key on the keyboard, or clicking a text box. These types of events are user-
initiated events and are what you will write code for most often.
The GotFocus and LostFocus events relate to most other events because they occur whenever a
new control becomes active to receive user input. This makes GotFocus and LostFocus useful for
data validation, the process of making sure that data is in the proper format for your program. Be
careful, though! Improperly coding these two events can cause your program to begin an endless
loop, which will cause your program to stop responding.
38
KeyDown The user presses a keyboard key while an object has focus.
KeyPress The user presses and releases a keyboard key while an object has focus.
KeyUp The user releases a keyboard key while an object has focus.
Event Occurrence
MouseDown The user presses any mouse button while the mouse pointer is over an object.
MouseUp The user releases any mouse button while the mouse pointer is over an object.
Although properties, methods, and events do different things, it's important to realize that they're
often interrelated. For example, if you move a control with the Move method (most likely in
response to an event), one or more of the control's position properties (Top, Height, Left, and
Width) will change as a result. Because the control's size has changed, the Resize event occurs.
39
This interdependence means that you can sometimes accomplish the same task multiple ways in
your code by manipulating object properties or methods. Consider the following code, which
shows two ways to move a CommandButton:
`************************************************
`Move the commandbutton by setting the properties
`************************************************
cmdMove.Left = 100
cmdMove.Top = 100
`********************************************
`Move the commandbutton by using the Move method
`********************************************
txtMove.Move 100, 100
As another example, you can make a form appear and disappear from the screen by using its
Visible property or its Show and Hide methods, as follows:
`***********************************************
` Make the form visible by setting the property
`***********************************************
frmMyForm.Visible=True
`***************************************
` Hide the form by setting the property
`***************************************
frmMyForm.Visible=False
`*********************************************
` Make the form visible by using the Show method
`*********************************************
frmMyForm.Show
`*************************************
` Hide the form by using the Hide method
`*************************************
frmMyForm.Hide
For a temporary phase, the control may be transferred to some other point in a program.
While in an event driven application, the program statements are executed only when a particular
event calls a specific part of the code that is assigned to the event.
Let us consider a TextBox control and a few of its associated events to understand the concept of
event driven programming. The TextBox control supports various events such as Change, Click,
40
MouseMove and many more that will be listed in the Properties dropdown list in the code
window for the TextBox control. We will look into a few of them as given below.
The code entered in the Change event fires when there is a change in the contents of the
TextBox
The Click event fires when the TextBox control is clicked.
The MouseMove event fires when the mouse is moved over the TextBox
As explained above, several events are associated with different controls and forms, some of the
events being common to most of them and few being specific to each control.
An event procedure is the place in your project where you put the code that will run when an
event occurs. To write an event procedure, you must access the Code window for your object by
doing one of the following:
The code write in an event procedure will run whenever the event occurs.
Visual Basic automatically generates an event procedure when select an event in the Code
Window. The name event procedures by joining the object's name and the event name with an
41
underscore character (cmdExit_Click()). When the event procedure in this example is run, it will
display a dialog when the user clicks the CommandButton named cmdExit.
The MoveIt program can be moved around onscreen when users click the buttons on its
interface.
MoveIt consists of the form frmMove, which contains four CommandButtons placed in its
corners. When you run MoveIt, clicking one of these buttons will move the form to the
corresponding corner of the screen. In the center of the form is a label that will provide event
notification--in other words, it will report information such as mouse movement and which
button has the focus.
1. Create a new project by choosing New Project from the File menu. Select Standard EXE from
the New Project dialog.
2. In the Properties window, change the name of the project's form to frmMove.
3. Add four CommandButtons to frmMove's corners and add a label in the center.
4. In the Properties window, name the label and the four buttons.
5. Now set the BorderStyle property of the form to 1-Fixed Single. This ensures that the form
can't be resized while the program is running. Also, set the label's Alignment property to 2-
Center and its BorderStyle property to 1-Fixed Single to give the label a finished appearance.
6. Save the form and the project, using friendly names such as frmMove.frm for the form and
MoveIt.vbp for the project.
42
Use the Form_Load() event procedure to prepare the form before showing it onscreen when
program is run. Use this procedure to
Open the Code window for the Form_Load() event procedure by double-clicking anywhere on
the form except the buttons, label, or title bar. Then, enter the code in Listing 6.1, being careful
to change the names if you named your control differently.
Use the Click() event procedure to move the form around the screen. To do so, double-click a
CommandButton to view the Code window. Then, enter that part of the code from Listing 6.2
that applies to that CommandButton.
Moving the form to the top or left of the screen is easy--set the Top or Left property of the form
to zero. This always corresponds to the top or left of your monitor, respectively.
Lining up the form on the right side or bottom of the screen is a little harder because right and
bottom properties don't exist. To place a form on the right side of the screen, must set the Left
property of the form to the Width property of the Screen object, minus the Width of the form
(because the Width of the screen would be the right property of the screen, if the right property
existed).
A similar technique is used to determine the bottom of the screen. To set the form's Top property
equal to the screen's Height property, wouldn't see the form because it would be just below the
bottom of the screen. To set the bottom of the form to the bottom of the screen, you subtract the
value of the form's Height property from the value of the screen's Height property. This raises the
form so that you can see it.
To finish MoveIt, let's add some code that will tell when certain events occur for the form and
the CommandButtons. When users press or release the mouse button over the form, the text in
lblNotify will change to reflect the state of the button. Also, when users use the Tab key or the
45
mouse button to move from one CommandButton to another (which changes the focus from one
button to the next), the text in lblNotify will change. Doing this requires to write code in three
different event procedures: the MouseUp and MouseDown event procedures for the form and the
GotFocus event procedure for each CommandButton.
Be careful when placing a form on the right side or bottom of the screen; otherwise, you might
place it offscreen.
Enter the code from Listing 6.3 into the MouseUp and MouseDown event procedures for
frmMain. To do this, open the Code window for the MouseDown event procedure by double-
clicking the form and selecting MouseDown from the event procedures drop-down list .
LISTING 6.3 Code for Reporting When Users Click and Release the Mouse Button
01 Private Sub Form_MouseDown(Button As Integer, _
Shift As Integer, X As Single, Y As Single)
02
03 lblNotify.Caption = "MouseDown Event"
04
05 End Sub
06
07 Private Sub Form_MouseUp(Button As Integer, Shift As Integer, X As Single,
Y As Single)
08
09 lblNotify.Caption = "MouseUp Event"
10
11 End Sub
When the program runs, if your mouse is over the form (not the CommandButtons or the label)
and you click the mouse button, the text MouseDown Event appears in lblNotify. When you
release your mouse button, the text MouseUp Event appears.
Last, add the code that will report which CommandButton has the focus. Enter the code from
Listing 6.4 into the GotFocus event procedures for each CommandButton. Do this by double-
clicking one of the CommandButtons and selecting the GotFocus event procedure (notice that
Visual Basic selects the Click event by default). Repeat this procedure for each
CommandButton.
LISTING 6.4 Code for Reporting Which CommandButton Has the Focus
01 Private Sub cmdBottomLeft_GotFocus()
02
03 lblNotify.Caption = "cmdBottomLeft has the Focus"
04
05 End Sub
06
07 Private Sub cmdBottomRight_GotFocus()
08
09 lblNotify.Caption = "cmdBottomRight has the Focus"
10
11 End Sub
12
13 Private Sub cmdTopLeft_GotFocus()
46
14
15 lblNotify.Caption = "cmdTopLeft has the Focus"
16
17 End Sub
18
19 Private Sub cmdTopRight_GotFocus()
20
21 lblNotify.Caption = "cmdTopRight has the Focus"
22
23 End Sub
Restore : Restores a maximized Form to the size it was before it was maximized;
available only if the Form has been maximized.
Move : Lets the user moves the Form around with the mouse
Size : Lets the user resizes the control with the mouse
Minimize: Minimizes the Form
Maximize : Maximizes the Form
Close : Closes the Form
By default, Visual Basic suggests the name of the first Form created when the project started.
In order to load and unload the forms, Load and Unload statements are used. The Load statement
has the following syntax :
Load FormName
Unload FormName
The FormName variable is the name of the Form to be loaded or unloaded. Unlike the Show
method which cares of both loading and displaying the Form, the load statement doesn't show
the Form. You have to call the Form's Show method to display it on the desktop.
FormName.Show mode
The FormName variable is the Form's name, and the optional argument mode determines
whether the Form will be Modal or not. It can have one of the following syntax :
* 0-Modeless (default)
* 1-Modal
Modeless Forms are the normal Forms. Modeless Forms interact with the user and the user
allowed to switch to any other Form of the application. If you do not specify the optional mode
argument, by default the mode is set to modeless.
48
The Modal Forms takes the total control of the application where user cannot switch to any other
Forms in the application unless the Form is closed. A modal Form, thus, must have a Close
button or some means to close the Form in order to return to the Form where the Modal Form
was loaded.
Hiding Forms
The Hide method is used to hide a Form. The following is the syntax of the Hide Method.
FormName.Hide
To hide a Form from within its own code, the following code can be used.
Me.Hide
Understand that the Forms that are hidden are not unloaded ; they remains in the memory and
can be displayed instantly with the Show Method. When a Form is hidden, you can still access
its properties and code. For instance, you can change the settings of its Control Properties or call
any Public functions in the Form.
The following is an example illustrates the Show method and Mode statement
Caption Form1
Form
Name frm1
Caption Form2
Form
Name frm2
Caption Form3
Form
Name frm3
Click on a
Caption button to display
Label
a Form
Name
Label1
49
The following code is typed in the Click event of the command buttons
Run the application. Clicking on the buttons will display the Forms respectively.
To know what the difference is between Unload and Hide methods we will do an example. Open
a new project and save the project. Draw two buttons on the form and name those as shown
above.
Me.Hide
Unload Me
50
Save the project and run the application. Once you click on Hide button you can note that the
Form is invisible but the application is still running. But when you click on Unload button you
can see that the application is terminated.
Variables
Variables are the memory locations which are used to store values temporarily. A
defined naming strategy has to be followed while naming a variable. A variable name must begin
with an alphabet letter and should not exceed 255 characters. It must be unique within the same
scope. It should not contain any special character like %, &, !, #, @ or $.
There are many ways of declaring variables in Visual Basic. Depending on where the
variables are declared and how they are declared, we can determine how they can be used by our
application. The different ways of declaring variables in Visual Basic are listed below and
elucidated in this section.
Syntax
Dim I as integer
Scope of variables
Local Variables
A local variable is one that is declared inside a procedure. This variable is only available to the
code inside the procedure and can be declared using the Dim statements as given below.
The local variables exist as long as the procedure in which they are declared, is executing. Once
a procedure is executed, the values of its local variables are lost and the memory used by these
variables is freed and can be reclaimed. Variables that are declared with keyword Dim exist only
as long as the procedure is being executed.
51
Static Variables
Static variables are not reinitialized each time Visual Invokes a procedure and therefore retains
or preserves value even when a procedure ends. In case we need to keep track of the number of
times a command button in an application is clicked, a static counter variable has to be declared.
These static variables are also ideal for making controls alternately visible or invisible. A static
variable is declared as given below.
Variables have a lifetime in addition to scope. The values in a module-level and public variables
are preserved for the lifetime of an application whereas local variables declared with Dim exist
only while the procedure in which they are declared is still being executed. The value of a local
variable can be preserved using the Static keyword. The follwoing procedure calculates the
running total by adding new values to the previous values stored in the static variable value.
Function RunningTotal ( )
Static Accumulate
RunningTotal = Accumulate
End Function
If the variable Accumulate was declared with Dim instead of static, the previously accumulated
values would not be preserved accross calls to the procedure, and the procedure would return the
same value with which it was called. To make all variables in a procedure static, the Static
keyword is placed at the beginning of the procedure heading as given in the below statement.
Example
The following is an example of an event procedure for a CommandButton that counts and
displays the number of clicks made.
Counter = Counter + 1
52
Print Counter
End Sub
The first time we click the CommandButton, the Counter starts with its default value of zero.
Visual Basic then adds 1 to it and prints the result.
A module level variable is available to all the procedures in the module. They are declared using
the Public or the Private keyword. If you declare a variable using a Private or a Dim statement in
the declaration section of a module—a standard BAS module, a form module, a class module,
and so on—you're creating a private module-level variable. Such variables are visible only from
within the module they belong to and can't be accessed from the outside. In general, these
variables are useful for sharing data among procedures in the same module:
You can also use the Public attribute for module-level variables, for all module types except
BAS modules. (Public variables in BAS modules are global variables.) In this case, you're
creating a strange beast: a Public module-level variable that can be accessed by all procedures in
the module to share data and that also can be accessed from outside the module. In this case,
however, it's more appropriate to describe such a variable as a property:
You can access a module property as a regular variable from inside the module and as a custom
property from the outside:
The lifetime of a module-level variable coincides with the lifetime of the module itself. Private
variables in standard BAS modules live for the entire life of the application, even if they can be
accessed only while Visual Basic is executing code in that module. Variables in form and class
modules exist only when that module is loaded in memory. In other words, while a form is active
(but not necessarily visible to the user) all its variables take some memory, and this memory is
released only when the form is completely unloaded from memory. The next time the form is re-
53
created, Visual Basic reallocates memory for all variables and resets them to their default values
(0 for numeric values, "" for strings, Nothing for object variables).
A variable can have the same name and different scope. For example, we can have a public
variable named R and within a procedure we can declare a local variable R. References to the
name R within the procedure would access the local variable and references to R outside the
procedure would access the public variable.
Constants
Constants are named storage locations in memory, the value of which does not change during
program Execution. They remain the same throughout the program execution. When the user
wants to use a value that never changes, a constant can be declared and created. The Const
statement is used to create a constant. Constants can be declared in local, form, module or global
scope and can be public or private as for variables. Constants can be declared as illustrated
below.
A compile-time constant is computed at the time the code is compiled, while a run-time constant
can only be computed while the application is running. A compile-time constant will have the
same value each time an application runs, while a run-time constant may change each time.
Compile-time constants are required for cases such as array bounds, case expressions, or
enumerator initializers.
You use the Const statement to declare a constant and set its value. By declaring a constant, you
assign a meaningful name to a value. Once a constant is declared, it cannot be modified or
assigned a new value.
Write a declaration that includes an access specifier, the Const keyword, and an expression, as in
the following examples:
DATATYPES
Visual Basic classifies the information mentioned above into two major data types, they are the
numeric data types and the non-numeric data types.
54
Numeric data types are types of data that consist of numbers, which can be computed
mathematically with various standard operators such as add, minus, multiply, divide and more.
Examples of numeric data types are examination marks, height, weight, the number of students
in a class, share values, price of goods, monthly bills, fees and others. In Visual Basic, numeric
data are divided into 7 types, depending on the range of values they can store. Calculations that
only involve round figures or data that does not need precision can use Integer or Long integer in
the computation. Programs that require high precision calculation need to use Single and Double
decision data types, they are also called floating point numbers. For currency calculation , you
can use the currency data types. Lastly, if even more precision is required to perform calculations
that involve a many decimal points, we can use the decimal data types. These data types
summarized in Table 5.1
Double 8 bytes
Nonnumeric data types are data that cannot be manipulated mathematically using standard
arithmetic operators. The non-numeric data comprises text or string data types, the Date data
types, the Boolean data types that store only two values (true or false), Object data type and
Variant data type .They are summarized in Table 5.2
Literals are values that you assign to data. In some cases, we need to add a suffix behind a literal
so that VB can handle the calculation more accurately. For example, we can use num=1.3089#
for a Double type data. Some of the suffixes are displayed in Table 5.3.
Table 5.3
& Long
! Single
# Double
@ Currency
56
In addition, we need to enclose string literals within two quotations and date and time literals
within two # sign. Strings can contain any characters, including numbers. The following are few
examples:
memberName="Turban, John."
TelNumber="1800-900-888-777"
LastDay=#31-Dec-00#
ExpTime=#12:00 am#
57
Unit – III
Visual Basic offers different types of procedures to execute small sections of coding in
applications.
The various procedures are elucidated in details in this section. Visual Basic programs
can be broken into smaller logical components called Procedures.
Procedures are useful for condensing repeated operations such as the frequently used
calculations, text and control manipulation etc.
It is easier to debug a program a program with procedures, which breaks a program into
discrete logical limits.
Procedures used in one program can act as building blocks for other programs with
slight modifications.
A Procedure can be Sub, Function or Property Procedure.
Sub Procedures
A sub procedure can be placed in standard, class and form modules. Each time the
procedure is called, the statements between Sub and End Sub are executed. The syntax for a
sub procedure is as follows:
[ statements]
End Sub
arglist is a list of argument names separated by commas. Each argument acts like a
variable in the procedure. There are two types of Sub Procedures namely general procedures
and event procedures.
Event Procedures
An event procedure is a procedure block that contains the control's actual name, an
underscore(_), and the event name. The following syntax represents the event procedure for a
Form_Load event.
58
....statement block..
End Sub
Function Procedures
Functions are like sub procedures, except they return a value to the calling procedure.
They are especially useful for taking one or more pieces of data, called arguments and
performing some tasks with them.
Then the functions returns a value that indicates the results of the tasks complete within
the function.
The following function procedure calculates the third side or hypotenuse of a right
triangle, where A and B are the other two sides.
It takes two arguments A and B (of data type Double) and finally returns the results.
End Function
The above function procedure is written in the general declarations section of the Code
window. A function can also be written by selecting the Add Procedure dialog box from the
Tools menu and by choosing the required scope and type.
Property Procedures
Defining procedures
'Return the result by writing it to a variable having the same name as the function
End Function
End Sub
The arguments to the function are declared as ByRef which requires the compiler to
make sure that only arguments of the specified type are used, in this case Double.
The function returns a value by assigning it to the function name as though the function
were a variable. This contrasts with the use of the keyword return in many other languages.
Calling procedures:
You can use or call the two procedures defined in the previous sections as follows:
'On the next line, names of arguments are used and argument order does not matter.
The arguments (argument list) passed to a function must be enclosed in round brackets,
whereas those supplied to a subroutine need not.
Control Statements:
Control Statements are used to control the flow of program's execution. Visual Basic
supports control structures such as if... Then, if...Then ...Else, Select...Case, and Loop structures
such as Do While...Loop, While...Wend, For...Next etc method.
60
The If...Then selection structure performs an indicated action only when the condition is
True; otherwise the action is skipped.
If <condition> Then
statement
End If
txtGrade.Text = "A"
End If
The If...Then...Else selection structure allows the programmer to specify that a different
action is to be performed when the condition is True than when the condition is False.
statements
Else
statements
End If
txtGrade.Text = "Pass"
Else
txtGrade.Text = "Fail"
End If
Method 1:
statements
statements
statements
Else
Statements
End If
Method 2:
statements
Else
statements
Else
statements
62
Else
Statements
End If
End If
End If
e.g.: Assume you have to find the grade using nested if and display in a text box
txtGrade.Text = "A"
txtGrade.Text = "B"
txtGrade.text = "C"
txtGrade.Text = "S"
Else
txtGrade.Text = "F"
End If
Case 0
63
Statements
Case 1
Statements
End Select
e.g.: Assume you have to find the grade using select...case and display in the text box
average = txtAverage.Text
Case 100 To 75
txtGrade.Text ="A"
Case 74 To 65
txtGrade.Text ="B"
Case 64 To 55
txtGrade.Text ="C"
Case 54 To 45
txtGrade.Text ="S"
Case 44 To 0
txtGrade.Text ="F"
Case Else
End Select
` The For...Next Loop is another way to make loops in Visual Basic. For...Next repetition
structure handles all the details of counter-controlled repetition. The following loop counts the
numbers from 1 to 100:
Dim x As Integer
For x = 1 To 50
Print x
Next
In order to count the numbers from 1 yo 50 in steps of 2, the following loop can be used
For x = 1 To 50 Step 2
Print x
Next
The above coding will display numbers vertically on the form. In order to display
numbers horizontally the following method can be used.
For x = 1 To 50
Next
To increase the space between the numbers increase the value inside the brackets after the &
Space$.
Following example is a For...Next repetition structure which is with the If condition used.
For number = 1 To 10
If number = 4 Then
Else
Print number
65
End If
Next
In the output instead of number 4 you will get the "This is number 4".
structure tests a condition for falsity for repetition to continue. Statements in the body
of a Do Until/Loop are executed repeatedly as long as the loop-continuation test evaluates
to false. As an example of a Do Until/Loop repetition structure, once again consider
the segment designed to find the first power of two larger than 1000:
The Do/Loop Until structure is similar to the Do Until/Loop structure, except that the
loop-continuation condition is tested after the body of the loop is performed; therefore, the
body of the loop executes at least once. When a Do/Loop Until terminates, execution
continues with the statement after the Loop Until clause. As an example of a Do/Loop
Until repetition structure, once again consider the segment designed to find the first power
of two larger than 1000:
67
ARRAYS
Introduction:
By definition, an array is a list of variables with the same data type and name. When we
work with a single item, we only need to use one variable. However, if we have a list of items
which are of similar type to deal with, we need to declare an array of variables instead of using a
variable for each item
For example, if we need to enter one hundred names, it is difficulty to declare 100 different
names, this is a waste of time and efforts. So, instead of declaring one hundred different
variables, we need to declare only one array. We differentiate each item in the array by using
subscript, the index value of each item, for example name(1), name(2),name(3) .......etc. , which
will make declaring variables streamline and much systematic.
Dimension of an Array:
An array can be one dimensional or multidimensional. One dimensional array is like a list of
items or a table that consists of one row of items or one column of items.
A two dimensional array is a table of items that make up of rows and columns. The format for a
one dimensional array is ArrayName(x), the format for a two dimensional array is
ArrayName(x,y) and a three dimensional array is ArrayName(x,y,z) . Normally it is sufficient to
use one dimensional and two dimensional array ,you only need to use higher dimensional arrays
if you need to deal more complex problems. Let me illustrate the the arrays with tables.
Table 16.1. One dimensional Array
Declaring Arrays
68
We can use Public or Dim statement to declare an array just as the way we declare a single
variable. The Public statement declares an array that can be used throughout an application while
the Dim statement declares an array that could be used only in a local procedure.
Fixed-sized Arrays
When an upper bound is specified in the declaration, a Fixed-array is created. The upper limit
should always be within the range of long data type.
Declaring a fixed-array
In the above illustration, numbers is the name of the array, and the number 6 included in the
parentheses is the upper limit of the array. The above declaration creates an array with 6
elements, with index numbers running from 0 to 5.
If we want to specify the lower limit, then the parentheses should include both the lower and
upper limit along with the To keyword. An example for this is given below.
In the above statement, an array of 10 elements is declared but with indexes running from 1 to 6.
A public array can be declared using the keyword Public instead of Dim as shown below.
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.
69
Tables or arrays that require two indexes to identify a particular element are called two
dimensional arrays. Note that multidimensional arrays can have more than two dimensions.
Visual Basic supports at least 60 array dimensions, but most people will need to use more than
two or three dimensional-arrays.
It is also possible to define the lower limits for one or both the dimensions as for fixed size
arrays. An example for this is given here.
An example for three dimensional-array with defined lower limits is given below.
Basically, you can create either static or dynamic arrays. Static arrays must include a fixed
number of items, and this number must be known at compile time so that the compiler can set
aside the necessary amount of memory. You create a static array using a Dim statement with a
constant argument:
Visual Basic starts indexing the array with 0. Therefore, the preceding array actually holds 101
items.
Most programs don't use static arrays because programmers rarely know at compile time how
many items you need and also because static arrays can't be resized during execution. Both these
issues are solved by dynamic arrays. You declare and create dynamic arrays in two distinct steps.
In general, you declare the array to account for its visibility (for example, at the beginning of a
module if you want to make it visible by all the procedures of the module) using a Dim
command with an empty pair of brackets. Then you create the array when you actually need it,
using a ReDim statement:
Variables of different data types when combined as a single variable to hold several
related informations is called a User-Defined data type.
A Type statement is used to define a user-defined type in the General declaration section
of a form or module. User-defined data types can only be private in form while in standard
modules can be public or private. An example for a user defined data type to hold the product
details is as given below.
Private Type ProductDetails
ProdID as String
ProdName as String
Price as Currency
End Type
The user defined data type can be declared with a variable using the Dim statement as in
any other variable declaration statement. An array of these user-defined data types can also be
declared. An example to consolidate these two features is given below.
A User-Defined data type can be referenced in an application by using the variable name
in the procedure along with the item name in the Type block. Say, for example if the text
property of a TextBox namely text1 is to be assigned the name of the electronic good, the
statement can be written as given below.
Text1.Text = ElectronicGoods.ProdName
Text1.Text = ElectronicGoods(i).ProdName
User-defined data types can also be passed to procedures to allow many related items as one
argument.
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
Function name
Return data type
71
CBool Boolean Data Type (Visual Basic) Any valid Char or String or numeric
expression.
CByte Byte Data Type (Visual Basic) 0 through 255 (unsigned); fractional parts
are rounded.1
CChar Char Data Type (Visual Basic) Any valid Char or String expression; only
first character of a String is converted; value can be 0 through 65535 (unsigned).
CDate Date Data Type (Visual Basic) Any valid representation of a date and time.
CSByte SByte Data Type (Visual Basic) -128 through 127; fractional parts are
rounded.1
CShort Short Data Type (Visual Basic) -32,768 through 32,767; fractional parts are
rounded.1
CSng Single Data Type (Visual Basic) -3.402823E+38 through -1.401298E-45 for
negative values; 1.401298E-45 through 3.402823E+38 for positive values.
CStr String Data Type (Visual Basic) Returns for CStr depend on the expression
argument. See Return Values for the CStr Function (Visual Basic).
CUInt UInteger Data Type 0 through 4,294,967,295 (unsigned); fractional parts are
rounded.1
72
CUShort UShort Data Type (Visual Basic) 0 through 65,535 (unsigned); fractional parts
are rounded.1
A conversion function should always be placed at the right hand side of the calculation
statement.
CType Function
The CType Function takes a second argument, typename, and coerces expression to typename,
where typename can be any data type, structure, class, or interface to which there exists a valid
conversion.
For a comparison of CType with the other type conversion keywords, see DirectCast Operator
(Visual Basic) and TryCast Operator (Visual Basic).
CBool Example
The following example uses the CBool function to convert expressions to Boolean values. If an
expression evaluates to a nonzero value, CBool returns True; otherwise, it returns False.
VB
Dim a, b, c As Integer
Dim check As Boolean
a=5
b=5
' The following line of code sets check to True.
check = CBool(a = b)
c=0
' The following line of code sets check to False.
check = CBool(c)
CByte Example
The following example uses the CByte function to convert an expression to a Byte.
VB
Dim aDouble As Double
Dim aByte As Byte
aDouble = 125.5678
' The following line of code sets aByte to 126.
aByte = CByte(aDouble)
CChar Example
73
The following example uses the CChar function to convert the first character of a String
expression to a Char type.
VB
Dim aString As String
Dim aChar As Char
' CChar converts only the first character of the string.
aString = "BCD"
' The following line of code sets aChar to "B".
aChar = CChar(aString)
The input argument to CChar must be of data type Char or String. You cannot use CChar to
convert a number to a character, because CChar cannot accept a numeric data type. The
following example obtains a number representing a code point (character code) and converts it to
the corresponding character. It uses the InputBox function to obtain the string of digits, CInt to
convert the string to type Integer, and ChrW to convert the number to type Char.
VB
Dim someDigits As String
Dim codePoint As Integer
Dim thisChar As Char
someDigits = InputBox("Enter code point of character:")
codePoint = CInt(someDigits)
' The following line of code sets thisChar to the Char value of codePoint.
thisChar = ChrW(codePoint)
CDate Example
The following example uses the CDate function to convert strings to Date values. In general,
hard-coding dates and times as strings (as shown in this example) is not recommended. Use date
literals and time literals, such as #Feb 12, 1969# and #4:45:23 PM#, instead.
VB
Dim aDateString, aTimeString As String
Dim aDate, aTime As Date
aDateString = "February 12, 1969"
aTimeString = "4:35:47 PM"
' The following line of code sets aDate to a Date value.
aDate = CDate(aDateString)
' The following line of code sets aTime to Date value.
aTime = CDate(aTimeString)
CDbl Example
VB
Dim aDec As Decimal
Dim aDbl As Double
' The following line of code uses the literal type character D to make aDec a Decimal.
aDec = 234.456784D
' The following line of code sets aDbl to 1.9225456288E+1.
aDbl = CDbl(aDec * 8.2D * 0.01D)
CDec Example
74
The following example uses the CDec function to convert a numeric value to Decimal.
VB
Dim aDouble As Double
Dim aDecimal As Decimal
aDouble = 10000000.0587
' The following line of code sets aDecimal to 10000000.0587.
aDecimal = CDec(aDouble)
CInt Example
The following example uses the CInt function to convert a value to Integer.
VB
Dim aDbl As Double
Dim anInt As Integer
aDbl = 2345.5678
' The following line of code sets anInt to 2346.
anInt = CInt(aDbl)
CLng Example
The following example uses the CLng function to convert values to Long.
VB
Dim aDbl1, aDbl2 As Double
Dim aLng1, aLng2 As Long
aDbl1 = 25427.45
aDbl2 = 25427.55
' The following line of code sets aLng1 to 25427.
aLng1 = CLng(aDbl1)
' The following line of code sets aLng2 to 25428.
aLng2 = CLng(aDbl2)
CObj Example
The following example uses the CObj function to convert a numeric value to Object. The
Object variable itself contains only a four-byte pointer, which points to the Double value
assigned to it.
VB
Dim aDouble As Double
Dim anObject As Object
aDouble = 2.7182818284
' The following line of code sets anObject to a pointer to aDouble.
anObject = CObj(aDouble)
CSByte Example
The following example uses the CSByte function to convert a numeric value to SByte.
VB
Dim aDouble As Double
Dim anSByte As SByte
75
aDouble = 39.501
' The following line of code sets anSByte to 40.
anSByte = CSByte(aDouble)
CShort Example
The following example uses the CShort function to convert a numeric value to Short.
VB
Dim aByte As Byte
Dim aShort As Short
aByte = 100
' The following line of code sets aShort to 100.
aShort = CShort(aByte)
CSng Example
The following example uses the CSng function to convert values to Single.
VB
Dim aDouble1, aDouble2 As Double
Dim aSingle1, aSingle2 As Single
aDouble1 = 75.3421105
aDouble2 = 75.3421567
' The following line of code sets aSingle1 to 75.34211.
aSingle1 = CSng(aDouble1)
' The following line of code sets aSingle2 to 75.34216.
aSingle2 = CSng(aDouble2)
CStr Example
The following example uses the CStr function to convert a numeric value to String.
VB
Dim aDouble As Double
Dim aString As String
aDouble = 437.324
' The following line of code sets aString to "437.324".
aString = CStr(aDouble)
The following example uses the CStr function to convert Date values to String values.
VB
Dim aDate As Date
Dim aString As String
' The following line of code generates a COMPILER ERROR because of invalid format.
' aDate = #February 12, 1969 00:00:00#
' Date literals must be in the format #m/d/yyyy# or they are invalid.
' The following line of code sets the time component of aDate to midnight.
aDate = #2/12/1969#
' The following conversion suppresses the neutral time value of 00:00:00.
' The following line of code sets aString to "2/12/1969".
aString = CStr(aDate)
76
' The following line of code sets the time component of aDate to one second past midnight.
aDate = #2/12/1969 12:00:01 AM#
' The time component becomes part of the converted value.
' The following line of code sets aString to "2/12/1969 12:00:01 AM".
aString = CStr(aDate)
CStr always renders a Date value in the standard short format for the current locale, for
example, "6/15/2003 4:35:47 PM". However, CStr suppresses the neutral values of 1/1/0001 for
the date and 00:00:00 for the time.
For more detail on the values returned by CStr, see Return Values for the CStr Function (Visual
Basic).
CUInt Example
The following example uses the CUInt function to convert a numeric value to UInteger.
VB
Dim aDouble As Double
Dim aUInteger As UInteger
aDouble = 39.501
' The following line of code sets aUInteger to 40.
aUInteger = CUInt(aDouble)
CULng Example
The following example uses the CULng function to convert a numeric value to ULong.
VB
Dim aDouble As Double
Dim aULong As ULong
aDouble = 39.501
' The following line of code sets aULong to 40.
aULong = CULng(aDouble)
CUShort Example
The following example uses the CUShort function to convert a numeric value to UShort.
VB
Dim aDouble As Double
Dim aUShort As UShort
aDouble = 39.501
' The following line of code sets aUShort to 40.
aUShort = CUShort(aDouble)
OPERATORS:
An operator is a special symbol which indicates a certain process is carried out. Operators
in programming languages are taken from mathematics. Programmers work with data. The
operators are used to process data.
77
An operator may have one or two operands. An operand is one of the inputs (arguments) of an
operator. Those operators that work with only one operand are called unary operators. Those
who work with two operands are called binary operators.
The assignment operator = assigns a value to a variable. A variable is a placeholder for a value.
In mathematics, the = operator has a different meaning. In an equation, the = operator is an
equality operator. The left side of the equation is equal to the right one.
x=1
Console.WriteLine(x) ' Prints 1
The previous expression does not make sense in mathematics. But it is legal in programming.
The expression adds 1 to the x variable. The right side is equal to 2 and 2 is assigned to x.
3=x
This code example results in syntax error. We cannot assign a value to a literal.
Concatenating strings
In Visual Basic we have two operators for string concatenation. The plus + operator and the &
ampersand operator.
Option Strict On
Module Example
Sub Main()
End Sub
End Module
And this is, what we get. Same result for both cases.
Bitwise operators
79
Decimal numbers are natural to humans. Binary numbers are native to computers. Binary, octal,
decimal or hexadecimal symbols are only notations of the same number. Bitwise operators work
with bits of a binary number. Bitwise operators are seldom used in higher level languages like
Visual Basic. Symbol Meaning
The operator reverts all bits of a number 7. One of the bits also determines, whether the number
is negative or not. If we negate all the bits one more time, we get number 7 again.
Operator precedence:
The operator precedence tells us which operators are evaluated first. The precedence level is
necessary to avoid ambiguity in expressions.
Like in mathematics, the multiplication operator has a higher precedence than addition operator.
So the outcome is 28.
(3 + 5) * 5
To change the order of evaluation, we can use parentheses. Expressions inside parentheses are
always evaluated first.
The following list shows common Visual Basic operators ordered by precedence (highest
precedence first
Operator(s) Description
^ exponentiation
+- unary identity and negation
*/ multiplication, float division
\ integer division
Mod modulus
+- addition, subtraction, string concatenation
& string concatenation
<< >> arithmetic bit shift
= <> < > >= <= Is IsNot Like TypeOf Is All comparison operators
Not negation
80
In this lesson, we will learn how to use some of the string manipulation function such as Len,
Right, Left, Mid, Trim, Ltrim, Rtrim, Ucase, Lcase, Instr, Val, Str ,Chr and Asc.
The length function returns an integer value which is the length of a phrase or a sentence,
including the empty spaces. The format is
Len (“Phrase”)
For example,
The Len function can also return the number of digits or memory locations of a number that is
stored in the computer. For example,
X=sqr (16)
Y=1234
Z#=10#
End Sub
will produce the output 1, 4 , 8. The reason why the last value is 8 is because z# is a double
precision number and so it is allocated more memory spaces.
81
The Right function extracts the right portion of a phrase. The format is
Right (“Phrase”, n)
Where n is the starting position from the right of the phrase where the portion of the phrase is
going to be extracted. For example,
The Left$ function extract the left portion of a phrase. The format is
Left(“Phrase”, n)
Where n is the starting position from the left of the phase where the portion of the phrase is
going to be extracted. For example,
The Ltrim function trims the empty spaces of the left portion of the phrase. The format is
Ltrim(“Phrase”)
.For example,
The Rtrim function trims the empty spaces of the right portion of the phrase. The format is
Rtrim(“Phrase”)
.For example,
The Ttrim function trims the empty spaces on both side of the phrase. The format is
Trim(“Phrase”)
.For example,
The Mid function extracts a substring from the original phrase or string. It takes the following
format:
Mid(phrase, position, n)
Where position is the starting position of the phrase from which the extraction process will start
and n is the number of characters to be extracted. For example,
The InStr function looks for a phrase that is embedded within the original phrase and returns the
starting position of the embedded phrase. The format is
Where n is the position where the Instr function will begin to look for the embedded phrase. For
example
The Ucase function converts all the characters of a string to capital letters. On the other hand, the
Lcase function converts all the characters of a string to small letters. For example,
The Str is the function that converts a number to a string while the Val function converts a string
to a number. The two functions are important when we need to perform mathematical operations.
The Chr function returns the string that corresponds to an ASCII code while the Asc function
converts an ASCII character or symbol to the corresponding ASCII code. ASCII stands for
“American Standard Code for Information Interchange”. Altogether there are 255 ASCII codes
and as many ASCII characters. Some of the characters may not be displayed as they may
represent some actions such as the pressing of a key or produce a beep sound. The format of the
Chr function is
Chr(charcode)
Asc(Character)
The system's current date and time can be retrieved using the Now, Date and Time functions in
Visual Basic. The Now function retrieves the date and time, while Date function retrieves only
date and Time function retrieves only the time.
To display both the date and time together a message box is displayed use the statement given
below.
MsgBox "The current date and time of the system is" & Now
Here & is used as a concatenation operator to concentrate the string and the Now function.
Selective portions of the date and time value can be extracted using the below listed functions.
Function Extracted Portion
Year ( ) Year (Now)
Month ( ) Month (Now)
Day ( ) Day (Now)
WeekDay ( ) WeekDay (Now)
Hour ( ) Hour (Now)
84
The calculation and conversion functions related to date and time functions are listed below.
Function Description
DateAdd ( ) Returns a date to which a specific interval has been added
DateDiff ( ) Returns a Long data type value specifying the interval between the two values
DatePart ( ) Returns an Integer containing the specified part of a given date
DateValue ( ) Converts a string to a Date
TimeValue ( ) Converts a string to a time
DateSerial ( ) Returns a date for specified year, month and day
DateDiff Function
The DateDiff function returns the intervals between two dates in terms of years, months or days.
The syntax for this is given below.
The format function accepts a numeric value and converts it to a string in the format specified by
the format argument. The syntax for this is given below.
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 Bars – 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) –
Menus – Menu Editor – Menu Creation
Books for Reference:
1. Steven Holzner, “VB 6 Programming Black Book”, Dream Tech Press, New Delhi, 2002.
2. N. Krishnan & N. Saravanan, “Visual Basic 6.0 in 30 days”, Scitech Publications, (India)
Pvt Ltd., Chennai, 2001.
85
The Form
The Form is the first object you see when you Open the application. It's the window into
which all the controls will appear, where you will input data and see results.
There's not too much you can do with the form at this time. Basically, you adjust
the BackColor and the StartUpPosition (where it will open on the screen when you Run it) and
then you start putting controls on it.
The Label:
This is probably the first control you will master. It is used to display static text, titles and screen
output from operations. The important properties to remember:
The command button is one of the most important controls as it is used to execute
commands. It displays an illusion that the button is pressed when the user click on it. The most
common event associated with the command button is the Click event, and the syntax for the
procedure is
Statements
End Sub
The text box is the standard control for accepting input from the user as well as to display
the output. It can handle string (text) and numeric data but not images or pictures. Just like text
fields in websites, powered not by Windows, but typically linux web hosting platforms like
iPage, these fields collect user input.String in a text box can be converted to a numeric data by
using the function Val(text). The
following example
The Picture Box is one of the controls that is used to handle graphics. You can load a
picture at design phase by clicking on the picture item in the properties window and select the
picture from the selected folder. You can also load the picture at runtime using
the LoadPicture method. For example, the statement will load the picture grape.gif into the
picture box.
You will learn more about the picture box in future lessons. The image in the picture box is not
resizable.
The Image Box is another control that handles images and pictures. It functions almost
identically to the picture box. However, there is one major difference, the image in an Image Box
is stretchable, which means it can be resized. This feature is not available in the Picture Box.
Similar to the Picture Box, it can also use the LoadPicture method to load the picture. For
example, the statement loads the picture grape.gif into the image box.
The function of the List Box is to present a list of items where the user can click and select the
items from the list. In order to add items to the list, we can use the AddItem method. For
example, if you wish to add a number of items to list box 1, you can key in the following
statements
Example 3.2
List1.AddItem “Lesson1”
List1.AddItem “Lesson2”
List1.AddItem “Lesson3”
List1.AddItem “Lesson4”
End Sub
The items in the list box can be identified by the ListIndex property, the value of the ListIndex
for the first item is 0, the second item has a ListIndex 1, and the third item has a ListIndex 2 and
so on
The function of the Combo Box is also to present a list of items where the user can click and
select the items from the list. However, the user needs to click on the small arrowhead on the
right of the combo box to see the items which are presented in a drop-down list. In order to add
88
items to the list, you can also use the AddItem method. For example, if you wish to add a
number of items to Combo box 1, you can key in the following statements
Example 3.3
Combo1.AddItem “Item1”
Combo1.AddItem “Item2”
Combo1.AddItem “Item3”
Combo1.AddItem “Item4”
End Sub
The Check Box control lets the user selects or unselects an option. When the Check Box is
checked, its value is set to 1 and when it is unchecked, the value is set to 0. You can include the
statements Check1.Value=1 to mark the Check Box and Check1.Value=0 to unmark the Check
Box, as well as use them to initiate certain actions. For example, the program will change the
background color of the form to red when the check box is unchecked and it will change to blue
when the check box is checked. You will learn about the conditional statement
If….Then….Elesif in later lesson. VbRed and vbBlue are color constants and BackColor is the
background color property of the form.
Example 3.4
End Sub
89
The Option Box control also lets the user selects one of the choices. However, two or
more Option Boxes must work together because as one of the Option Boxes is selected, the other
Option Boxes will be unselected. In fact, only one Option Box can be selected at one time. When
an option box is selected, its value is set to “True” and when it is unselected; its value is set to
“False”. In the following example, the shape control is placed in the form together with six
Option Boxes. When the user clicks on different option boxes, different shapes will appear. The
values of the shape control are 0, 1, and 2,3,4,5 which will make it appear as a rectangle, a
square, an oval shape, a rounded rectangle and a rounded square respectively.
Example 3.5
Private Sub Option1_Click ( )
Shape1.Shape = 0
End Sub
Shape1.Shape = 5
End Sub
The Drive ListBox is for displaying a list of drives available in your computer. When you place
this control into the form and run the program, you will be able to select different drives from
your computer as shown in Figure 3.4
The Directory List Box is for displaying the list of directories or folders in a selected drive.
When you place this control into the form and run the program, you will be able to select
different directories from a selected drive in your computer as shown in Figure 3.5
The File List Box is for displaying the list of files in a selected directory or folder. When you
place this control into the form and run the program, you will be able to shown the list of files in
a selected directory as shown in Figure 3.6
Scroll Bars:
Vertical scroll bar
92
Value
The Value property returns the scroll bar position's value. Each position of the thumb has a
value. The Value changes when you click on one of the arrow buttons or when you move the
thumb by dragging it.
Min
The Min property sets/returns the minimum value of a scroll bar position.
Max
The Max property sets/returns the maximum value of a scroll bar position.
SmallChange
The SmallChange property sets/returns the amount of change to Value property in a scroll bar
when the user clicks on a scroll arrow button.
LargeChange
93
The LargeChange property sets/returns the amount of change to Value property in a scroll bar
when the user clicks on the scroll bar area.
The Change event fires when an arrow button or the scroll bar area is clicked or after the thumb
has been dragged. The Scroll event is raised when the thumb is being dragged.
Sample program
TIMER CONTROL:
The Visual Basic Timer control helps in executing a set of code repeatedly at specific
intervals. When you draw the control on the form, it is only visible during design time and is
hidden during runtime.
Tick Event
The code that needs to be executed is written in the Tick event of the Timer control in
VB.NET and the same is known as Timer event in VB 6.0. This event is triggered after
each Interval, as long as the Timer Enabled property is True.
Interval Property
This property of the visual basic timer control is used to set the number of milliseconds
between subsequent Tick events (Timer event in case if VB 6.0). The value of this property is a
32-bit integer i.e. from 1 to 2147483647 - in VB.NET. In case if VB 6.0 it is a 16-bit integer and
valid values are from 0 to 65535. If the value is set to 0 it means nothing will happen, the Timer
event will not at all be triggered.
Enabled Property
This property is similar in use as for the other controls. When Enabled is set to True the
code under the Tick event will keep getting executed after every elapse of Interval milliseconds.
If you no longer want the Visual Basic Timer control to execute the Tick code, you need to stop
the Timer by setting its Enabled property to False. In VB 6.0 this can also be done by setting the
Interval property to 0.
94
FRAME:
Properties
Frame
General
Color
Font
The Line and Shape controls work together to draw lines, boxes, and all kinds of figures on the
form. By placing the controls and setting appropriate properties, you'll be adding flair to
applications. The properties of each control that you place on your form determine exactly what
kind of image the control becomes.
Here are the primary graphics images that you can draw with the Line and Shape controls:
Lines
Rectangles
Squares
Ovals
Circles
Rounded rectangles
Rounded squares
Figure 19.8 shows most of these images. By combining these fundamental geometric images and
setting appropriate color and size properties, you can draw virtually anything you need to draw
on the form.
97
Table 19.1 lists the fundamental property values for the Line control. Table 19.2 contains the
values that you can specify for theBorderStyle property. The BorderStyle property determines
the pattern that Visual Basic uses to draw the line. By specifying various BorderStyle values,
you can vary the line pattern. If you assign a BorderStyle property at runtime, you can either
specify a number that represents BorderStyle or use one of Visual Basic's named literals.
BorderStyle Contains one of seven values that specifies the pattern of the drawn line. See Table
19.2 for available BorderStylevalues. The default value is 1-Solid. BorderStyle has
no effect on lines with BorderWidth greater than 1 twip.
DrawMode An advanced style that determines how the bit patterns of the line interact with the
surrounding form's bit appearance. The default value, 13-Copy Pen, works well for
virtually all Visual Basic applications.
Visible Holds True or False, indicating whether the user can see the Line control. You
might want to set the Visible property in code so the line appears as a highlighting
tool.
X1 Contains the number of twips from the left of the Form window to the start of the
line.
X2 Contains the number of twips from the left of the Form window to the end of the
line.
98
Property Description
Y1 Contains the number of twips from the top of the Form window to the left starting
point of the line.
Y2 Contains the number of twips from the top of the Form window to the lower ending
point of the line.
5-Dash-Dot- vbBSDashDotDot The line is composed of a series of one dash followed by two
Dot dots.
Figure 19.9 shows how various BorderStyle settings affect the lines you
draw. BorderStyle determines how a series of dashes and dots compose the line's pattern. (Is
this Morse code we're speaking here?)
To draw a line, double-click the Line control on the toolbox. A line appears in the center of the
form with a handle on each end. To move the line to a different location, drag the center of the
line with the mouse. To lengthen or shorten the line, drag either handle on the line. You can raise
and lower either end of the line by dragging either end's handle with the mouse.
After you position the line with the mouse in the approximate location at which you need the line
to appear, you can fine-tune the line's size and location by setting the various property values. If
you're a patient programmer, you can even animate the lines by changing the X1, X2, Y1,
and Y2 property settings repeatedly through code.
Figure 19.10 contains the Form window that might be used as a company's front-end form. The
various lines help separate controls from the title. As you can see, lines help focus the user's
attention.
BackColor Specifies a Windows color value that determines the background color of the
shape.
100
Property Description
BackStyle Contains either 0-Transparent (the default) or 1-Opaque, which determines whether
the background of the form appears through the shape or if the shape hides
whatever it covers.
BorderColor Specifies a Windows color value that determines the color of the shape's bordering
edges.
BorderStyle Contains one of seven values that specifies the pattern of the shape's border. The
Line control's BorderStyle values (refer to Table 19.2) provide the
shape's BorderStyle possible values as well. The default value is 1-
Solid. BorderStylehas no effect on shapes with a BorderWidth greater than 1 twip.
BorderWidth Specifies the size, in twips, that the shape's outline takes.
DrawMode An advanced style that determines how the bit patterns of the shape interact with
the surrounding form's bit appearance. The default value, 13-Copy Pen, works well
for virtually all Visual Basic applications.
FillColor Specifies a Windows color value that determines the color of the shape's interior
lines.
FillStyle Contains one of eight values that specifies the pattern of lines with which Visual
Basic paints the interior of the shape. Table 19.4 contains the possible values for
the shape's FillStyle. The default FillStyle value is 0-Solid.
Height Specifies the number of twips high that the shape is (from the highest point to the
lowest point in the shape).
Left Specifies the number of twips from the form's left edge to the shape's far left edge.
Shape Contains one of six values that specifies the type of shape that the Shape control
takes on. Table 19.5 contains the possible values for the shape's Shape property.
The default Shape property is 0-Rectangle.
Top Specifies the number of twips from the form's top edge to the shape's highest edge.
Width Specifies the number of twips wide that the shape takes (at the widest axis).
Table 19.4 contains the possible values for the Shape control's FillStyle property. Figure
19.11 shows the various fill patterns that a shape can contain.
101
Figure 19.11 The FillStyle property determines the shape's interior design.
Table 19.5 contains the possible values for the Shape control's Shape property. Figure
19.8 shows the various shapes that the Shape control can take. Therefore, when you want to
place a square on a form, you'll place the Shape control on the form and set the Shape property
to 1-Square.
0-Rectangle A rectangle
102
Value Description
1-Square A square
2-Oval An oval
3-Circle A circle
CONTROL ARRAY:
Control Array is the collection of controls that programmer put it in form (VB Form).
Control array is always a single dimensional array. Control array is that you can add or delete
array elements at run-time. With some controls, it is very useful to define control arrays - it
depends on the application.
Control arrays are a convenient way to handle groups of controls that perform a similar
function. All of the events available to the single control are still available to the array of
controls, the only difference being an argument indicating the index of the selected array element
is passed to the event. Hence, instead of writing individual procedures for each control (i.e. not
using control arrays), you only have to write one procedure for each array.
The set of controls that form a control array must be all of the same type (all textboxes,
all labels, all option buttons, etc.)
You set up a control array by naming one or more controls of the same type the same
name and set the Index property of each control in the array to a non-negative value (i.e., the
controls in the control array are usually indexed from 0 to one less than the number of controls in
the array).
The properties of the controls in the control array can vary: i.e., some members can be
visible or not, they can be sized differently, they can have different fonts or colors, etc.
ControlName(Index)[.Property]
For example, to refer to the Text property of the first element of an array of textboxes
called txtField, you would use:
txtField(0).Text
All the members of the control array share the same event procedure – for example, if
you have a control array of 10 textboxes call txtField, indexed 0 to 9, you will not have 10
103
different GotFocus events – you will just have one that is shared amongst the 10 members. To
differentiate which member of the control array is being acted upon, VB will automatically pass
an Index parameter to the event procedure. For example, the GotFocus event procedure for the
txtField control array might look like this:
txtField(Index).SelStart = 0
txtField(Index).SelLength = Len(txtField(Index).Text)
End Sub
- or -
With txtField(Index)
.SelStart = 0
.SelLength = Len(.Text)
End With
End Sub
For events where VB already passes a parameter (for example, the textbox's KeyPress
event where VB passes the KeyAscii parameter), VB will add "Index" as the first
parameter, followed by the parameters that are usually passed to the event. For example,
the procedure header of the KeyPress event of the txtField control array would look like
this:
DIALOG BOXES:
A dialog box is a form defined with particular properties. Like a form, a dialog box is referred
to as a container. Like a form, a dialog box is mostly used to host child controls, insuring the
role of dialog between the user and the machine. Here is an example of a dialog box:
104
The only system button it is equipped with is Close . As the only system button, this
button allows the user to dismiss the dialog and ignore whatever the user would have
done on the dialog box
It cannot be minimized, maximized, or restored. A dialog box does not have any other
system button but Close
It is usually modal, in which case the user is not allowed to continue any other operation
on the same application until the dialog box is dismissed
It provides a way for the user to close or dismiss it
The Border Style of a Dialog Box
There are a few actions you should perform on a form to transform it into a dialog box;
but normally, these are only suggestions, not rules. Based on the Microsoft Windows
design and standards, to create a dialog box, you should set a
form'sFormBorderStyle property to FixedDialog. Setting this property changes the
borders of the form to the standard borders of a dialog box (the border of a dialog box is
thinner than that of a regular form). You can set this characteristic in the Properties
window or programmatically. Here is an example:
Public Sub InitializeComponent()
Text = "Domain Configuration"
Width = 320
Height = 150
Location = New Point(140, 100)
StartPosition = FormStartPosition.CenterScreen
FormBorderStyle = Windows.Forms.FormBorderStyle.FixedDialog
End Sub
FormBorderStyle = Windows.Forms.FormBorderStyle.FixedDialog
105
MinimizeBox = False
MaximizeBox = False
End Sub
Accepting an Action
Often the user will be presented with various options on a dialog box and may be asked
to make a decision on the available controls. Most of the time, if you are creating such a
dialog box, besides the OK button, it should also have a Cancel button. The OK button
should be the default so that if the user presses Enter, the dialog box would be closed as if
the user had clicked OK. Clicking OK or pressing Enter would indicate that, if the user
had made changes on the controls of the dialog box, those changes would be
acknowledged and kept when the dialog box is closed and usually the changed values of
the control would be transferred to another dialog box or form. Keep in mind that you are
responsible for implementing this functionality.
To fulfill this functionality of the OK button, after adding it to a dialog box (or form),
open the AcceptButton combo box in the Properties window for the form and select the
name of the button.
A Modal dialog box is one that the user must first close in order to have access to any other
framed window or dialog box of the same application. One of the scenarios in which you use a
dialog box is to create an application that is centered around one.
In this case, if either there is no other form or dialog box in your application or all the other
forms or dialog boxes depend on this central dialog box, it must be created as modal. Such an
application is referred to as dialog-based.
Some applications require various dialog boxes to complete their functionality. When in case,
you may need to call one dialog box from another and display it as modal. Here is an example:
A modeless dialog box is created from a form but it should look like a regular dialog box or a
tool window. Therefore, to create a modeless dialog box, set the FormBorderStyle property to
an appropriate value such
as FixedSingle, FixedToolWindow, Sizable or SizableToolWindow. Also, set
its ShowInTaskbar property to False.
After creating the dialog box, to display it as modeless, call the Show() method. the modeless
dialog box always remains on top of the application. This is easily taken care of by setting the
Boolean TopMostproperty of the form to True.
There are two main ways a normal modeless dialog box can be dismissed:
If the user has finished using it, he or she can close it and recall it at will
When the form or application that owns the modeless dialog box is closed, the form or
application closes the modeless dialog if it is opened; this means that you don't need to
find out whether a modeless dialog box is still opened when the application is being
destroyed: either the user or the application itself will take care of closing it
Use the InputBox function to solicit data from the user. This function displays a modal dialog
box that asks the user to enter some data. The text input box shown in Figure 6.17 prompts the
user for the name of the file to open.
108
The following code displays the input box shown in Figure 6.17:
FileName = InputBox("Enter file to open:", "File Open")
Note Remember that when you use the InputBox function, you have little control over the
components of the dialog box. You can change only the text in the title bar, the command prompt
displayed to the user, the position of the dialog box on the screen, and whether or not it displays
a Help button.
Use the MsgBox function to get yes or no responses from users, and to display brief messages,
such as errors, warnings, or alerts in a dialog box. After reading the message, the user chooses a
button to close the dialog box.
An application named Text Editor might display the message dialog box shown in Figure 6.18 if
a file cannot be opened.
Figure 6.18 An error message dialog box created using the MsgBox function
The following code displays the message box shown in Figure 6.18:
MsgBox "Error encountered while trying to open file, _
please retry.", vbExclamation, "Text Editor"
Adding a Title
A dialog box should always have a title that identifies it. To create a title, set the form's Caption
property to the text string that will appear in the title bar. Usually, this is done at design time
using the Properties window, but you can also do this from code. For example:
109
frmAbout.Caption = "About"
Tip If you want to remove the title bar completely, set the form's ControlBox, MinButton, and
MaxButton properties to False; set the BorderStyle to a nonsizable setting (0, 1, or 3); and set the
Caption equal to an empty string ("").
BorderStyle 1 Changes the border style to fixed single, thus preventing the dialog box
from being sized at run time.
MaxButton False Removes the Maximize button, thus preventing the dialog box from
being maximized at run time.
MinButton False Removes the Minimize button, thus preventing the dialog box from
being minimized at run time.
Generally, the user responds to a dialog box by providing information and then closing the
dialog box with an OK or Cancel command button. Because a dialog box is temporary, users
usually don't need to move, size, maximize, or minimize it. As a result, the sizable border style,
Control menu box, Maximize button, and Minimize button that come with a new form are
unnecessary on most dialog boxes.
You can remove these items by setting the BorderStyle, ControlBox, MaxButton, and MinButton
properties. For example, an About dialog box might use the following property settings.
Remember that if you remove the Control menu box (ControlBox = False), you must provide the
user with another way to exit the dialog box. This is commonly done by adding an OK, Cancel,
or Exit command button to the dialog box and adding code in the Click event for the button that
hides or unloads the dialog.
110
Each window of the application holds a single document, so if the user wants to open more
documents with that application, he must open a new window. Its also the default mode when
building an application with Visual Basic. An example of an SDI application is Windows
Notepad.
Advantages of SDI
An SDI interface works very well with multiple monitors and multiple virtual desktops. It
also allows users to switch between multiple open documents using the native Windows taskbar
and task manager, rather than through special code that must be written into your application.
Multiple-Document Interface (MDI) :
The multiple-document interface (MDI) allows you to create an application that maintains
multiple forms within a single container form. Applications such as Microsoft Excel and
Microsoft Word for Windows have multiple-document interfaces.
An MDI application allows the user to display multiple documents at the same time, with each
document displayed in its own window. Documents or child windows are contained in a parent
window, which provides a workspace for all the child windows in the application. For example,
Microsoft Excel allows you to create and display multiple-document windows of different types.
Each individual window is confined to the area of the Excel parent window. When you minimize
Excel, all of the document windows are minimized as well; only the parent window's icon
appears in the task bar.
A child form is an ordinary form that has its MDIChild property set to True. Your application
can include many MDI child forms of similar or different types.
At run time, child forms are displayed within the workspace of the MDI parent form (the area
inside the form's borders and below the title and menu bars). When a child form is minimized, its
icon appears within the workspace of the MDI form instead of on the taskbar, as shown in Figure
6.4.
111
6.4 Child forms displayed within the workspace of the MDI form
Note Your application can also include standard, non-MDI forms that are not contained in the
MDI form. A typical use of a standard form in an MDI application is to display a modal dialog
box.
An MDI form is similar to an ordinary form with one restriction. You can't place a control
directly on a MDI form unless that control has an Align property (such as a picture box control)
or has no visible interface (such as a timer control).
To create an MDI child form, create a new form (or open an existing one) and set its
MDIChild property to True.
Advantages of MDI
MDI applications can often handle multiple documents more readily than SDI programs.
For example, many MDI text editors allow the user to open multiple text files side by side in the
same window, making it easy to compare and look up information from a second document
while working on the first.
112
Visual Basic provides an easy way to create menus with the modal Menu Editor dialog. The
below dialog is displayed when the Menu Editor is selected in the Tool Menu. The Menu Editor
command is grayed unless the form is visible. And also you can display the Menu Editor window
by right clicking on the Form and selecting Menu Editor.
Basically, each menu item has a Caption property (possibly with an embedded & character to
create an access key) and a Name. Each item also exposes three Boolean properties, Enabled,
Visible, and Checked, which you can set both at design time and at run time.
At design time, you can assign the menu item a shortcut key so that your end users don't have to
go through the menu system each time they want to execute a frequent command
Building a menu is a simple, albeit more tedious, job: You enter the item's Caption and Name,
set other properties (or accept the default values for those properties), and press Enter to move to
the next item. When you want to create a submenu, you press the Right Arrow button (or the
Alt+R hot key). When you want to return to work on top-level menus—those items that appear
in the menu bar when the application runs—you click the Left Arrow button (or press Alt+L).
You can move items up and down in the hierarchy by clicking the corresponding buttons or the
hot keys Alt+U and Alt+B, respectively.
You can create up to five levels of submenus (six including the menu bar), which are too many
even for the most patient user. If you find yourself working with more than three menu levels,
think about trashing your specifications and redesigning your application from the ground up.
You can insert a separator bar using the hypen (-) character for the Caption property. But even
these separator items must be assigned a unique value for the Name property, which is a real
nuisance. If you forget to enter a menu item's Name, the Menu Editor complains when you
decide to close it. The convention used in this book is that all menu names begin with the three
letters menu.
113
An expanded menu
The programmer can create menu control arrays. The Index TextBox specifies the menu's index
in the control array.
114
The Menu Editor dialog also provides several CheckBoxes to control the appearance of the
Menu.
Checked : This is unchecked by default and allows the programmer the option of creating a
checked menu item( a menu item that act as a toggle and displays a check mark when selected.
The following is a Check Menu items.
Enabled : specifies whether a menu is disabled or not. If you see a disabled command in a menu
that means that feature is not available. The Visible checkbox specifies whether the menu is
visible or not.
To add commands to the Form's menu bar, enter a caption and a name for each command. As
soon as you start typing the command's caption, it also appears in a new line in the list at the
bottom of the Menu Editor window. To add more commands click Enter and type the Caption
and the Name.
Creating Menus
Open a new Project and save the form as menu.frm and save the project as menu.vbp.
Choose Tools ››› Menu Editor and type the menu items as shown below.
Caption Name
File mnuFile
Open mnuOpen
Save mnuSave
Exit mnuExit
Edit mnuEdit
Copy mnuCopy
Cut mnuCut
Paste mnuPaste
115
Unit – V
Data Controls – Data Access Objects (DAO) – Accessing and Manipulating Databases –
Recordset –Types 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.
Introduction:
A character is the most basic element of data that can be observed and manipulated.
Behind it are the invisible data elements we call bits and bytes, referring to physical storage
elements used by the computer hardware. A field contains an item of data; that is, a character, or
group of characters that are related. A record is composed of a group of related fields. A
database is a collection of information that is organized so that it can easily be accessed,
managed, and updated. Database management systems are used to access and manipulate data
in a database. A database management system is a software package that enables users to edit,
link, and update files as needs dictate.
116
In order to track and analyze data effectively, each record requires a unique identifier or
what is called a key. The key must be completely unique to a particular record just as each
individual has a unique social security number assigned to them.
Data Controls:
Visual Basic communicates with databases through the data control. Data controls can
read, modify, delete, and add records to databases. 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 inbound controls. The disadvantage of
using the data control is that once the project is completed, it is not always easy to modify the
data entry form or adapt the finished form for another data entry project
Jet Engine can also access ODBC data sources using ODBC drivers.
Jet Engine also has its own query engine, which is used to search, order and filter the data
without using the query engine of the database. This may be an advantage with small databases
such as MS-Access and FoxPro, but for large databases such as Oracle database, using Jet query
engine may be inefficient.
To illustrate DAO data handling in code, we’ll build a fully functional DAO project—the
daocode project. This program has a File menu with the following items:
• New Database—Creates a new database.
• Open Database—Opens a database.
• Close Database—Closes the current database.
• New Table—Creates a new table.
• Search—Searches the database.
• Sort—Sorts the database.
• Exit—Exits the application.
Creating a Database:
It is, with the objects in the Microsoft DAO Object Library. To add a reference to that
library, select the Project |References menu item, select the Microsoft DAO Object Library, and
click on OK to close the References dialog box.
Now we can make use of the data objects in that library to create a new database using
CreateDatabase. CreateDatabase is a method of the DAO Workspace object (there are a
collection of Workspace objects in the DAO DBEngine object’s Workspaces collection). Here’s
how you use CreateDatabase:
Set database = workspace.CreateDatabase (name, locale [, options])
Here are the arguments to CreateDatabase:
• name—A string up to 255 characters long that is the name of the database file that you’re
creating. It can be the full path and file name, such as C:vbbb\db.mdb. If you don’t supply a file
name extension, .mdb is added.
• Locale—a string that specifies a collating order for creating the database, like dbLangGeneral
(which includes English), dbLangGreek, and so on.
Here are the possible settings for the options argument:
• dbEncrypt—Creates an encrypted database.
118
• dbVersion10—Creates a database that uses the Jet engine version 1 file format.
• dbVersion11—Creates a database that uses the Jet database engine version 1.1 file format.
• dbVersion20—Creates a database that uses the Jet database engine version 2 file format.
• dbVersion30—The default. Creates a database that uses the Jet database engine version 3 file
format (compatible with version 3.5).
A data bound control connects a data control in Visual Basic to a database table or
query. Data controls are visual objects that are said to be data-aware. Data controls may include
check boxes, images, labels, picture boxes, and text boxes (see figure). Visual Basic's data
controls allow users to access stored database records. The data control establishes a link
between the database and other controls in the interface, in a process called binding.
When a control is bound, it displays database field contents when the Data control is
present. Required property settings for the Data control include the DatabaseName property
which specifies the complete path to the database (see figure B), and
the RecordSource property, which indicates the table to use from the database (see figure C).
The DataSource property (specifies the name of the Data control to which it is bound)
and the DataField property (specifies the name of a field in the database to which the control is
linked) should be set for all form controls that access database information (Cashman, VB 4).
The properties list for a data control (see figures B and C) includes a "DatabaseName" to
specify the database the control is to connect to and a "Recordsource" to specify the table in the
database, or the SQL statement, for the data. SQL stands for Structured Query Language--a high-
level language used to manipulate and/or define databases.
Data controls rely on Data Access Objects (DAO) to perform processing. The DAO provide a
more comprehensive interface to data using Visual Basic--they allow the user to run queries,
120
update database table values and create the structure of databases (McManus, Database Access
with Visual Basic 6.0).
1. Database Name--(DatabaseName) This is the full path to the database to which you
would like to connect.
2. Table Name--(RecordSource) This is the name of the table in 1) to which you would like
to connect.
3. Field Name--(DataField) This is the field to which your control should be connected.
4. Data Source--(DataSource) This is the name of the data control to be specified in linked
components (such as text boxes). This is necessary because it is possible to have two data
controls on one form.
Users may add records to the database with data controls in two ways:
Using the EOFAction property, which indicates the action to take when the user tries to
move past the last record in a table. Parameters for the EOFAction property are: 0 for
Move Last (move the last record in the database), 1 for EOF (default), or 2 for Add New
(adds a new record to the database).
Using "AddNew" with the connected data control's record set.
(ex. DataCustomer.Recordset.AddNew )
Records may be updated using "Update" with the connected data control's record set in the same
way "AddNew" is used.
Data binding features may be set for a control in the Procedure Attributes dialog box
(see figure D). The Procedure Attributes box is active after a procedure has been added. A
procedure may be added to a module by choosing Add Procedure from the Tools menu. After
adding the procedure, the full procedure attributes box is available under Tools, Procedure
Attributes, then Advanced. The "Name" property must be set to the name of the data control
being bound, and the "Property is Data Bound" checkbox must be checked.
121
The checkbox labeled "This property binds to DataField" specifies that the property
should appear alone under the DataField Property which is used when a control has a single
bound property. The checkbox labeled "Show in DataBindings collection at design time"
determines whether the bound property appears in the Properties window under the
DataBindings property. The checkbox labeled "Property will call CanPropertyChange before
changing" specifies that the control will check with the container to see if the property can be
changed (Cashman, VB 4).
Recordset:
defining one attribute of information for the record. Taken together, a record defines one specific
unit of retrievable information in a database."
The Recordset's five most common methods that enable you to programmatically position the
record pointer are as follows:
Move - This method takes a positive or negative Long value as a required parameter. The
parameter specifies the number of records to move away from the current record pointer
position. Positive values indicate forward movement, while negative values indicate
backward movement. An optional second parameter enables you to specify the Bookmark
of a different record. Specifying this second parameter causes the movement to happen
relative to the record of the Bookmark.
MoveFirst - Moves the record pointer to the first row of the Recordset's data.
MoveLast - Moves the record pointer to the last row of the Recordset's data.
MoveNext - Moves the record pointer one row beyond its current position in the
Recordset.
MovePrevious - Moves the record pointer one row before its current position in the
Recordset.
You might call these methods to programmatically process records, or you might call them in
response to some user action, such as clicking buttons labeled Next, Previous, First, or Last.
The following table summarizes the characteristics and purposes of the three recordset types.
Best Uses Working with a Working with records, possibly Finding data or preparing
single table (in a non- containing fields from one or reports. Reflects the state
ODBC database). more tables. Reflects changes by of the data at the time of
other users and is updatable. the snapshot.
Limitations Can use only with Doesn't reflect new records that Not updatable. The
.MDB databases or meet selection criteria after the snapshot is not quite
ISAM tables opened recordset opens. instantaneous..
directly.
A dynaset is a recordset that reflects changes to the underlying records by other users of the
database or by other recordsets. As your application scrolls to a changed record, a new copy is
retrieved, bringing it up to date. This behavior is ideal for situations in which it is important to be
completely up to date.
Creating a Recordset:
The process of creating recordset objects based either on class CDaoRecordset itself or
on a class derived from CDaoRecordset.
You can use recordset objects in two ways:
Create recordsets directly from class CDaoRecordset and bind record fields
dynamically.
Derive your own custom recordset class from CDaoRecordset and use DAO Record Field
Exchange (DFX) to manage binding record data to recordset class field data members.
In either case, you can base your recordset objects on a query defined by
a CDaoQueryDef object or a CDaoTableDef object, or you can specify the recordset objects'
SQL strings either at design time, when you create the class, or at run time, when you pass a
string containing an SQL statement to the CDaoRecordset::Open member function.
The following table describes the characteristics of a recordset, depending on how you create it:
The SQL string specified at The recordset uses the SQL string retrieved by calling
design time its GetDefaultSQL member function.
An SQL string specified at run The SQL string passed to Open overrides the SQL defined
time, in the Open call at design time.
1. Create the querydef, as described in Creating a Query with a Querydef, or use an existing
querydef object.
2. Construct a CDaoRecordset object.
3. Call the recordset object's Open member function, passing a pointer to the querydef
object.
Opening the recordset runs the query, using the SQL statement defined by the querydef.
The following code shows the process of creating a recordset from a querydef:
// pdb is a pointer to an open CDaoDatabase object
try
125
{
// Construct the querydef
CDaoQueryDef qd( pdb );
The fields of the new recordset, represented by the recordset's edit buffer (the recordset's
data members), are initially all Null. AddNew prepares the MFC recordset's edit buffer,
which DAO calls the copy buffer.
126
If you're using a CDaoRecordset-derived class with DFX, assign values to the fields. If
you have double buffering turned off, make the following two calls for each field you
assign a value to:
SetFieldDirty
SetFieldNull with the parameter FALSE (meaning "not Null").
Or, if you explicitly want the field to be Null, call only SetFieldNull, with the
parameter TRUE.
Update adds the record. If no transaction is in effect, the change takes place immediately.
Otherwise, the change takes place when you call CDaoWorkspace::CommitTrans.
If you move to another record without calling Update, the change is lost.
Edit Method
Update Method
If you have double buffering turned on, MFC maintains a copy of the edit buffer so it can detect
changes to the recordset fields for you. You don't have to
call SetFieldDirty and SetFieldNull(passing FALSE) for each change.
Use any of the recordset's navigation mechanisms that take you to a specific record.
Edit prepares the recordset's edit buffer, which DAO calls the copy buffer. For more
information about the edit buffer with Edit,
If you're using a CDaoRecordset-derived class with DFX, assign values to the fields. To
give a field the value Null, call SetFieldNull (passing TRUE). If you have double
buffering turned off, call SetFieldDirty and SetFieldNull (passing FALSE) for each field
you assign a value to.
Update changes the record in the database. If no transaction is in effect, the change takes
place immediately. Otherwise, the change takes place when you
callCDaoWorkspace::CommitTrans.
Use any of the recordset's navigation mechanisms that take you to a specific record.
4. Move to another record before you attempt any other recordset operations.
In table-type and dynaset-type recordset objects, Delete removes the current record and
makes it inaccessible. Although you can't edit or use the deleted record, it remains current. Once
you move to another record, however, you can't make the deleted record current again.
Subsequent references to a deleted record in a recordset are invalid and cause an exception to be
thrown. For more information, see Delete. You can tell whether you're on a deleted record by
calling IsDeleted.
128
Finding Records:
Using Seek
Using Find
These two mechanisms for locating records that meet certain criteria are used in different
situations, as described in the following table.
Call After Seek/Find Check Seek or Find return Check Seek or Find return value
value
Seek and Find is not the only means of navigating in a recordset. You can also use:
Using Seek:
The CDaoRecordset::Seek member function lets you search for a record in a table-type
recordset based on a table index. Two versions of the function provide for seeking based on:
129
Up to three specified keys, each of which represents a field that makes up part of the
current index.
An array of keys, for indexes with four or more fields. Each key represents one of the
fields. The array must contain at least one and no more than 13 keys.
In both versions, the search is based on a string containing a relational operator, such as
"=" or ">=", in the lpszComparison parameter and the COleVariant value specified in the first
key.
For example, suppose the comparison operator is "=" and the first key is the value
"Microsoft" (the first key being a Company Name field). Using the first version of Seek, you
would find the first record that has a Company Name of "Microsoft". The found record becomes
the current record. The following code illustrates how to use Seek:
// rs is a table-type recordset
try
{
// Set current index for recordset and
// save current position.
rs.SetCurrentIndex( _T("PartNameIndex") );
COleVariant varCurrentPos = rs.GetBookmark( );
This code seeks the first record whose Part Name field (the first field in the PartNameIndex
index) is "Framis Lever" (whatever a framis lever is).
Using Find:
130
Find is a virtual function. This means you can, if necessary, override it to provide your own
implementation. The other Find functions are all based on Find, so they use whatever
functionality you provide in your override. You shouldn't normally need to override Find,
however.
For example, suppose you have a dynaset-type recordset in which you want to find the first
record with a State code of "NY":
// rs is a dynaset-type recordset previously opened
CString strCriteria = _T("STATE = 'NY'");
try
{
if ( rs.FindFirst( strCriteria ) )
// Do something with the found record
rs.FindNext( strCriteria );
// ...
131
}
catch( CDaoException* e )
{
e->Delete( );
}
Data Report:
A Data Report is similar to a VB form in that it has a visual designer and a code module.
Using the visual designer, you can divide the report into two or more sections, each with its own
headings. Each section can contain controls to display the report details. The design of the details
sections is simplified by drag-and-drop functionality. The available controls are distinct from VB
controls but have similar functionality.
Data Environment:
Data Environment object is created and managed using Data Environment designer. A
Data Environment object can accomplish any of the following tasks.
1. Select Project-> Add Data Environment. If Add Data Environment option is not found then
select More ActiveX Designers and then select Data Environment.
Note: Visual Basic adds Data Environment Designer to your project and also creates a
connection object.
Command objects define specific detailed information about what data is retrieved from
a database connection. Command objects can be based on either a database object (such as a
table, view, stored procedure or synonym) or a Structured Query Language (SQL) query.
After connection is established using Connection object, now we have to create a
command object to access the data of the database. A connection object can contain any number
of command objects. In fact, a command object can contain another command object, which is
called as child command object.
A command object is created with the default name (command1). If you expand the command
object by clicking on + sign, you get the columns of AUTHORS table.
The Data Report designer is a versatile data report generator that features the ability to
created banded hierarchical reports. Used in conjunction with a data source such as the Data
Environment designer, you can create reports from several different relational tables
Automatically create reports that are exported in HTML format for instant distribution on
the Internet.
Create reports that show the sums of transactions occurring on a daily basis.
Report Header—contains the text that appears at the very beginning of a report, such as
the report title, author, or database name. If you want the Report Header to be the first
page in the report, set its ForcePageBreak property to rptPageBreakAfter.
Page Header—contains information that goes at the top of every page, such as the
report's title.
Details—contains the innermost "repeating" part (the records) of the report. The details
section is associated with the lowest-level Command object in a Data Environment
hierarchy.
Page Footer—contains the information that goes at the bottom of every page, such as the
page number.
135
Report Footer—contains the text that appears at the very end of the report, such as
summary information, or an address or contact name. The Report Footer appears between
the last Page Header and Page Footer.
2. Toolbox Controls—The Data Report designer features its own set of controls. When a
Data Report designer is added to a project, the controls are automatically created on a
new Toolbox tab named DataReport. Most of the controls are functionally identical to
Visual Basic intrinsic controls, and include a Label, Shape, Image, TextBox, and Line
control. The sixth control, the Function control, automatically generates one of four kinds
of information: Sum, Average, Minimum, or Maximum. For more information about the
Function control, see "Adding a Function Control to the Data Report."
3. Print Preview—Preview the report by using the Show method. The data report is then
generated and displayed in its own window.
4. Print Reports—Print a report programmatically by calling the PrintReport method.
When the data report is in preview mode, users can also print by clicking the printer icon
on the toolbar.
5. File Export—Export the data report information using the ExportReport method.
Formats for export include HTML and text.
6. Export Templates—You can create a collection of file templates to be used with the
ExportReport method. This is useful for exporting reports in a variety of formats, each
tailored to the report type.
When a new Data Report designer is added to a project, the following controls are automatically
placed in the Toolbox tab named DataReport:
Label Control (RptLabel)—allows you to place labels on the report to identify fields or
sections.
Image Control (RptImage)—enables you to place graphics on your report. Note that
this control cannot be bound to a data field.
Line Control (RptLine)—lets you draw rules on the report to further distinguish
sections.
Function Control (RptFunction)—a special text box that calculates values as the report
is generated.