173
1 Unit – I Introduction – Client/Server – Benefits of Client/Server – Downsizing – Upsizing Right sizing Client/Server Models Distributed Presentation – Remote Presentation – Remote Data – Distributed Logic – Distributed Data – Client/Server Architecture – Technical Architecture – Application Architecture Two Tier Architecture Three Tier Architecture OLTP & n Tier Architecture. Unit – II Introduction to Visual Basic – Steps in VB Application – Integrated Development Environment (IDE) – Menu Bar – Tool Bar – Project Explorer Window – Property Window – Toolbox – Properties, Methods and Events – Event Driven Programming – Working with Forms - Variables – Scope of Variables – Constants – Data Types. Unit – III Functions – Procedures – Control Structure : If - Switch – Select – For – While – Do While - Arrays – User Defined Data Types – Data Type Conversions - Operators – String Functions – Date and Time Functions. Unit – IV Creating and Using Standard Controls: Form, Label, Text box, Command Button, Check Box, Option Button, List Box, Combo Box, Picture Box, Image Controls, Scroll 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

STUDY MATERIAL.doc · Web view... Form, Label, Text box, Command Button, Check Box, Option Button, List Box, Combo Box, Picture Box, Image Controls, Scroll Bars – Drive List Box

Embed Size (px)

Citation preview

Page 1: STUDY MATERIAL.doc · Web view... Form, Label, Text box, Command Button, Check Box, Option Button, List Box, Combo Box, Picture Box, Image Controls, Scroll Bars – Drive List Box

1

Unit – I

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

Unit – II

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

Unit – III

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

Unit – IV

Creating and Using Standard Controls: Form, Label, Text box, Command Button, Check Box, Option Button, List Box, Combo Box, Picture Box, Image Controls, Scroll 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.

Page 2: STUDY MATERIAL.doc · Web view... Form, Label, Text box, Command Button, Check Box, Option Button, List Box, Combo Box, Picture Box, Image Controls, Scroll Bars – Drive List Box

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

What is meant by client and server?

A network is set up between client system and server system to communicate with each other is called client/server network.

The computer requesting information is called a client.

The computer responding to the request is called a server.

The individual computers is called clients.

Client-Server Models:

Distributed Presentation

Remote Presentation http://tnvelaivaaippu.gov.in/Empower/#

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.”

Along the range there are at least five points:1.Distributed presentation: The server and the client partly handle the presentation 2.Remote presentation: The client handles or controls the entire presentation3.Distributed logic: The server and the client partly handle the application logic

Page 3: STUDY MATERIAL.doc · Web view... Form, Label, Text box, Command Button, Check Box, Option Button, List Box, Combo Box, Picture Box, Image Controls, Scroll Bars – Drive List Box

3

4.Remote data management: The server handles or controls the entire Database management5. 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:

The presentation is controlled and handled entirely by the client.

Distributed logic:

The application logic is handled partly by the server and partly by the client.

Remote data management:

Database management is controlled and handled entirely by the server.

Distributed database:

Database management is handled partly by the server and partly by the client. There are,

therefore, two major applications for client/server in a library environment:

1) as the architecture for an automated library system, and

2) as an approach to linking heterogeneous systems.

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.

Layers of the Client/Server Logic

Distributed Presentation:

Page 4: STUDY MATERIAL.doc · Web view... Form, Label, Text box, Command Button, Check Box, Option Button, List Box, Combo Box, Picture Box, Image Controls, Scroll Bars – Drive List Box

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

- Adding client/server to existing applications

- Integrating multiple, existing applications on a workstation

- Supporting many terminal users and a small number of PC users

- Integrating mainframe application data into PC products

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

- Multiple operating system environments for client workstations

- Highly data centered processing

- Low powered client PCs

- Simple transaction processing

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

Page 5: STUDY MATERIAL.doc · Web view... Form, Label, Text box, Command Button, Check Box, Option Button, List Box, Combo Box, Picture Box, Image Controls, Scroll Bars – Drive List Box

5

- Mix of data and presentation level processing

- Highly complex processing demands

- Downsizing existing mainframe application

Remote Data Management

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

- Presentation oriented processing

- Shared access to data

- Upsizing of existing PC application

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

- Naturally segmented database and discrete usage

- Simple (single location, single table) updates

Types of Client/Server Computing The Gartner Group came out with the five ways of describing the different c/s styles based on how they split the three components of any application: user interface, business or application logic, data management. The five styles are distributed presentation, remote presentation, distributed function, remote data management, and distributed data management. (Note: This is an arbitary classification and others may do it differently).

Page 6: STUDY MATERIAL.doc · Web view... Form, Label, Text box, Command Button, Check Box, Option Button, List Box, Combo Box, Picture Box, Image Controls, Scroll Bars – Drive List Box

6

Types of Client/Server Computing

C/S TypeDistributed Presentation

Remote Presentation

Distributed LogicRemote DataManagement

Distributed Database

Functions on Server Side

Data Mgt.Business LogicUser Interface

Data Mgt.Business Logic

Data Mgt.Business Logic

Data Mgt. Data Mgt.

Network over which the processes communicate

Functions on Client Side

User Interface User InterfaceBusiness LogicUser Interface

Business LogicUser Interface

Data Mgt.Business LogicUser 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

Page 7: STUDY MATERIAL.doc · Web view... Form, Label, Text box, Command Button, Check Box, Option Button, List Box, Combo Box, Picture Box, Image Controls, Scroll Bars – Drive List Box

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.

Client-server architectures are sometimes called two-tier architectures.

Technical Architecture:

Page 8: STUDY MATERIAL.doc · Web view... Form, Label, Text box, Command Button, Check Box, Option Button, List Box, Combo Box, Picture Box, Image Controls, Scroll Bars – Drive List Box

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.

Page 9: STUDY MATERIAL.doc · Web view... Form, Label, Text box, Command Button, Check Box, Option Button, List Box, Combo Box, Picture Box, Image Controls, Scroll Bars – Drive List Box

9

Client Server Application architecture

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.

The service will be a web service

Page 10: STUDY MATERIAL.doc · Web view... Form, Label, Text box, Command Button, Check Box, Option Button, List Box, Combo Box, Picture Box, Image Controls, Scroll Bars – Drive List Box

10

After successful authentication the client application will directly access web service so there will be no overloading on server.

Introduction to 2-Tier Architecture:

2-tier architecture is used to describe client/server systems where the client requests resources and the server responds directly to the request, using its own resources. This means that the server does not call on another application in order to provide part of the service.

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

Database (Data tier)

Client Application (Client tier)

Page 11: STUDY MATERIAL.doc · Web view... Form, Label, Text box, Command Button, Check Box, Option Button, List Box, Combo Box, Picture Box, Image Controls, Scroll Bars – Drive List Box

11

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:

Understanding and maintenances is easier.

Disadvantages:

Performance will be reduced when there are more users.

Page 12: STUDY MATERIAL.doc · Web view... Form, Label, Text box, Command Button, Check Box, Option Button, List Box, Combo Box, Picture Box, Image Controls, Scroll Bars – Drive List Box

12

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

Page 13: STUDY MATERIAL.doc · Web view... Form, Label, Text box, Command Button, Check Box, Option Button, List Box, Combo Box, Picture Box, Image Controls, Scroll Bars – Drive List Box

13

Introduction to 3-Tier Architecture:

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:

Three tier architecture having three layers. They are

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.

Page 14: STUDY MATERIAL.doc · Web view... Form, Label, Text box, Command Button, Check Box, Option Button, List Box, Combo Box, Picture Box, Image Controls, Scroll Bars – Drive List Box

14

Data layer: it has the database.

`

Advantages:

Easy to modify with out affecting other modules

Fast communication

Performance will be good in three tier architecture.

Page 15: STUDY MATERIAL.doc · Web view... Form, Label, Text box, Command Button, Check Box, Option Button, List Box, Combo Box, Picture Box, Image Controls, Scroll Bars – Drive List Box

15

Visual overview of a Three-tiered application

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.

The three-tier model is a software architecture and a software design pattern.

Three-tier architecture has the following three tiers:

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.

Page 16: STUDY MATERIAL.doc · Web view... Form, Label, Text box, Command Button, Check Box, Option Button, List Box, Combo Box, Picture Box, Image Controls, Scroll Bars – Drive List Box

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.

Comparing both types of architecture:

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:

A greater degree of flexibility

Increased security, as security can be defined for each service, and at each level

Increased performance, as tasks are shared between servers

What are the advantages and disadvantages of client-server networking ?

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 :-

Advantages of Client Server Networks :

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.

Page 17: STUDY MATERIAL.doc · Web view... Form, Label, Text box, Command Button, Check Box, Option Button, List Box, Combo Box, Picture Box, Image Controls, Scroll Bars – Drive List Box

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.

8) Servers can play different roles for different clients.

Disadvantages of Client Server Architecture :

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.

3) Cost : It is very expensive to install and manage this type of computing.

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:

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

Page 18: STUDY MATERIAL.doc · Web view... Form, Label, Text box, Command Button, Check Box, Option Button, List Box, Combo Box, Picture Box, Image Controls, Scroll Bars – Drive List Box

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.

Page 19: STUDY MATERIAL.doc · Web view... Form, Label, Text box, Command Button, Check Box, Option Button, List Box, Combo Box, Picture Box, Image Controls, Scroll Bars – Drive List Box

19

Online Transaction Processing (OLTP)

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,

1. Receive a fixed set of inputs from remote clients.2. Perform multiple pre-compiled SQL comments against a local database.3. Commit the work and4. Return a fixed set of results.

The N-tier Architecture :

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 request, what the result will look like, etc; as well as information on how to send that result back to the client.

Page 20: STUDY MATERIAL.doc · Web view... Form, Label, Text box, Command Button, Check Box, Option Button, List Box, Combo Box, Picture Box, Image Controls, Scroll Bars – Drive List Box

20

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").

DIAGRAM FOR N-TIER ARCHITECTURE:

The following sections define each layer of a n-tier architecture in more detail.

Data Access Layer

Page 21: STUDY MATERIAL.doc · Web view... Form, Label, Text box, Command Button, Check Box, Option Button, List Box, Combo Box, Picture Box, Image Controls, Scroll Bars – Drive List Box

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

Business Servicing Layer

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).

The Presentation Layer consists of three major components:

User interface components (forms, buttons, menus, etc.).

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).

Page 22: STUDY MATERIAL.doc · Web view... Form, Label, Text box, Command Button, Check Box, Option Button, List Box, Combo Box, Picture Box, Image Controls, Scroll Bars – Drive List Box

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.

In software engineering, multi-tier architecture (often referred to as n-tier architecture) is a client server architecture in which more than one software agent usually running in different servers does the execution of an application. The reasons for multi-tier architectures are as follows:

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.

Page 23: STUDY MATERIAL.doc · Web view... Form, Label, Text box, Command Button, Check Box, Option Button, List Box, Combo Box, Picture Box, Image Controls, Scroll Bars – Drive List Box

23

Describe a disconnected data access structure:

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.

Page 24: STUDY MATERIAL.doc · Web view... Form, Label, Text box, Command Button, Check Box, Option Button, List Box, Combo Box, Picture Box, Image Controls, Scroll Bars – Drive List Box

24

Page 25: STUDY MATERIAL.doc · Web view... Form, Label, Text box, Command Button, Check Box, Option Button, List Box, Combo Box, Picture Box, Image Controls, Scroll Bars – Drive List Box

25

Difference between 2 or 3 tier architecture and n tier architecture:

Nowadays approach to IT systems architecture is 4-tier.

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.

Page 26: STUDY MATERIAL.doc · Web view... Form, Label, Text box, Command Button, Check Box, Option Button, List Box, Combo Box, Picture Box, Image Controls, Scroll Bars – Drive List Box

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:

Figure 1 The Visual Basic startup dialog box

Overview to the Integrated Development Environment (IDE).

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.

 

Page 27: STUDY MATERIAL.doc · Web view... Form, Label, Text box, Command Button, Check Box, Option Button, List Box, Combo Box, Picture Box, Image Controls, Scroll Bars – Drive List Box

27

Figure-1-1- The Visual Basic Integrated Development Environment

Figure 1.1 The Visual Basic Integrated Development Environment.

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.)

The IDE is composed of these parts:

Page 28: STUDY MATERIAL.doc · Web view... Form, Label, Text box, Command Button, Check Box, Option Button, List Box, Combo Box, Picture Box, Image Controls, Scroll Bars – Drive List Box

28

1. The Menu Bar2. The Toolbar

3. The Project Explorer

4. The Properties Window

5. The Form Layout Window

6. The Toolbox

7. Form Designer

8. Code Window

9. The Immediate Window

1. The Menu Bar

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.

Page 29: STUDY MATERIAL.doc · Web view... Form, Label, Text box, Command Button, Check Box, Option Button, List Box, Combo Box, Picture Box, Image Controls, Scroll Bars – Drive List Box

29

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.

 

Figure-1-2-Main Toolbar

Figure 1.2 The 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.

 

Figure-1-3- Standard Toolbar

Figure 1.3 Standard Toolbar

The Edit toolbar contains the commands of the Edit menu.

 

Page 30: STUDY MATERIAL.doc · Web view... Form, Label, Text box, Command Button, Check Box, Option Button, List Box, Combo Box, Picture Box, Image Controls, Scroll Bars – Drive List Box

30

Figure-1-4- Edit Toolbar

Figure 1.4 Edit Toolbar

The Debug toolbar contains the commands of the Debug menu.

 

Figure-1-5- Debug Toolbar

Figure 1.5 Debug Toolbar.

The Form Editor Toolbar contains the commands of the Format menu.

 

Figure-1-6- Form Editor toolbar

Figure 1.6 Form Editor toolbar

 

Opening and closing of toolbar can be done by choosing View > Toolbar, which then displays a submenu containing the names of the toolbars.

Creating a New Toolbar

To create a new toolbar, follow these steps:

Page 31: STUDY MATERIAL.doc · Web view... Form, Label, Text box, Command Button, Check Box, Option Button, List Box, Combo Box, Picture Box, Image Controls, Scroll Bars – Drive List Box

31

Figure-1-7-TCS Toolbar

a) Open customize dialog box, choose View >Toolbars > Customize.

b) On toolbar tab, click the New Tab.

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 ExplorerDocked 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.

Figure 3 Project Explorer

Page 32: STUDY MATERIAL.doc · Web view... Form, Label, Text box, Command Button, Check Box, Option Button, List Box, Combo Box, Picture Box, Image Controls, Scroll Bars – Drive List Box

32

Properties Window4. The Properties Window.

Figure-1-9-The-Properties-Window

Page 33: STUDY MATERIAL.doc · Web view... Form, Label, Text box, Command Button, Check Box, Option Button, List Box, Combo Box, Picture Box, Image Controls, Scroll Bars – Drive List Box

33

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).

ToolboxThe 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.

Figure 2 Toolbox window with its controls available commonly.

Page 34: STUDY MATERIAL.doc · Web view... Form, Label, Text box, Command Button, Check Box, Option Button, List Box, Combo Box, Picture Box, Image Controls, Scroll Bars – Drive List Box

34

Control Description

Pointer Provides a way to move and resize the controls form

PictureBox Displays icons/bitmaps and metafiles. It displays text or acts as a visual container for other controls.

TextBox Used to display message and enter text.

Frame Serves as a visual and functional container for controls

CommandButton Used to carry out the specified action when the user chooses it.

CheckBox Displays a True/False or Yes/No option.

OptionButton OptionButton control which is a part of an option group allows the user to select only one option even it displays mulitiple choices.

ListBox Displays a list of items from which a user can select one.

ComboBox Contains a TextBox and a ListBox. This allows the user to select an ietm from the dropdown ListBox, or to type in a selection in the TextBox.

HScrollBar and VScrollBar

These controls allow the user to select a value within the specified range of values

Page 35: STUDY MATERIAL.doc · Web view... Form, Label, Text box, Command Button, Check Box, Option Button, List Box, Combo Box, Picture Box, Image Controls, Scroll Bars – Drive List Box

35

Timer Executes the timer events at specified intervals of time

DriveListBox Displays the valid disk drives and allows the user to select one of them.

DirListBox Allows the user to select the directories and paths, which are displayed.

FileListBox Displays a set of files from which a user can select the desired one.

Shape Used to add shape (rectangle, square or circle) to a Form

Line Used to draw straight line to the Form

Image used to display images such as icons, bitmaps and metafiles. But less capability than the PictureBox

Data Enables the use to connect to an existing database and display information from it.

OLE Used to link or embed an object, display and manipulate data from other windows based applications.

Label Displays a text that the user cannot modify or interact with.

 Visual Basic 6.0 - Properties, Methods and EventsAll the controls in the ToolBox except the Pointer are objects in Visual Basic. These objects have associated properties, methods and events.

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 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.

Page 36: STUDY MATERIAL.doc · Web view... Form, Label, Text box, Command Button, Check Box, Option Button, List Box, Combo Box, Picture Box, Image Controls, Scroll Bars – Drive List Box

36

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.

Similarly in object-oriented programming, a method is a connected or built-in procedure, a block of code that can be invoked to impart some action on a particular object. A method requires an object to provide them with a context. For example, the word Move has no meaning in Visual Basic, but the statement,

Text1.Move 700, 400

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.

What Are Properties, Methods, and Events?Put simply, properties describe objects. Methods cause an object to do something. Events are what happens when an object does something.

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.

TABLE 6.1  Common Properties of Visual Basic Controls

Property Description

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

Height A control's height

Width A control's width

Name The string value used to refer to a control

Enabled The Boolean (True/False) value that determines whether users can manipulate the control

Page 37: STUDY MATERIAL.doc · Web view... Form, Label, Text box, Command Button, Check Box, Option Button, List Box, Combo Box, Picture Box, Image Controls, Scroll Bars – Drive List Box

37

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.

TABLE 6.2  The Six Settings of the BorderStyle Property

Setting Description

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 (default)

Sizable by dragging borders and by using Maximize and Minimize buttons. Use this for typical programs.

3-Fixed Dialog Not sizable and no Maximize/Minimize buttons. Use this for simple forms such as a password dialog.

4-Fixed ToolWindow

Similar to 3-Fixed Dialog except that the title bar is shorter and the title bar font and Close button are correspondingly smaller. Use this for floating toolbars.

5-Sizable ToolWindow

Similar to a 4-Fixed ToolWindow except that it's sizable by dragging the border. Use 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.

TABLE 6.3  Common Methods of Visual Basic Controls

Method Use

Move Changes an object's position in response to a code request

Page 38: STUDY MATERIAL.doc · Web view... Form, Label, Text box, Command Button, Check Box, Option Button, List Box, Combo Box, Picture Box, Image Controls, Scroll Bars – Drive List Box

38

Drag Handles the execution of a drag-and-drop operation by the user

SetFocus Gives focus to the object specified in the method call

ZOrder Determines the order in which multiple objects appear onscreen

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.

Using GotFocus and LostFocus

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.

TABLE 6.4  Common Events of Visual Basic Controls

Event Occurrence

Change The user modifies text in a combo box or text box.

Click The user clicks the primary mouse button on an object.

DblClick The user double-clicks the primary mouse button on an object.

DragDrop The user drags an object to another location.

Page 39: STUDY MATERIAL.doc · Web view... Form, Label, Text box, Command Button, Check Box, Option Button, List Box, Combo Box, Picture Box, Image Controls, Scroll Bars – Drive List Box

39

DragOver The user drags an object over another control.

GotFocus An object receives focus.

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

LostFocus An object loses focus.

MouseDown The user presses any mouse button while the mouse pointer is over an object.

MouseMove The user moves the mouse pointer over an object.

MouseUp The user releases any mouse button while the mouse pointer is over an object.

The Relationship Between Properties, Methods, and Events

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.

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 = 100cmdMove.Top = 100`********************************************`Move the commandbutton by using the Move method`********************************************txtMove.Move 100, 100

Page 40: STUDY MATERIAL.doc · Web view... Form, Label, Text box, Command Button, Check Box, Option Button, List Box, Combo Box, Picture Box, Image Controls, Scroll Bars – Drive List Box

40

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

Event Driven ProgrammingVisual Basic programs are built around events. Events are various things that can happen in a program. this will become clearer when studied in contrast to procedural programming.

In procedural languages, an application is written is executed by checking for the program logically through the program statements, one after another.

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, 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.

The Importance of Event-Driven Programming

Page 41: STUDY MATERIAL.doc · Web view... Form, Label, Text box, Command Button, Check Box, Option Button, List Box, Combo Box, Picture Box, Image Controls, Scroll Bars – Drive List Box

41

Event-driven programming means that most of the code write will be run as users do things within the program or even when certain things happen in Windows--when events occur.

Of course, programming this way means that have to know when events occur and have to write code that will make your program do something in response to the event.

Whenever an event takes place, Windows sends out a message to your program. Your program reads this message, and then runs the code you've attached to the event. If you don't specify code for an event, your program will simply ignore the event.

Generally, this code is known as a procedure, defined as any block of code that can be called from within your application.

This code might be used to move objects around on a form, calculate a value from a formula, or write data to a database. No matter the purpose, a procedure always uses this format:

[Public|Private] [Static] Sub|Function|Property _ function_name (arguments) [As Type]{...Your procedure code...}End Sub|Function|Property

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:

Double-clicking the object Selecting the object with the mouse and pressing F7

Selecting the object and choosing Code from the View menu

Selecting the object's form in the Project Explorer, clicking the View Code button, and choosing the object from the Code window

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 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.

Using Properties, Methods, and Events in a Sample ProgramProperties, methods, and events in an application named MoveIt.

The MoveIt program can be moved around onscreen when users click the buttons on its interface.

Page 42: STUDY MATERIAL.doc · Web view... Form, Label, Text box, Command Button, Check Box, Option Button, List Box, Combo Box, Picture Box, Image Controls, Scroll Bars – Drive List Box

42

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.

Create MoveIt (general steps)

1. Create the graphical user interface (GUI).

2. Program the Form_Load() event procedure.

3. Program the Click() event procedures.

4. Add the event notification.

Creating the Interface

Create MoveIt's GUI

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.

Programming the Form_Load() Event Procedure

Use the Form_Load() event procedure to prepare the form before showing it onscreen when program is run. Use this procedure to

Set the Caption property of the CommandButtons Set the initial text of the label

Set the form's title bar text

Set the position of the four CommandButtons, the label, and the form onscreen

Page 43: STUDY MATERIAL.doc · Web view... Form, Label, Text box, Command Button, Check Box, Option Button, List Box, Combo Box, Picture Box, Image Controls, Scroll Bars – Drive List Box

43

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.

LISTING 6.1  The Form_Load() Event Procedure Code for MoveIt01 `Set the Caption property of the CommandButtons02 cmdTopLeft.Caption = "Top Left"03 cmdTopRight.Caption = "Top Right"04 cmdBottomLeft.Caption = "Bottom Left"05 cmdBottomRight.Caption = "Bottom Right"0607 `Clear the initial text of the label08 lblNotify.Caption = ""0910 `Set the form's title bar text11 frmMove.Caption = "MoveIt"1213 `The rest of the code centers the form on the14 `screen, sets the position of the four15 `CommandButtons, and sets the size and16 `position of the label.1718 `Center the form on the screen. This works by19 `setting the Left side of the form to the center20 `of the screen, less half the width of the form.21 `Also, the Top of the form is set to the center22 `of the screen, less half the height of the form.23 frmMove.Left = (Screen.Width - frmMove.Width) / 224 frmMove.Top = (Screen.Height - frmMove.Height) / 22526 `Set the Left edge of the buttons. The 200 setting27 `for the left buttons sets a space between the edge28 `of the form and the buttons. The right buttons are29 `set by subtracting the width of the button from30 `the width of the form, and subtracting 300 to31 `set a space between the button and the form edge.32 cmdTopLeft.Left = 20033 cmdBottomLeft.Left = 20034 cmdTopRight.Left = frmMove.Width - cmdTopRight.Width - 30035 cmdBottomRight.Left = frmMove.Width - cmdBottomRight.Width - 3003637 `Set the Top edge of the buttons. This is done38 `similar to setting the Left edge.39 cmdTopLeft.Top = 20040 cmdBottomLeft.Top = frmMove.Height - cmdBottomLeft.Height - 50041 cmdTopRight.Top = 20042 cmdBottomRight.Top = frmMove.Height - cmdBottomRight.Height - 5004344 `Set the size of the label45 lblNotify.Height = 36046 lblNotify.Width = 30004748 `Center the label within the form. This is done

Page 44: STUDY MATERIAL.doc · Web view... Form, Label, Text box, Command Button, Check Box, Option Button, List Box, Combo Box, Picture Box, Image Controls, Scroll Bars – Drive List Box

44

49 `similar to centering the form.50 lblNotify.Left = (frmMove.Width - lblNotify.Width) / 251 lblNotify.Top = (frmMove.Height - lblNotify.Height) / 2 - 200

Setting these starting values is called initialization.

Programming the Click() Event

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.

LISTING 6.2  The Click() Event Procedures for the CommandButtons01 Private Sub cmdBottomLeft_Click()0203 `Set the value of the form's TOP property04 `to the bottom of the screen but bring05 `it up the height of the screen so that the06 `bottom of the form is on the bottom of07 `the screen08 frmMove.Top = Screen.Height - frmMove.Height0910 `Set the value of the form's LEFT property11 `to the far left of the screen.12 frmMove.Left = 01314 End Sub1516 Private Sub cmdBottomRight_Click()1718 `Set the value for the form's TOP property to19 `the bottom of the screen, but bring the TOP20 `up the HEIGHT of the form so that the bottom21 `of the form is on the bottom of the screen.22 frmMove.Top = Screen.Height - frmMove.Height2324 `Set the value of the form's LEFT property to25 `the right of the screen but bring it across26 `the screen the width of the form so that the27 `right side of the form is on the right28 `side of the screen29 frmMove.Left = Screen.Width - frmMove.Width3031 End Sub3233 Private Sub cmdTopLeft_Click()3435 `Set the value of the form's TOP property36 `to the top of the screen.37 frmMove.Top = 03839 `Set the value of the form's LEFT property

Page 45: STUDY MATERIAL.doc · Web view... Form, Label, Text box, Command Button, Check Box, Option Button, List Box, Combo Box, Picture Box, Image Controls, Scroll Bars – Drive List Box

45

40 `to the left of the screen.41 frmMove.Left = 04243 End Sub4445 Private Sub cmdTopRight_Click()4647 `Set the value of the form's TOP property48 `to the top of the screen.49 frmMove.Top = 05051 `Set the value of the form's LEFT property to52 `the right of the screen but bring it back across53 `the screen the width of the form, so that the54 `right side of the form is on the right55 `side of the screen56 frmMove.Left = Screen.Width - frmMove.Width5758 End Sub

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.

Adding Event Notification

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 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.

Page 46: STUDY MATERIAL.doc · Web view... Form, Label, Text box, Command Button, Check Box, Option Button, List Box, Combo Box, Picture Box, Image Controls, Scroll Bars – Drive List Box

46

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 Button01 Private Sub Form_MouseDown(Button As Integer, _Shift As Integer, X As Single, Y As Single)0203 lblNotify.Caption = "MouseDown Event"0405 End Sub0607 Private Sub Form_MouseUp(Button As Integer, Shift As Integer, X As Single, Y As Single)0809 lblNotify.Caption = "MouseUp Event"1011 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 Focus01 Private Sub cmdBottomLeft_GotFocus()0203 lblNotify.Caption = "cmdBottomLeft has the Focus"0405 End Sub0607 Private Sub cmdBottomRight_GotFocus()0809 lblNotify.Caption = "cmdBottomRight has the Focus"1011 End Sub1213 Private Sub cmdTopLeft_GotFocus()1415 lblNotify.Caption = "cmdTopLeft has the Focus"1617 End Sub1819 Private Sub cmdTopRight_GotFocus()2021 lblNotify.Caption = "cmdTopRight has the Focus"2223 End Sub

Page 47: STUDY MATERIAL.doc · Web view... Form, Label, Text box, Command Button, Check Box, Option Button, List Box, Combo Box, Picture Box, Image Controls, Scroll Bars – Drive List Box

47

Working with Forms in Visual Basic The main characteristic of a Form is the title bar on which the Form's caption is displayed. On the left end of the title bar is the Control Menu icon. Clicking this icon opens the Control Menu. Maximize, Minimize and Close buttons can be found on the right side of the Form. Clicking on these buttons performs the associated function.

The following figure illustrates the appearance of a Form

The control menu contains the following commands :

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

Setting the Start-Up Form

A typical application has more than a single Form. When an application runs the main Form is loaded. By setting the Project properties you can control which Form is to be displayed in the Start-Up of the application. Following figure illustrates the Project property window.

Page 48: STUDY MATERIAL.doc · Web view... Form, Label, Text box, Command Button, Check Box, Option Button, List Box, Combo Box, Picture Box, Image Controls, Scroll Bars – Drive List Box

48

By default, Visual Basic suggests the name of the first Form created when the project started.

Loading and Unloading Forms

In order to load and unload the forms, Load and Unload statements are used. The Load statement has the following syntax :

Load FormName

And the Unload statement has the following syntax :

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.

Showing and Hiding Forms

Show method is used to Show a Form. If the Form is loaded but invisible, the Show method is used to bring the Form on Top every other window. If the Form is not loaded, the Show method loads it and then displays it.

Syntax of the Show method of the Form

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.

Page 49: STUDY MATERIAL.doc · Web view... Form, Label, Text box, Command Button, Check Box, Option Button, List Box, Combo Box, Picture Box, Image Controls, Scroll Bars – Drive List Box

49

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

* Open a new Project and save the Project

Design the application as shown below

Object Property Setting

FormCaption

Name

Form1

frm1

FormCaption

Name

Form2

frm2

FormCaption

Name

Form3

frm3

LabelCaption

Name

Click on a button to display a Form

Label1

Page 50: STUDY MATERIAL.doc · Web view... Form, Label, Text box, Command Button, Check Box, Option Button, List Box, Combo Box, Picture Box, Image Controls, Scroll Bars – Drive List Box

50

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.

Finding out the difference between Unload and Hide method

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.

In the click event of the Hide button Following code is entered.

Me.Hide

In the click event of the Unload button following code is entered.

Unload Me

Page 51: STUDY MATERIAL.doc · Web view... Form, Label, Text box, Command Button, Check Box, Option Button, List Box, Combo Box, Picture Box, Image Controls, Scroll Bars – Drive List Box

51

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 variable [As Type]

Dim I as integer

Dim intInterestRate As Integer = 10

Scope of variables

A variable is scoped to a procedure-level (local) or module-level variable depending on how it is declared. The scope of a variable, procedure or object determines which part of the code in our application are aware of the variable's existence. A variable is declared in general declaration section of e Form, and hence is available to all the procedures. Local variables are recognized only in the procedure in which they are declared. They can be declared with Dim and Static keywords. If we want a variable to be available to all of the procedures within the same module, or to all the procedures in an application, a variable is declared with broader scope.

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.

Dim sum As Integer

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.

Page 52: STUDY MATERIAL.doc · Web view... Form, Label, Text box, Command Button, Check Box, Option Button, List Box, Combo Box, Picture Box, Image Controls, Scroll Bars – Drive List Box

52

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.

Static intPermanent As Integer

Variables have a lifetime in addition to scope. The values in a module-level and public variables are preserved for the lifetime of an application whereas local variables declared with Dim exist only while the procedure in which they are declared is still being executed. The value of a local variable can be preserved using the Static keyword. The follwoing procedure calculates the running total by adding new values to the previous values stored in the static variable value.

Function RunningTotal ( )

Static Accumulate

Accumulate = Accumulate + num

RunningTotal = Accumulate

End Function

If the variable Accumulate was declared with Dim instead of static, the previously accumulated values would not be preserved accross calls to the procedure, and the procedure would return the 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.

Static Function RunningTotal ( )

Example

The following is an example of an event procedure for a CommandButton that counts and displays the number of clicks made.

Private Sub Command1_Click ( )

Static Counter As Integer

Counter = Counter + 1

Page 53: STUDY MATERIAL.doc · Web view... Form, Label, Text box, Command Button, Check Box, Option Button, List Box, Combo Box, Picture Box, Image Controls, Scroll Bars – Drive List Box

53

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.

Module Levele Variables

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:

' In the declarative section of any module

Private LoginTime As Date ' A private module-level variable

Dim LoginPassword As String ' Another private module-level variable

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:

' In the declarative section of Form1 module

Public CustomerName As String ' A Public property

You can access a module property as a regular variable from inside the module and as a custom property from the outside:

' From outside Form1 module...

Form1.CustomerName = "John Smith"

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-

Page 54: STUDY MATERIAL.doc · Web view... Form, Label, Text box, Command Button, Check Box, Option Button, List Box, Combo Box, Picture Box, Image Controls, Scroll Bars – Drive List Box

54

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).

Public vs Local 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.

Public Const gravityconstant As Single = 9.81

Compile-time and Run-time Constants

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:

Public Const DaysInYear = 365

Private Const WorkDays = 250

DATATYPES

5.1 Visual Basic Data Types

Visual Basic classifies the information mentioned above into two major data types, they are the numeric data types and the non-numeric data types.

Page 55: STUDY MATERIAL.doc · Web view... Form, Label, Text box, Command Button, Check Box, Option Button, List Box, Combo Box, Picture Box, Image Controls, Scroll Bars – Drive List Box

55

5.1.1 Numeric Data Types

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

Table 5.1: Numeric Data Types

Type Storage Range of Values

Byte 1 byte 0 to 255

Integer 2 bytes -32,768 to 32,767

Long 4 bytes -2,147,483,648 to 2,147,483,648

Single 4 bytes -3.402823E+38 to -1.401298E-45 for negative values

1.401298E-45 to 3.402823E+38 for positive values.

Double 8 bytes

-1.79769313486232e+308 to -4.94065645841247E-324 for negative values

4.94065645841247E-324 to 1.79769313486232e+308 for positive values.

Currency 8 bytes -922,337,203,685,477.5808 to 922,337,203,685,477.5807

Decimal 12 bytes +/- 79,228,162,514,264,337,593,543,950,335 if no decimal is use

+/- 7.9228162514264337593543950335 (28 decimal places).

Page 56: STUDY MATERIAL.doc · Web view... Form, Label, Text box, Command Button, Check Box, Option Button, List Box, Combo Box, Picture Box, Image Controls, Scroll Bars – Drive List Box

56

5.1.2 Non-numeric Data Types

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

Table 5.2: Nonnumeric Data Types

Data Type Storage Range

String(fixed length) Length of string 1 to 65,400 characters

String(variable length) Length + 10 bytes 0 to 2 billion characters

Date 8 bytes January 1, 100 to December 31, 9999

Boolean 2 bytes True or False

Object 4 bytes Any embedded object

Variant(numeric) 16 bytes Any value as large as Double

Variant(text) Length+22 bytes Same as variable-length string

5.1.3 Suffixes for Literals

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

Suffix Data Type

& Long

! Single

# Double

@ Currency

Page 57: STUDY MATERIAL.doc · Web view... Form, Label, Text box, Command Button, Check Box, Option Button, List Box, Combo Box, Picture Box, Image Controls, Scroll Bars – Drive List Box

57

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#

Page 58: STUDY MATERIAL.doc · Web view... Form, Label, Text box, Command Button, Check Box, Option Button, List Box, Combo Box, Picture Box, Image Controls, Scroll Bars – Drive List Box

58

Unit – III

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

Procedures in Visual Basic

Visual Basic offers different types of procedures to execute small sections of coding in applications.

The various procedures are elucidated in details in this section. Visual Basic programs can be broken into smaller logical components called Procedures.

Procedures are useful for condensing repeated operations such as the frequently used calculations, text and control manipulation etc.

The benefits of using procedures in programming are:

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:

[Private | Public] [Static] Sub Procedurename [( arglist)]

[ 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.

Private Sub Form_Load()

Page 59: STUDY MATERIAL.doc · Web view... Form, Label, Text box, Command Button, Check Box, Option Button, List Box, Combo Box, Picture Box, Image Controls, Scroll Bars – Drive List Box

59

....statement block..

End Sub

Event Procedures acquire the declarations as Private by default.

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.

Function Hypotenuse (A As Double, B As Double) As Double

Hypotenuse = sqr (A^2 + B^2)

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

A property procedure is used to create and manipulate custom properties. It is used to create read only properties for Forms, Standard modules and Class modules.Visual Basic provides three kind of property procedures-Property Let procedure that sets the value of a property, Property Get procedure that returns the value of a property, and Property Set procedure that sets the references to an object.

Defining procedures

An example function definition:

Public Function Sum(ByRef Number1 As Double, ByRef Number2 As Double) As Double

'Return the result by writing it to a variable having the same name as the function

Sum = Number1 + Number2

End Function

Page 60: STUDY MATERIAL.doc · Web view... Form, Label, Text box, Command Button, Check Box, Option Button, List Box, Combo Box, Picture Box, Image Controls, Scroll Bars – Drive List Box

60

An example subroutine definition:

Public Sub Tell(ByVal MyString1 as String, ByVal MyString2 as String)

MsgBox MyString1 & MyString2

End Sub

Note the following:

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, argument order matters

Tell "Hello there.", ""

'On the next line, names of arguments are used and argument order does not matter.

Tell MyString1:="Hello there,", MyString2:=" again."

'Tell ("Hello there.","") -- syntax error

MySum = Sum(123.456, 234)

MySum2 = Sum(Number2:=8, Number1:=6)

'MySum3 = Sum Number2:=8, Number1:=6 -- syntax error

Note the following:

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.

If...Then selection structure:

Page 61: STUDY MATERIAL.doc · Web view... Form, Label, Text box, Command Button, Check Box, Option Button, List Box, Combo Box, Picture Box, Image Controls, Scroll Bars – Drive List Box

61

The If...Then selection structure performs an indicated action only when the condition is True; otherwise the action is skipped.

Syntax of the If...Then selection

If <condition> Then

statement

End If

e.g.: If average>75 Then

txtGrade.Text = "A"

End If

If...Then...Else selection structure:

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.

Syntax of the If...Then...Else selection

If <condition > Then

statements

Else

statements

End If

e.g.: If average>50 Then

txtGrade.Text = "Pass"

Else

txtGrade.Text = "Fail"

End If

Nested If...Then...Else selection structure:

Page 62: STUDY MATERIAL.doc · Web view... Form, Label, Text box, Command Button, Check Box, Option Button, List Box, Combo Box, Picture Box, Image Controls, Scroll Bars – Drive List Box

62

Nested If...Then...Else selection structures test for multiple cases by placing If...Then...Else selection structures inside If...Then...Else structures.

Syntax of the Nested If...Then...Else selection structure

You can use Nested If either of the methods as shown above

Method 1:

If < condition 1 > Then

statements

ElseIf < condition 2 > Then

statements

ElseIf < condition 3 > Then

statements

Else

Statements

End If

Method 2:

If < condition 1 > Then

statements

Else

If < condition 2 > Then

statements

Else

If < condition 3 > Then

statements

Else

Page 63: STUDY MATERIAL.doc · Web view... Form, Label, Text box, Command Button, Check Box, Option Button, List Box, Combo Box, Picture Box, Image Controls, Scroll Bars – Drive List Box

63

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

If average > 75 Then

txtGrade.Text = "A"

ElseIf average > 65 Then

txtGrade.Text = "B"

ElseIf average > 55 Then

txtGrade.text = "C"

ElseIf average > 45 Then

txtGrade.Text = "S"

Else

txtGrade.Text = "F"

End If

Select...Case selection structure:

Select...Case structure is an alternative to If...Then...ElseIf for selectively executing a single block of statements from among multiple block of statements. Select...case is more convenient to use than the If...Else...End If. The following program block illustrate the working of Select...Case.

Syntax of the Select...Case selection structure:

Select Case Index

Case 0

Statements

Page 64: STUDY MATERIAL.doc · Web view... Form, Label, Text box, Command Button, Check Box, Option Button, List Box, Combo Box, Picture Box, Image Controls, Scroll Bars – Drive List Box

64

Case 1

Statements

End Select

e.g.: Assume you have to find the grade using select...case and display in the text box

Dim average as Integer

average = txtAverage.Text

Select Case average

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

MsgBox "Invalid average marks"

End Select

LOOPS (REPETITION STRUCTURES):

The For...Next Loop:

` 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:

Page 65: STUDY MATERIAL.doc · Web view... Form, Label, Text box, Command Button, Check Box, Option Button, List Box, Combo Box, Picture Box, Image Controls, Scroll Bars – Drive List Box

65

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 following loop counts numbers as 1, 3, 5, 7..etc

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

Print x & Space$ (2);

Next

To increase the space between the numbers increase the value inside the brackets after the & Space$.

Following example is a For...Next repetition structure which is with the If condition used.

Dim number As Integer

For number = 1 To 10

If number = 4 Then

Print "This is number 4"

Else

Print number

End If

Next

Page 66: STUDY MATERIAL.doc · Web view... Form, Label, Text box, Command Button, Check Box, Option Button, List Box, Combo Box, Picture Box, Image Controls, Scroll Bars – Drive List Box

66

In the output instead of number 4 you will get the "This is number 4".

While Repetition Structure:A repetition structure allows the programmer to specify that an action

be repeated a numberof times, depending on the value of a condition. Visual Basic .NET provides seven repetitionstructures—one of which is the While repetition structure.

As an example of a While structure, consider a program segment designed to find thefirst power of two larger than 1000. Suppose Integer variable product contains thevalue 2. When the following While structure finishes executing, product contains the result:Dim product As Integer = 2While product <= 1000product = product * 2End While

Do While/Loop Repetition Structure:The Do While/Loop repetition structure behaves like the While repetition structure. As

an example of a Do While/Loop structure, consider another version of the segment designed

to find the first power of two larger than 1000:

Dim product As Integer = 2

Do While product <= 1000

product = product * 2

Loop

Do Until/Loop Repetition Structure:Unlike the While and Do While/Loop repetition structures, the Do Until/Loop repetition

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

Page 67: STUDY MATERIAL.doc · Web view... Form, Label, Text box, Command Button, Check Box, Option Button, List Box, Combo Box, Picture Box, Image Controls, Scroll Bars – Drive List Box

67

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:

Dim product As Integer = 2

Do Until product >= 1000

product = product * 2

Loop

Do/Loop While Repetition Structure:The Do/Loop While repetition structure is similar to the While and Do While/Loop

structures. In the While and Do While/Loop structures, the loop-continuation condition

is tested at the beginning of the loop, before the body of the loop always is performed. The

Do/Loop While structure tests the loop-continuation condition after the body of the loop

is performed. Therefore, in a Do/Loop While structure, the body of the loop is always executed

at least once. When a Do/Loop While structure terminates, execution continues

with the statement after the Loop While clause. As an example of a Do/Loop While

repetition structure, once again consider the segment designed to find the first power of two

larger than 1000:

Dim product As Integer = 1Doproduct = product * 2Loop While produce <= 1000

Do/Loop Until Repetition Structure

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:

Dim product As Integer = 1

Do

Page 68: STUDY MATERIAL.doc · Web view... Form, Label, Text box, Command Button, Check Box, Option Button, List Box, Combo Box, Picture Box, Image Controls, Scroll Bars – Drive List Box

68

product = product * 2

Loop Until product >= 1000

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

Student Name Name(1) Name(2) Name(3) Name(4) Name(5)

Table 16.2 Two Dimensional ArrayName(1,1) Name(1,2) Name(1,3) Name(1,4)Name(2,1) Name(2,2) Name(2,3) Name(2,4)

Declaring Arrays

Page 69: STUDY MATERIAL.doc · Web view... Form, Label, Text box, Command Button, Check Box, Option Button, List Box, Combo Box, Picture Box, Image Controls, Scroll Bars – Drive List Box

69

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.

The general format to declare a one dimensional array is as follow:

Dim arrayName(subs) as dataType

Where subs indicates the last subscript in the array.Example 16.1

Dim CusName(10) as String

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

Dim numbers(5) As Integer

In the above illustration, numbers is the name of the array, and the number 6 included in the parentheses is the upper limit of the array. The above declaration creates an array with 6 elements, with index numbers running from 0 to 5.

If we want to specify the lower limit, then the parentheses should include both the lower and upper limit along with the To keyword. An example for this is given below.

Dim numbers (1 To 6 ) As Integer

In the above statement, an array of 10 elements is declared but with indexes running from 1 to 6.

A public array can be declared using the keyword Public instead of Dim as shown below.

Public numbers(5) As Integer Multidimensional Arrays

Arrays can have multiple dimensions. A common use of multidimensional arrays is to represent tables of values consisting of information arranged in rows and columns. To identify a particular table element, we must specify two indexes: The first (by convention) identifies the element's row and the second (by convention) identifies the element's column.

Tables or arrays that require two indexes to identify a particular element are called two dimensional arrays. Note that multidimensional arrays can have more than two dimensions.

Page 70: STUDY MATERIAL.doc · Web view... Form, Label, Text box, Command Button, Check Box, Option Button, List Box, Combo Box, Picture Box, Image Controls, Scroll Bars – Drive List Box

70

Visual Basic supports at least 60 array dimensions, but most people will need to use more than two or three dimensional-arrays.

The following statement declares a two-dimensional array 50 by 50 array within a procedure.

Dim AvgMarks ( 50, 50)

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

Dim Marks ( 101 To 200, 1 To 100)

An example for three dimensional-array with defined lower limits is given below.

Dim Details( 101 To 200, 1 To 100, 1 To 100)

Static and dynamic arrays:

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:

' This is a static array. Dim Names(100) As String

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:

' An array defined in a BAS module (with Private scope) Dim Customers() As String

USER-DEFINED DATA TYPE:

Variables of different data types when combined as a single variable to hold several related informations is called a User-Defined data type.

Page 71: STUDY MATERIAL.doc · Web view... Form, Label, Text box, Command Button, Check Box, Option Button, List Box, Combo Box, Picture Box, Image Controls, Scroll Bars – Drive List Box

71

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.

Dim ElectronicGoods as ProductDetails ' One Record Dim ElectronicGoods(10) as ProductDetails ' An array of 11 records

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

If the same is implemented as an array, then the statement becomes

Text1.Text = ElectronicGoods(i).ProdName

User-defined data types can also be passed to procedures to allow many related items as one argument.

Sub ProdData( ElectronicGoods as ProductDetails) Text1.Text = ElectronicGoods.ProdName Text1.Text = ElectronicGoods.Price End Sub

Data Type Conversion:

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 FunctionFunction nameReturn data typeRange for expression argument

Page 72: STUDY MATERIAL.doc · Web view... Form, Label, Text box, Command Button, Check Box, Option Button, List Box, Combo Box, Picture Box, Image Controls, Scroll Bars – Drive List Box

72

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.

CDbl Double Data Type (Visual Basic) -1.79769313486231570E+308 through -4.94065645841246544E-324 for negative values; 4.94065645841246544E-324 through 1.79769313486231570E+308 for positive values.

CDec Decimal Data Type (Visual Basic) +/-79,228,162,514,264,337,593,543,950,335 for zero-scaled numbers, that is, numbers with no decimal places. For numbers with 28 decimal places, the range is +/-7.9228162514264337593543950335. The smallest possible non-zero number is 0.0000000000000000000000000001 (+/-1E-28).

CInt Integer Data Type (Visual Basic) -2,147,483,648 through 2,147,483,647; fractional parts are rounded.1

CLng Long Data Type (Visual Basic) -9,223,372,036,854,775,808 through 9,223,372,036,854,775,807; fractional parts are rounded.1

CObj Object Data Type Any valid expression.

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

CULng ULong Data Type (Visual Basic) 0 through 18,446,744,073,709,551,615 (unsigned); fractional parts are rounded.1

Page 73: STUDY MATERIAL.doc · Web view... Form, Label, Text box, Command Button, Check Box, Option Button, List Box, Combo Box, Picture Box, Image Controls, Scroll Bars – Drive List Box

73

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.VBDim a, b, c As Integer Dim check As Booleana = 5b = 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.VBDim aDouble As Double Dim aByte As ByteaDouble = 125.5678' The following line of code sets aByte to 126.aByte = CByte(aDouble)CChar Example

The following example uses the CChar function to convert the first character of a String expression to a Char type.

Page 74: STUDY MATERIAL.doc · Web view... Form, Label, Text box, Command Button, Check Box, Option Button, List Box, Combo Box, Picture Box, Image Controls, Scroll Bars – Drive List Box

74

VBDim 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.VBDim someDigits As String Dim codePoint As Integer Dim thisChar As CharsomeDigits = 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.VBDim aDateString, aTimeString As String Dim aDate, aTime As DateaDateString = "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 ExampleVBDim 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

The following example uses the CDec function to convert a numeric value to Decimal.

Page 75: STUDY MATERIAL.doc · Web view... Form, Label, Text box, Command Button, Check Box, Option Button, List Box, Combo Box, Picture Box, Image Controls, Scroll Bars – Drive List Box

75

VBDim aDouble As Double Dim aDecimal As DecimalaDouble = 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.VBDim aDbl As Double Dim anInt As IntegeraDbl = 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.VBDim aDbl1, aDbl2 As Double Dim aLng1, aLng2 As LongaDbl1 = 25427.45aDbl2 = 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.VBDim aDouble As Double Dim anObject As ObjectaDouble = 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.VBDim aDouble As Double Dim anSByte As SByteaDouble = 39.501' The following line of code sets anSByte to 40.

Page 76: STUDY MATERIAL.doc · Web view... Form, Label, Text box, Command Button, Check Box, Option Button, List Box, Combo Box, Picture Box, Image Controls, Scroll Bars – Drive List Box

76

anSByte = CSByte(aDouble)CShort Example

The following example uses the CShort function to convert a numeric value to Short.VBDim aByte As Byte Dim aShort As ShortaByte = 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.VBDim aDouble1, aDouble2 As Double Dim aSingle1, aSingle2 As SingleaDouble1 = 75.3421105aDouble2 = 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.VBDim aDouble As Double Dim aString As StringaDouble = 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.VBDim 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)' The following line of code sets the time component of aDate to one second past midnight.aDate = #2/12/1969 12:00:01 AM#

Page 77: STUDY MATERIAL.doc · Web view... Form, Label, Text box, Command Button, Check Box, Option Button, List Box, Combo Box, Picture Box, Image Controls, Scroll Bars – Drive List Box

77

' 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.VBDim aDouble As Double Dim aUInteger As UIntegeraDouble = 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.VBDim aDouble As Double Dim aULong As ULongaDouble = 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.VBDim aDouble As Double Dim aUShort As UShortaDouble = 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.

We have several types of operators: Arithmetic operators

Page 78: STUDY MATERIAL.doc · Web view... Form, Label, Text box, Command Button, Check Box, Option Button, List Box, Combo Box, Picture Box, Image Controls, Scroll Bars – Drive List Box

78

Boolean operatorsRelational operatorsBitwise operators

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:

Page 79: STUDY MATERIAL.doc · Web view... Form, Label, Text box, Command Button, Check Box, Option Button, List Box, Combo Box, Picture Box, Image Controls, Scroll Bars – Drive List Box

79

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 = 1Console.WriteLine(x) ' Prints 1

Here we assign a number to the x variable. x = x + 1Console.WriteLine(x)

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()

Console.WriteLine("Return " & "of " & "the king") Console.WriteLine("Return " + "of " + "the king")

End Sub

End Module

We join three strings together using both operators. $ ./concatstrings.exe Return of the kingReturn of the king

And this is, what we get. Same result for both cases.

Bitwise operators

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

Page 80: STUDY MATERIAL.doc · Web view... Form, Label, Text box, Command Button, Check Box, Option Button, List Box, Combo Box, Picture Box, Image Controls, Scroll Bars – Drive List Box

80

with bits of a binary number. Bitwise operators are seldom used in higher level languages like Visual Basic. Symbol Meaning

Not bitwise negationXor bitwise exclusive orAnd bitwise andOr bitwise or

The bitwise negation operator changes each 1 to 0 and 0 to 1. Console.WriteLine(Not 7) ' Prints -8Console.WriteLine(Not -8) ' Prints 7

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.

What is the outcome of the following expression? 28 or 40? 3 + 5 * 5

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 divisionMod modulus+ - addition, subtraction, string concatenation& string concatenation<< >> arithmetic bit shift= <> < > >= <= Is IsNot Like TypeOf Is All comparison operatorsNot negationAnd AndAlso conjunctionOr OrElse Inclusive disjunction

Page 81: STUDY MATERIAL.doc · Web view... Form, Label, Text box, Command Button, Check Box, Option Button, List Box, Combo Box, Picture Box, Image Controls, Scroll Bars – Drive List Box

81

Xor Exclusive disjunction

String Manipulation Functions:

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. (i)The Len Function

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,

Len (VisualBasic) = 11 and Len (welcome to VB tutorial) = 22

The Len function can also return the number of digits or memory locations of a number that is stored in the computer. For example,

Private sub Form_Activate ( )

X=sqr (16)

Y=1234

Z#=10#

Print Len(x), Len(y), and Len (z)

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.(ii) The Right Function

Page 82: STUDY MATERIAL.doc · Web view... Form, Label, Text box, Command Button, Check Box, Option Button, List Box, Combo Box, Picture Box, Image Controls, Scroll Bars – Drive List Box

82

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,

Right(“Visual Basic”, 4) = asic

(iii)The Left Function

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,

Left (“Visual Basic”, 4) = Visu

(iv) The Ltrim Function

The Ltrim function trims the empty spaces of the left portion of the phrase. The format is

Ltrim(“Phrase”)

.For example,

Ltrim (“ Visual Basic”, 4)= Visual basic(v) The Rtrim Function

The Rtrim function trims the empty spaces of the right portion of the phrase. The format is

Rtrim(“Phrase”)

.For example,

Rtrim (“Visual Basic ”, 4) = Visual basic(vi) The Trim function

The Ttrim function trims the empty spaces on both side of the phrase. The format is

Page 83: STUDY MATERIAL.doc · Web view... Form, Label, Text box, Command Button, Check Box, Option Button, List Box, Combo Box, Picture Box, Image Controls, Scroll Bars – Drive List Box

83

Trim(“Phrase”)

.For example,

Trim (“ Visual Basic ”) = Visual basic (viii) The Mid Function

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,

Mid(“Visual Basic”, 3, 6) = ual Bas

(ix) The InStr function

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

Instr (n, original phase, embedded phrase)

Where n is the position where the Instr function will begin to look for the embedded phrase. For example

Instr(1, “Visual Basic”,” Basic”)=8

(x) The Ucase and the Lcase functions

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,

Ucase(“Visual Basic”) =VISUAL BASiC

Lcase(“Visual Basic”) =visual basic

(xi) The Str and Val functions

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.

Page 84: STUDY MATERIAL.doc · Web view... Form, Label, Text box, Command Button, Check Box, Option Button, List Box, Combo Box, Picture Box, Image Controls, Scroll Bars – Drive List Box

84

(xii) The Chr and the Asc functions

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)

and the format of the Asc function is

Asc(Character)

The following are some examples:

Chr(65)=A, Chr(122)=z, Chr(37)=% , Asc(“B”)=66, Asc(“&”)=38

DATE & TIME FUNCTION:Not only does Visual Basic let you store date and time information in the specific Date

data type, it also provides a lot of date- and time-related functions. These functions are very important in all business applications and deserve an in-depth look. Date and Time are internally stored as numbers in Visual Basic. The decimal points represents the time between 0:00:00 and 23:59:59 hours inclusive.

The system's current date and time can be retrieved using the Now, Date and Time functions in Visual Basic. The Now function retrieves the date and time, while Date function retrieves only date and Time function retrieves only the time.

To display both the date and time together a message box is displayed use the statement given below.

MsgBox "The current date and time of the system is" & Now

Here & is used as a concatenation operator to concentrate the string and the Now function. Selective portions of the date and time value can be extracted using the below listed functions.Function Extracted PortionYear ( ) Year (Now)Month ( ) Month (Now)Day ( ) Day (Now)WeekDay ( ) WeekDay (Now)Hour ( ) Hour (Now)Minute ( ) Minute (Now)Second ( ) Second (Now)

Page 85: STUDY MATERIAL.doc · Web view... Form, Label, Text box, Command Button, Check Box, Option Button, List Box, Combo Box, Picture Box, Image Controls, Scroll Bars – Drive List Box

85

The calculation and conversion functions related to date and time functions are listed below.Function DescriptionDateAdd ( ) Returns a date to which a specific interval has been addedDateDiff ( ) Returns a Long data type value specifying the interval between the two valuesDatePart ( ) Returns an Integer containing the specified part of a given dateDateValue ( ) Converts a string to a DateTimeValue ( ) Converts a string to a timeDateSerial ( ) 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.

DateDiff (interval, date1, date2[, firstdayofweek[, firstweekofyear]])Format Function

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.

Format (expression[, format[, firstdayofweek[, firstweekofyear]]])

The Format function syntax has these parts:Part DescriptionExpression Required any valid expressionformat Optional. A valid named or user-defined format expression.firstdayofweek Optional. A contant that specifies the first day of the week.firstweekofyear Optional. A contant that specifies the first week of the year

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.

Page 86: STUDY MATERIAL.doc · Web view... Form, Label, Text box, Command Button, Check Box, Option Button, List Box, Combo Box, Picture Box, Image Controls, Scroll Bars – Drive List Box

86

Creating and Using Standard Controls:

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:

Caption - the text that is displayed in the label BackColor and ForeColor - colors of the background and the text

BackStyle - Opaque or Transparent - whether the background is visible or not

Font - font and size of text

Alignment - text centered, left or right

Page 87: STUDY MATERIAL.doc · Web view... Form, Label, Text box, Command Button, Check Box, Option Button, List Box, Combo Box, Picture Box, Image Controls, Scroll Bars – Drive List Box

87

Multiline- True or False - if True, you can have several lines of text, delimited by <CR> in the label - by default, it is set to False

The Command Button  

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

Private Sub Command1_Click ()

Statements

End Sub

The Text Box  

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  

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.

Page 88: STUDY MATERIAL.doc · Web view... Form, Label, Text box, Command Button, Check Box, Option Button, List Box, Combo Box, Picture Box, Image Controls, Scroll Bars – Drive List Box

88

Picture1.Picture=LoadPicture ("C:\VB program\Images\grape.gif")

You will learn more about the picture box in future lessons. The image in the picture box is not resizable.

The Image Box

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.

Image1.Picture=LoadPicture ("C:\VB program\Images\grape.gif")

The List 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 

Private Sub Form_Load ( ) 

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 Combo Box  

Page 89: STUDY MATERIAL.doc · Web view... Form, Label, Text box, Command Button, Check Box, Option Button, List Box, Combo Box, Picture Box, Image Controls, Scroll Bars – Drive List Box

89

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 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

Private Sub Form_Load ( ) 

Combo1.AddItem “Item1”Combo1.AddItem “Item2”Combo1.AddItem “Item3”Combo1.AddItem “Item4” 

End Sub

The Check Box

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

Private Sub Command1_Click()

If Check1.Value = 1 And Check2.Value = 0 ThenMsgBox "Apple is selected"ElseIf Check2.Value = 1 And Check1.Value = 0 ThenMsgBox "Orange is selected"ElseMsgBox "All are selected"End If

Page 90: STUDY MATERIAL.doc · Web view... Form, Label, Text box, Command Button, Check Box, Option Button, List Box, Combo Box, Picture Box, Image Controls, Scroll Bars – Drive List Box

90

End Sub

The Option Box

 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

 

Private Sub Option2_Click()

Shape1.Shape = 1

End Sub

 

Private Sub Option3_Click()

Shape1.Shape = 2

End Sub

 

Private Sub Option4_Click()

Shape1.Shape = 3

End Sub

 

Private Sub Option5_Click()

Shape1.Shape = 4

End Sub

 

  

Page 91: STUDY MATERIAL.doc · Web view... Form, Label, Text box, Command Button, Check Box, Option Button, List Box, Combo Box, Picture Box, Image Controls, Scroll Bars – Drive List Box

91

Private Sub Option6_Click()

Shape1.Shape = 5

End Sub

 

The Drive List Box

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

 

Figure 3.4 The Drive List Box

The Directory List Box

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

Figure 3.5 The Directory List Box

Page 92: STUDY MATERIAL.doc · Web view... Form, Label, Text box, Command Button, Check Box, Option Button, List Box, Combo Box, Picture Box, Image Controls, Scroll Bars – Drive List Box

92

 

The File List Box

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

Figure 3.6 The File List Box

Scroll Bars:

Vertical scroll bar

Page 93: STUDY MATERIAL.doc · Web view... Form, Label, Text box, Command Button, Check Box, Option Button, List Box, Combo Box, Picture Box, Image Controls, Scroll Bars – Drive List Box

93

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

Page 94: STUDY MATERIAL.doc · Web view... Form, Label, Text box, Command Button, Check Box, Option Button, List Box, Combo Box, Picture Box, Image Controls, Scroll Bars – Drive List Box

94

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.

Page 95: STUDY MATERIAL.doc · Web view... Form, Label, Text box, Command Button, Check Box, Option Button, List Box, Combo Box, Picture Box, Image Controls, Scroll Bars – Drive List Box

95

FRAME:

A frame is an object that provides a visual an functional container for controls. It is an object that has solid border around it and a caption at the top. You cannot just drag an option button over a frame to add it to the frame. Instead, you must actually draw the option button on the frame. This means you cannot draw an option button in a frame using the shortcut of double-clicking the control in the toolbox.

Properties 

  Frame

General  

Caption Text used to label the frame. Font is set in the font tab.

MousePointer The type of mouse pointer displayed when over the frame. Choose from 16 different types plus a custom pointer

Appearance 3D or Flat. 3D is the standard Windows look. Flat results in a rectangular square of background color with a foreground color border and caption.

BorderStyle FixedSingle (default) or None. None may be used with Flat Appearance to achieve an uncaptioned rectangle of background color.

OLEDropMode Set to None (default) if the frame does not accept OLE drops and is to display the No Drop cursor if an OLE drop is attempted. Set to Manual, the frame will trigger OLE drop events, allowing programs to handle the OLE drop operation in code.

Enabled True or False. True means the object can respond to user-generated events, false prevents it from responding. We can disable a control like a text box if we wish it to simply display information in a read-only way.

Page 96: STUDY MATERIAL.doc · Web view... Form, Label, Text box, Command Button, Check Box, Option Button, List Box, Combo Box, Picture Box, Image Controls, Scroll Bars – Drive List Box

96

   

Color  

Back Color Color to be used for the frame's background, normally seen only when Flat Style is used.

Fore Color Color to be used for the frame's foreground, the color of the text caption.

Color Set Choose from Standard Colors (standard Windows non-dithered colors) or Windows System Colors. The latter will be defined by the user's Control Panel settings and is normally the setting used so that the form changes appearance like the rest of Windows if the Control Panel settings are changed.

Color Palette Displays available colors. Click on the property to be changed to highlight it in the Properties pane, click on the desired color in the Color Palettepane and then press Apply.

Edit Custom Color

Change the custom color presented in the Color Palette when the Color Set is set to Windows System Colors.

   

Font  

Properties Font properties that may be changes.

Font Choose a font installed on this system. It's wise to choose standard Windows fonts such as MS Sans Serif that are universally available.

Size Size of font, in points.

Effects Bold, Italic, Underline or Strikeout.

Sample Text A preview of the selected settings.

Page 97: STUDY MATERIAL.doc · Web view... Form, Label, Text box, Command Button, Check Box, Option Button, List Box, Combo Box, Picture Box, Image Controls, Scroll Bars – Drive List Box

97

The Line and Shape ControlsThe graphics you've worked with in this book have, until now, been graphic images stored in files. The Image and Picture Box controls display graphic images on the form. The toolbar buttons can display icon images. You have yet to see how to draw your own graphics. The rest of this lesson introduces VB's drawing tools.

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.

Page 98: STUDY MATERIAL.doc · Web view... Form, Label, Text box, Command Button, Check Box, Option Button, List Box, Combo Box, Picture Box, Image Controls, Scroll Bars – Drive List Box

98

Figure 19.8 The images that you can draw.

The Line ControlYou use the Line control to draw lines of various widths, lengths, and patterns. The Shape control handles the drawing of all other fundamental shapes.

Mastering the Line ControlThe Line control contains properties that specify the width and length of lines you draw. In addition, you can change the pattern of each line you draw.

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.

Table 19.1. The Line control's fundamental properties.Property Description

BorderColor Sets the line color.

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.

BorderWidth Specifies the size, in twips, that the line takes.

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.

Y1 Contains the number of twips from the top of the Form window to the left starting

Page 99: STUDY MATERIAL.doc · Web view... Form, Label, Text box, Command Button, Check Box, Option Button, List Box, Combo Box, Picture Box, Image Controls, Scroll Bars – Drive List Box

99

Property Description

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.

Table 19.2. The Line control's BorderStyle values.Value Named Literal Description

0-Transparent vbTransparent Background comes through the line.

1-Solid vbBSSolid The line is a solid line.

2-Dash vbBSDash The line is composed of dashes.

3-Dot vbBSDot The line is composed of dots.

4-Dash-Dot vbBSDashDot The line is composed of a continuing dash-dot-dash-dot.

5-Dash-Dot-Dot vbBSDashDotDot The line is composed of a series of one dash followed by two dots.

6-Inside Solid vbBSInsideSolid Same as 1-Solid for lines.

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?)

Figure 19.9 The BorderStyle property values.

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

Page 100: STUDY MATERIAL.doc · Web view... Form, Label, Text box, Command Button, Check Box, Option Button, List Box, Combo Box, Picture Box, Image Controls, Scroll Bars – Drive List Box

100

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.

Figure 19.10 Accenting forms with lines.

Mastering the Shape ControlThe Shape control gives you the capability to draw six different kinds of figures on the form. The various shading and color properties help you distinguish one shape from another. Table 19.3 contains the basic properties you'll use for the Shape control. The most important property is the Shape property. The Shape property gives a shape from one of the six fundamental shapes.

Table 19.3. The Shape control's fundamental properties.Property Description

BackColor Specifies a Windows color value that determines the background color of the shape.

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.

Page 101: STUDY MATERIAL.doc · Web view... Form, Label, Text box, Command Button, Check Box, Option Button, List Box, Combo Box, Picture Box, Image Controls, Scroll Bars – Drive List Box

101

Property Description

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.

Page 102: STUDY MATERIAL.doc · Web view... Form, Label, Text box, Command Button, Check Box, Option Button, List Box, Combo Box, Picture Box, Image Controls, Scroll Bars – Drive List Box

102

Figure 19.11 The FillStyle property determines the shape's interior design.

Table 19.4. The Shape control's FillStyle values.Value Named Literal Description

0-Solid vbFSSolid Solid color fill with no pattern.

1-Transparent vbFSTransparent The shape appears as an outline only.

2-Horizontal Line vbHorizontalLine Horizontal lines fill the shape.

3-Vertical Line vbVerticalLine Vertical lines fill the shape.

4-Upward Diagonal vbUpwardDiagonal Upward diagonal lines fill the shape.

5-Downward Diagonal vbDownwardDiagonal Downward diagonal lines fill the shape.

6-Cross vbCross Crosshairs fill the shape.

7-Diagonal Cross vbDiagonalCross Diagonal crosshairs fill the shape.

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.

Table 19.5. The Shape control's Shape values.Value Description

0-Rectangle A rectangle

1-Square A square

2-Oval An oval

Page 103: STUDY MATERIAL.doc · Web view... Form, Label, Text box, Command Button, Check Box, Option Button, List Box, Combo Box, Picture Box, Image Controls, Scroll Bars – Drive List Box

103

Value Description

3-Circle A circle

4-Rounded Rectangle A rectangle with rounded corners

5-Rounded Square A square with rounded corners

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. 

To refer to a member of a control array, the syntax is: 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 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

Page 104: STUDY MATERIAL.doc · Web view... Form, Label, Text box, Command Button, Check Box, Option Button, List Box, Combo Box, Picture Box, Image Controls, Scroll Bars – Drive List Box

104

an Index parameter to the event procedure. For example, the GotFocus event procedure for the txtField control array might look like this:

 Private Sub txtField_GotFocus(Index As Integer) txtField(Index).SelStart = 0txtField(Index).SelLength = Len(txtField(Index).Text) End Sub

 - or - 

Private Sub txtField_GotFocus(Index As Integer) 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: Private Sub txtField_KeyPress(Index As Integer, KeyAscii As Integer) 

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:

A dialog box has the following characteristics:

Page 105: STUDY MATERIAL.doc · Web view... Form, Label, Text box, Command Button, Check Box, Option Button, List Box, Combo Box, Picture Box, Image Controls, Scroll Bars – Drive List Box

105

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.FixedDialogEnd Sub

The Minimize and Maximize Boxes

Besides taking care of the border, you should also set both the MinimizeBox and the MaximizeBox properties to False. This causes the window to display only the system Close button. You can set these characteristics 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

Page 106: STUDY MATERIAL.doc · Web view... Form, Label, Text box, Command Button, Check Box, Option Button, List Box, Combo Box, Picture Box, Image Controls, Scroll Bars – Drive List Box

106

MinimizeBox = False MaximizeBox = FalseEnd Sub

This would produce:

Closing a Dialog Box

You should provide a way for the user to close the dialog box. A dialog box should have at least one button labeled OK. This button allows the user to acknowledge the message of the dialog box and close it by clicking the button. If the user   press Enter, the dialog box should also be closed as if the OK button was clicked.

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.

Modal Dialog BoxesThere are two types of dialog boxes: modal and modeless.

Page 107: STUDY MATERIAL.doc · Web view... Form, Label, Text box, Command Button, Check Box, Option Button, List Box, Combo Box, Picture Box, Image Controls, Scroll Bars – Drive List Box

107

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:

Modeless Dialog Boxes

A dialog box is referred to as modeless if the user does not have to close it in order to continue using the application that owns the dialog box. A modeless dialog box has the following characteristics

It has a thin border

It can be neither minimized nor maximized. This means that it is not equipped with the Minimize or the Maximize buttons

It is not represented on the taskbar with a button

It must provide a way for the user to close it

Here is an example:

Page 108: STUDY MATERIAL.doc · Web view... Form, Label, Text box, Command Button, Check Box, Option Button, List Box, Combo Box, Picture Box, Image Controls, Scroll Bars – Drive List Box

108

The Find (and the Replace) dialog box of WordPad (also the Find and the Replace dialog boxes of most applications) is an example of a modeless dialog box. If it is opened, the user does not have to close it in order to use the application or the document in the background.

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

Predefined Dialog Boxes:The easiest way to add a dialog box to your application is to use a predefined dialog, because you don't have to worry about designing, loading, or showing the dialog box. However, your control over its appearance is limited. Predefined dialog boxes are always modal.Prompting for Input with InputBox

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.

Page 109: STUDY MATERIAL.doc · Web view... Form, Label, Text box, Command Button, Check Box, Option Button, List Box, Combo Box, Picture Box, Image Controls, Scroll Bars – Drive List Box

109

Figure 6.17   A dialog box using the InputBox function

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.

Displaying Information with MsgBox

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"

Custom Dialog Boxes:

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:

Page 110: STUDY MATERIAL.doc · Web view... Form, Label, Text box, Command Button, Check Box, Option Button, List Box, Combo Box, Picture Box, Image Controls, Scroll Bars – Drive List Box

110

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 ("").

Setting Standard Dialog Box Properties

Property Setting

Effect

BorderStyle 1 Changes the border style to fixed single, thus preventing the dialog box from being sized at run time.

ControlBox False Removes the Control menu box.

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.

Page 111: STUDY MATERIAL.doc · Web view... Form, Label, Text box, Command Button, Check Box, Option Button, List Box, Combo Box, Picture Box, Image Controls, Scroll Bars – Drive List Box

111

SINGLE DOCUMENT INTERFACE:

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.

Page 112: STUDY MATERIAL.doc · Web view... Form, Label, Text box, Command Button, Check Box, Option Button, List Box, Combo Box, Picture Box, Image Controls, Scroll Bars – Drive List Box

112

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).

Creating an MDI ApplicationUse the following procedure to create an MDI form and its child forms.

To create an MDI application1. Create an MDI form.

From the Project menu, choose Add MDI Form.Note   An application can have only one MDI form. If a project already has an MDI form, the Add MDI Form command on the Project menu is unavailable.

2. Create the application's child forms.

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.

Stability and Performance

Page 113: STUDY MATERIAL.doc · Web view... Form, Label, Text box, Command Button, Check Box, Option Button, List Box, Combo Box, Picture Box, Image Controls, Scroll Bars – Drive List Box

113

SDI applications tend to be more robust and bug-free than MDI applications, since a serious error with one document rarely affects the other documents within an SDI environment. For example, if one Windows Notepad document crashes, any other open copies of Notepad will usually survive the crash. On the other hand, if one Web page in Firefox causes the browser to crash, all the open Web pages die with it. Nevertheless, MDI applications tend to perform more quickly than SDI programs, since only one version of the application is loaded into memory.

MENUS:

Windows applications provide groups of related commands in Menus.Menus are intrinsic controls, and as such they deserve a place in this chapter. On the other hand, menus behave differently from other controls.

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.

An expanded Menu Editor window.

Page 114: STUDY MATERIAL.doc · Web view... Form, Label, Text box, Command Button, Check Box, Option Button, List Box, Combo Box, Picture Box, Image Controls, Scroll Bars – Drive List Box

114

An expanded menu

The Template Manager in action

The programmer can create menu control arrays. The Index TextBox specifies the menu's index in the control array.

The Menu Editor dialog also provides several CheckBoxes to control the appearance of the Menu.

Page 115: STUDY MATERIAL.doc · Web view... Form, Label, Text box, Command Button, Check Box, Option Button, List Box, Combo Box, Picture Box, Image Controls, Scroll Bars – Drive List Box

115

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 mnuFileOpen mnuOpenSave mnuSaveExit mnuExitEdit mnuEditCopy mnuCopyCut mnuCutPaste mnuPaste

Page 116: STUDY MATERIAL.doc · Web view... Form, Label, Text box, Command Button, Check Box, Option Button, List Box, Combo Box, Picture Box, Image Controls, Scroll Bars – Drive List Box

116

Unit – VData 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.

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.

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.

Page 117: STUDY MATERIAL.doc · Web view... Form, Label, Text box, Command Button, Check Box, Option Button, List Box, Combo Box, Picture Box, Image Controls, Scroll Bars – Drive List Box

117

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

Data Access Objects (DAO):

DAO (Data Access Objects) is an application program interface (API) available with Microsoft's Visual Basic that lets a programmer request access to a Microsoft Access database. DAO was Microsoft's first object-oriented interface with databases. DAO objects encapsulate Access's Jet functions. Through Jet functions, it can also access other Structured Query Language (SQL) databases. This includes all of the applications in Microsoft Office, such as MS-Word, MS-Access, and Excel. Jet Engine is the database engine that accesses the data. Jet Engine is a collection of programs that work together. Jet Engine makes use of some other translators to access various types of databases.

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.

Objects in DAO object model:

The following are the various objects in DAO object model. Here is the object model’s hierarchy.

Each object contains collections, methods and properties.

Page 118: STUDY MATERIAL.doc · Web view... Form, Label, Text box, Command Button, Check Box, Option Button, List Box, Combo Box, Picture Box, Image Controls, Scroll Bars – Drive List Box

118

A collection is a collection of objects of the same type. A method performs an operation on the object. A property contains a single attribute of the object.

A Full-Scale DAO Example:

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.• dbVersion10—Creates a database that uses the Jet engine version 1 file format.

Page 119: STUDY MATERIAL.doc · Web view... Form, Label, Text box, Command Button, Check Box, Option Button, List Box, Combo Box, Picture Box, Image Controls, Scroll Bars – Drive List Box

119

• 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).

Declaring a Data Bound Control:

Figure A: Components Figure B: Properties table

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

Page 120: STUDY MATERIAL.doc · Web view... Form, Label, Text box, Command Button, Check Box, Option Button, List Box, Combo Box, Picture Box, Image Controls, Scroll Bars – Drive List Box

120

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).

Figure C: Properties Table

Connecting a Data Bound Control with a Database:

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, update database table values and create the structure of databases (McManus, Database Access with Visual Basic 6.0).

Page 121: STUDY MATERIAL.doc · Web view... Form, Label, Text box, Command Button, Check Box, Option Button, List Box, Combo Box, Picture Box, Image Controls, Scroll Bars – Drive List Box

121

In general, four parameters must be defined for data access:

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.

Manipulating Data Records with a Data Bound Control:

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.

Page 122: STUDY MATERIAL.doc · Web view... Form, Label, Text box, Command Button, Check Box, Option Button, List Box, Combo Box, Picture Box, Image Controls, Scroll Bars – Drive List Box

122

Figure D: Procedure attributes box

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:

A DAO Recordset, represented in MFC (Microsoft Foundation Class) by

a CDaoRecordset object. "A logical set of records. where Microsoft defines a record as "A set

of related data about a person, place, event, or some other item. Table data is stored in records

(rows) in the database. Each record is composed of a set of related fields (columns) - each field

Page 123: STUDY MATERIAL.doc · Web view... Form, Label, Text box, Command Button, Check Box, Option Button, List Box, Combo Box, Picture Box, Image Controls, Scroll Bars – Drive List Box

123

defining one attribute of information for the record. Taken together, a record defines one specific

unit of retrievable information in a database."

A Recordset represents, simultaneously: All of the records in a table or query — a set of records. The current record in that set, whose fields fill the recordset's field data members, if any.

Scrolling to a different record in the set fills the recordset's field data members with new values.

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.

DAO Recordset Types:

You can create three kinds of CDaoRecordset objects: Table-type recordsets, representing a base table in a Microsoft Jet (.MDB) database Dynaset-type recordsets, which result from a query

Snapshot-type recordsets, consisting of a static copy of a set of records

The following table summarizes the characteristics and purposes of the three recordset types.

Characteristics of Recordset Types:

Characteristic Table-Type Dynaset-Type Snapshot-Type

Page 124: STUDY MATERIAL.doc · Web view... Form, Label, Text box, Command Button, Check Box, Option Button, List Box, Combo Box, Picture Box, Image Controls, Scroll Bars – Drive List Box

124

Based On A base table A query A query

Updatable Yes Yes No

Dynamic Yes Yes No

Best Uses Working with a single table (in a non-ODBC database).

Working with records, possibly containing fields from one or more tables. Reflects changes by other users and is updatable.

Finding data or preparing reports. Reflects the state of the data at the time of the snapshot.

Limitations Can use only with .MDB databases or ISAM tables opened directly.

Doesn't reflect new records that meet selection criteria after the recordset opens.

Not updatable. The snapshot is not quite instantaneous..

A table-type recordset is based directly on the table rather than on a query.

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.

For information about why and how to bind records 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'

Page 125: STUDY MATERIAL.doc · Web view... Form, Label, Text box, Command Button, Check Box, Option Button, List Box, Combo Box, Picture Box, Image Controls, Scroll Bars – Drive List Box

125

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:

If you base your recordset on...

It has these characteristics...

A querydef The recordset inherits the querydef's SQL string.

A tabledef The recordset (a table-type recordset) is based on the table. Creating a recordset from a tabledef is similar to creating one from a querydef. See the following procedure for creating from a querydef.

The SQL string specified at design time

The recordset uses the SQL string retrieved by calling its GetDefaultSQL member function.

An SQL string specified at run time, in the Open call

The SQL string passed to Open overrides the SQL defined at design time.

To create a recordset from a querydef: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 objecttry{ // Construct the querydef CDaoQueryDef qd( pdb );

// Set up the SQL string and create the querydef

Page 126: STUDY MATERIAL.doc · Web view... Form, Label, Text box, Command Button, Check Box, Option Button, List Box, Combo Box, Picture Box, Image Controls, Scroll Bars – Drive List Box

126

CString strSQL = _T("SELECT [Company Name] FROM Publishers WHERE State = 'NY'"); qd.Create( _T("My Querydef"), strSQL );

// Construct a CDaoRecordset-derived object // and open it based on the querydef CPublisherSet rsPub( pdb ); rsPub.Open( &qd );}catch( CDaoException* e )// ...

To create a recordset without a querydef:1. Construct a CDaoRecordset object.2. Call the recordset object's Open member function. Specify a SQL string.

A SELECT statement of the basic form:

SELECT column-list FROM table-list

Modifying, Deleting Records:

Adding New Records in DAO: Populating Recordsets and Counting Records with DAO AddNew Method

Update Method

To add a new record to a recordset:1. Determine whether your recordset is updatable.

Call the recordset's CanUpdate member function.2. Call the recordset's AddNew member function.

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.

3. Assign values to the new record's fields.

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").

Page 127: STUDY MATERIAL.doc · Web view... Form, Label, Text box, Command Button, Check Box, Option Button, List Box, Combo Box, Picture Box, Image Controls, Scroll Bars – Drive List Box

127

Or, if you explicitly want the field to be Null, call only SetFieldNull, with the parameter TRUE.

4. Complete the process by calling the recordset's Update member function.

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.

Editing Existing Records in DAO:

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.

To edit an existing record in a recordset:1. Determine whether your recordset is updatable.

Call the recordset's CanUpdate member function.2. Move to the record you want to edit.

Use any of the recordset's navigation mechanisms that take you to a specific record.3. Call the recordset's Edit member function.

Edit prepares the recordset's edit buffer, which DAO calls the copy buffer. For more information about the edit buffer with Edit,

4. Assign values to the fields you want to change.

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.

5. Complete the process by calling the recordset's Update member function.

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.

Page 128: STUDY MATERIAL.doc · Web view... Form, Label, Text box, Command Button, Check Box, Option Button, List Box, Combo Box, Picture Box, Image Controls, Scroll Bars – Drive List Box

128

Deleting Records in DAO:

To delete a record from a recordset:1. Determine whether your recordset is updatable.

Call the recordset's CanUpdate member function.2. Move to the record you want to edit.

Use any of the recordset's navigation mechanisms that take you to a specific record.3. Call the recordset's Delete member function.

You don't call Update for a deletion.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.

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.

Using Seek vs. Using Find

Criterion Seek Find

Use In Indexed table-type recordsets.

Dynaset-type or snapshot-type recordsets.

Limitations Can't use on attached tables, but can use on

Can't use on a forward-only scrolling snapshot-type recordset. Use with

Page 129: STUDY MATERIAL.doc · Web view... Form, Label, Text box, Command Button, Check Box, Option Button, List Box, Combo Box, Picture Box, Image Controls, Scroll Bars – Drive List Box

129

installable ISAM databases.

ODBC-based recordsets can be inefficient.

Call Before Seek/Find

SetCurrentIndex  

Call After Seek/Find Check Seek or Find return value

Check Seek or Find return value

Seek and Find is not the only means of navigating in a recordset. You can also use: Move, MoveFirst, MoveLast, MoveNext, and MovePrev GetBookmark, SetBookmark

GetAbsolutePosition, SetAbsolutePosition

GetPercentPosition, SetPercentPosition

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: 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 recordsettry{ // Set current index for recordset and // save current position. rs.SetCurrentIndex( _T("PartNameIndex") ); COleVariant varCurrentPos = rs.GetBookmark( );

Page 130: STUDY MATERIAL.doc · Web view... Form, Label, Text box, Command Button, Check Box, Option Button, List Box, Combo Box, Picture Box, Image Controls, Scroll Bars – Drive List Box

130

// variant used as a key in Seek COleVariant varKey (_T("Framis Lever"), VT_BSTRT);

// Find first record whose Part Name // field is "Framis Lever". if ( rs.Seek( _T("="), &varKey ) ) // Return to the saved position rs.SetBookmark( varCurrentPos ); else // Do something in response to Seek failure}catch( CDaoException* e ){ e->Delete( );}

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:

The CDaoRecordset::Find member function and its relatives, FindNext, FindPrev, FindFirst, and FindLast, let you search for a record in a dynaset-type or snapshot-type recordset. The Find member functions search from a location and in a direction as shown in the following table.

The Find Family of Functions

Find operation

Begin at Search direction

FindFirst Beginning of recordset End of recordset

FindLast End of recordset Beginning of recordset

FindNext Current record End of recordset

Page 131: STUDY MATERIAL.doc · Web view... Form, Label, Text box, Command Button, Check Box, Option Button, List Box, Combo Box, Picture Box, Image Controls, Scroll Bars – Drive List Box

131

FindPrev Current record Beginning of recordset

The basic Find function takes two parameters: The type of find: AFX_DAO_NEXT, AFX_DAO_PREV, AFX_DAO_FIRST,

or AFX_DAO_LAST. A filter — a string expression like the WHERE clause in an SQL statement (without the

keyword), that specifies the criterion for finding. The expression can be compound, using AND,OR, and so on.

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 openedCString strCriteria = _T("STATE = 'NY'");try{ if ( rs.FindFirst( strCriteria ) ) // Do something with the found record rs.FindNext( strCriteria ); // ...}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.

Page 132: STUDY MATERIAL.doc · Web view... Form, Label, Text box, Command Button, Check Box, Option Button, List Box, Combo Box, Picture Box, Image Controls, Scroll Bars – Drive List Box

132

• Can contain connection and command objects• Can establish relationship between command object to represent hierarchies• Can group data and get aggregates• Allows fields to be dragged and dropped on to a Data Report, for report, and a Form for data entry screen• Can work as source for Databound control such as DataCombo controls and Hierarchical Flexgrid control. In order to work with Data Environment object, you have to add Data Environment Designer to your project. Data Environment Designer allows programmer to accomplish any of the tasks mentioned above. Data Environment Designer is invoked when you double click on Data Environment object in Project Explorer.

To add Data Environment object to the project:

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.

Data Environment Designer:

Working with Connection Object:

A Connection object represents a connection to a remote database that is used as a data source.

Whenever you create a Data Environment object a Connection object is added to Data Environment object. But that Connection object is not connected to any database. So first we have to establish a connection with the Connection object. Now, let us see how to connect to database through Connection object. 

To connect to Biblio.mdb using connection object:1. Select Connection object (Connection1) and click on right button.2. From popup menu select Properties optionData Environment designer displays Data Link properties dialog.3. Select the required OLEDB provider (Microsoft Jet 3.51 OLE DB Provider)4. Select Connection tab and select the name of the database ( BIBLIO.MDB)5. Click on Ok

To rename connection object:

Page 133: STUDY MATERIAL.doc · Web view... Form, Label, Text box, Command Button, Check Box, Option Button, List Box, Combo Box, Picture Box, Image Controls, Scroll Bars – Drive List Box

133

1. Invoke popup menu by click on Connection object with right button.2. Select Rename option.3. Enter new name and press enter key to confirm it.

Creating Command 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.

To create command object to get data from Authors table:1. Invoke popup menu of Connection object and select Add Command optionData Environment Designer creates a command object with name Command1.2. Invoke Popup menu of command object by clicking on right button and select Properties option.Properties dialog is displayed 3. Change the Name of the command object to Authors4. Select Table as Database Object5. Invoke the list of tables by clicking on down arrow of Object Name drop down and select Authors as the name of the table.6. For the time being, ignore remaining tabs and click on OK.

Properties of 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. 

Data Report Designer:

Page 134: STUDY MATERIAL.doc · Web view... Form, Label, Text box, Command Button, Check Box, Option Button, List Box, Combo Box, Picture Box, Image Controls, Scroll Bars – Drive List Box

134

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.

Page 135: STUDY MATERIAL.doc · Web view... Form, Label, Text box, Command Button, Check Box, Option Button, List Box, Combo Box, Picture Box, Image Controls, Scroll Bars – Drive List Box

135

Sections of the Data Report Designer:

The default Data Report designer contains these Sections:

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.

Group Header/Footer—contains a "repeating" section of the data report. Each group header is matched with a group footer. The header and footer pair are associated with a single Command object in the Data Environment designer.

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.

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.

Data Report Designer Features:

The Data Report designer has several features:

1. Drag-and-Drop Functionality for Fields—Drag fields from the Microsoft Data Environment designer to the Data Report designer. When you do this, Visual Basic automatically creates a text box control on the data report and sets the DataMember and DataField properties of the dropped field. You can also drag a Command object from the Data Environment designer to the Data Report designer. In that case, for each of the fields contained by the Command object, a text box control will be created on the data report; the DataMember and DataField property for each text box will be set to the appropriate values.

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."

Page 136: STUDY MATERIAL.doc · Web view... Form, Label, Text box, Command Button, Check Box, Option Button, List Box, Combo Box, Picture Box, Image Controls, Scroll Bars – Drive List Box

136

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.

7. Asynchonous Operation—The DataReport object's PrintReport and ExportReport methods are asynchronous operations. Using the ProcessingTimeout event, you can monitor the state of these operations and cancel any that are taking too long.

Data Report Controls:

When a new Data Report designer is added to a project, the following controls are automatically placed in the Toolbox tab named DataReport:

TextBox Control (RptTextBox)—allows you to format text, or assign a DataFormat.

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.

Shape Control (RptShape)—enables you to place rectangles, triangles, or circles (and ovals) on a report.

Function Control (RptFunction)—a special text box that calculates values as the report is generated.

Page 137: STUDY MATERIAL.doc · Web view... Form, Label, Text box, Command Button, Check Box, Option Button, List Box, Combo Box, Picture Box, Image Controls, Scroll Bars – Drive List Box

137