You are on page 1of 85

INFORMATION SHEET

TOPIC : PROGRAMMING AND DATABASE


1.0 Introduction C++
2.0 Control Structures
3.0 User defined function
4.0 File system and database (Ms Access)
SUB-TOPIC :
5.0 The relational database model
6.0 Structured query language (SQL)
7.0 Visual basic interfaces

1. Identify the computer languages.


2. Identify the syntax of C++ languages.
3. Write a C++ program based on given problem.
4. Describe the Entity Relationship (E-R) modeling basic
LEARNING components.
OUTCOME : 5. Draw E-R diagram (ERD) to map Entity Relationship (E-R)
modeling by using Chen model.
6. Write proper naming convention for each component in ERD.
7. Apply the ERD into Microsoft Access.

Page 1 of 85
INTRODUCING C++
COMPUTER LANGUAGE

Computer language is divided into three general types which are:


 Machines language
 Assembly language
 High-level language

Machine languages
 Any computer can directly understand only its own machine language
 Machine language are machine dependent, which means a particular machine
language can be used on only one type of computer
 Machine language are cumbersome for human because it consist of strings of
numbers
 Example:

Following is a section of a machine language program that adds overtime pay to base pay
and stores the result in gross pay.

+1300042774
+1400593419
+1200274027

Assembly languages
 Instead of using the strings of numbers, programmers began using English-
like abbreviations to represent the elementary operations of the computer
 These English-like abbreviations formed the basis of assembly languages
 Translator programs called assemblers were developed to convert assembly
language to machine language
 Example:

Following is a section of an assembly languages program that adds overtime pay to base
pay and stores the result in gross pay.

LOAD BASEPAY
ADD OVERPAY
STORE GROSSPAY

High-level languages
 To speed the programming process, high-level languages were developed in which
single statements accomplish substantial tasks
 Translator programs called compilers convert high-level languages into machine
language
 High-level languages allow programmers to write instructions that look almost like
everyday English and contain commonly used mathematical notations
 Example:

Page 2 of 85
Following is a section of a high-level languages program that adds overtime pay to base
pay and stores the result in gross pay.

grossPay = basePay + overTimePay

 Example of high-level languages:


i. C
ii. C++ (derived from C)
iii. BASIC
iv. Visual Basic (derived from BASIC)
v. FORTRAN
vi. COBOL
vii. Pascal
viii. Java

C++ SYNTAX

C++ program file names often end with the .cpp, .cxx, .cc or .C (C is uppercase).
Following is a table that consists of C++ syntax (Please refer Appendix for related
program: Example 1.cpp).

Line C++ Syntax Description


Comment: Comment help
people read and understand
1–4 /* ….. */
your program. You can also
replace this syntax with //.
Preprocessor directives: Lines
that begin with # are processed
by the preprocessor before the
#include<iostream.h program is compiled. Line 6
6–7 > notifies the preprocessor to
#include<stdlib.h> include in the program the
contents of the input/output
stream header file
<iostream.h>.
The parenthesis after main
indicates that main is a program
building block called a function.
10 int main()
The keyword int to the left of
main indicates that main
“returns” an integer value.
The left brace, {, must begin the
body of every function. A
11 & 29 { & }
corresponding right brace, },
must end each function’s body.
12 - 13 char name[20]; Declarations of variables: The
int matrixno; words name[20] and matrixno
are the names of variables. A
variable is a location in the
computer’s memory where a

Page 3 of 85
value can be stored for use by a
program. This declaration
specifies that the variable
name[20] is data of type char,
which means that this variable
will hold string value (within 20
characters including letter,
number, and symbol), i.e., whole
string such as khairi, NEPAL,
Ais_14. Variable matrixno is
data of type int, which means
that this variable will hold integer
values, i.e., whole numbers such
as 7, -11, 0, 31914.
Instructs the computer to print on
the screen the string of
characters contained between
15 cout<<”……”;
the quotation marks. The entire
line of line 15 is called a
statement.
Uses the input stream object cin
and the stream extraction
16 cin>>variable;
operator >>, to obtain a value
from the keyboard.
The backslash (\) is called an
escape character. It indicates
that a “special” character is to be
output. When a backslash is
encountered in a string of
characters, the next character is
combined with the backslash to
\n
15 & 26 form an escape sequence. The
endl
escape sequence \n means
newline. Other examples of
escape sequence are \t, \a, and
\r.

The endl has same function


as \n in the program.
C++ keyword return is one of
several means we will use to exit
28 return 0; a function. The value 0 indicates
that the program has terminated
successfully.

ARITHMETIC OPERATORS

Basically C++ used mathematical operators for calculation tasks. Following is a table that
consists of C++ syntax (Please refer Appendix for related program: Example 2.cpp).

Page 4 of 85
Line C++ Syntax Description
Addition operation which sum of
26 total1 = a + c;
a and c is stored in total1.
Addition operation which 1 is
28 a++; automatically added to a and
stored in a as a new value.
Addition operation which 2 is
29 a+=2; added to a and stored in a as a
new value.
The program will display the
33 cout<<”\n\ntotal2:”<<d-a; value of subtraction between d
and a.
Subtraction operation which 1 is
34 a--; automatically minus from a and
stored in a as a new value.
Subtraction operation which 1 is
35 a-=1; minus from a and stored in a as
a new value.
Multiplication operation which
40 total3 = total1 * a; product of total1 and a is stored
in total3.
Multiplication operation which
42 total3*=2; product of total3 and 2 is stored
in total3.
The program will display the
value of division between d and
a.

Examples:
46 ..…”\n\ntotal4: “<<d/2.....
Sum1 = 8 / 4
=2

Sum2 = 9 / 7
= 1 (ignore the balance)
Modulus operation which product
of 7 and 2 is stored in total5.

Examples:
50 total5 = 7 % 2
Sum1 = 8 / 4
= 0 (pick the balance)

Sum2 = 9 / 7
= 2 (pick the balance)

RELATIONAL AND EQUALITY OPERATORS

Following is a table that consists of C++ syntax (Please refer Appendix for related

Page 5 of 85
program: Example 3.cpp).

Line C++ Syntax Description


14 if (num1<num2) num1 is less than num2
17 if (num1>num2) num1 is greater than num2
num1 is less than or equal to
22 if (num1<=num2)
num2
num1 is greater than or equal to
25 if (num1>=num2)
num2
30 if (num1= =num2) num1 is equal to num2
33 if (num1!=num2) num1 is not equal to num2

LOGICAL OPERATORS

Following is a table that consists of C++ syntax (Please refer Appendix for related
program: Example 4.cpp).

Line C++ Syntax Description


Either any one condition is TRUE
if ((gender= ='M') ||
19 (for example, gender is M or
(gender= ='F'))
gender is F)
Both conditions must TRUE (for
if ((gender= ='M') &&
22 example, gender is M and age is
(age>=21))
greater than or equal to 21)

CONTROL STRUCTURES
IF SELECTION STRUCTURE

The if selection structure is a single-selection structure-it selects or ignores a single


action.

For example, suppose the passing grade on an exam is 60. The pseudocode statement

If student’s grade is greater than or equal to 60


Print “Passed”

determines whether the condition “student’s grade is greater or equal than 60” is true or
false. If the condition is true, then “Passed” is printed and the next pseudocode statement
in order is “performed”. If the condition is false, the print statement is ignored and the next
pseudocode statement in order is performed.

The preceding pseudocode if statement can be written in C++ as

if ( grade >= 60 )
cout << “Passed”;

Page 6 of 85
Please refer Appendix for related program: Example 5.cpp.

IF/ELSE SELECTION STRUCTURE

The if/else selection structure is a double-selection structure-it selects between two


different actions.

For example, the pseudocode statement

If student’s grade is greater than or equal to 60


Print ”Passed”
else
Print “Failed”

print Passed if the student’s grade is greater than or equal to 60, but prints Failed if the
student’s grade is less than 60. In either case, after printing occurs, the next pseudocode
statement in sequence is performed.

The preceeding pseudocode if/else structure can be written in C++ as

if ( grade >=60 )
cout << ”Passed”;
else
cout << ”Failed”;

C++ provides the conditional operator (?:), which is closely related to the if/else structure.
The conditional operator is C++’s only ternary operator – it takes three operands. The
operands, together with the conditional operator, form a conditional expression. The first
operand is a condition, the second operand is the value for the entire conditional
expression if the condition is true and the third operand is the value for the entire
conditional expression if the condition is false. For example, the output statement

cout << ( grade >= 60 ? “Passed” : “Failed”);

Please refer Appendix for related program: Example 6.cpp & Example 7.cpp.

WHILE REPETITION STRUCTURE

A repetition structure allows the programmer to specify that a program should repeat an
action while some condition remains true. The pseudocode statement

While there are more items on my shopping list


Purchase next item and cross it off my list

describes the repetition that occurs during a shopping trip. The condition, “there are more
items on my shopping list” is either true or false. If it is true, then the action, “Purchase
next item and cross it off my list” is performed.

As an example of an actual while, consider a program segment designed to find the first

Page 7 of 85
power of 2 larger than 1000. Suppose the integer variable product has been initialized to
2. When the following while repetition structure finishes executing, product will contain the
desired answer:

int product=2;

while (product <=1000)


product = 2 * product;

When the while structure begins execution, the value of product is 2. Each repetition of the
while structure multiplies product by 2, so product takes on the values 4, 8, 16, 32, 64,
128, 256, 512, and 1024 successively. When product becomes 1024, the while structure
condition, product <=1000, becomes false. This terminates the repetition-the final value of
product is 1024. Program execution continues with the next statement after the while.

Please refer Appendix for related program: Example 8.cpp.

FOR REPETITION STRUCTURE

The general format of the for structure is

for ( initialization; loopContinuationCondition; increment )


statement

where the initialization expression initializes the loop’s control variable,


loopContinuationCondition is the condition that determines whether the loop should
continue executing (this condition contains the final value of the control variable for which
the condition is true) and increment increments the control variable.

Control Required Final value of Required


for variable semicolo control variable for semicolo
keyword name n which the n
separator condition is true separator

for ( int counter = 1; counter <= 10; counter++ )

Loop- Increment
Initial value continuation of control
of control condition variable
variable Figure 7.1

Please refer Appendix for related program: Example 9.cpp.

SWITCH MULTIPLE SELECTION STRUCTURE

The switch structure consists of a series of case labels and an optional default case.

Page 8 of 85
(Please refer Appendix for related program: Example 5.cpp).

In the program, the users enters letter grades fro a class. Inside the while header, the
parenthesized assignment (grade=cin.get()) executes first. The cin.get() function reads
one character from the keyboard and stores that character in integer variable grade.
Characters normally are stored in variables of type char, however, an important feature of
C++ is that characters can be stored in any integer data type because they are
represented as 1-byte integers in the computer.

In the program, the value of the assignment grade = cin.get() is compared with the value
of EOF ( a symbol whose acronym stands for “end-of-file”). We use EOF (which normally
has the value – 1) as the sentinel value. However, you do not type the value -1, nor do
you type the letters EOF as the sentinel value. Rather, you type a system-dependent
keystroke combination that means “end-of-file” to indicate that you have no more data to
enter.

System such as Microsoft Windows, end-of-file can be entered by typing

<ctrl-z>

Please refer Appendix for related program: Example 10.cpp.

DO/WHILE REPETITION STRUCTURE

The do/while structure tests the loop-continuation condition after the loop body executes;
therefore, the loop body executes at least once. When a do/while terminates, execution
continues with the statement after the while clause. Note that it is not necessary to use
braces in the do/while structure if there is only one statement in the body; however, most
programmers include the braces to avoid confusion between the while and do/while
structures. For example,

while (condition)

normally is regarded ad the header to a while structure. A do/while with no braces


around the single statement body appears as

do
statement
while (condition);

which can be confusing. The last line – while (condition); - might be misinterpreted by
the reader as a while structure containing an empty statement. Thus, the do/while with
one statement is often written as follows to avoid confusion:

do {
statement
} while (condition);

Please refer Appendix for related program: Example 11.cpp.

Page 9 of 85
BREAK AND CONTINUE STATEMENTS

The break and continue statements alter the flow of control. The break statement, when
executed in a while, for, do/while or switch structure, causes immediate exit from that
structure. Program execution continues with the first statement after the structure.
Common uses of the break statement are to escape early from a loop or to skip the
remainder of a switch structure.

The continue statement, when executed in a while, for or do/while structure, skips the
remaining statements in the body of that structure and proceeds with the next iteration of
the loop. In while and do/while structures, the loop-continuation test evaluates
immediately after the continue statement executes. In the for structure, the increment
expression executes, then the loop-continuation test evaluates. Earlier, we stated that the
while structure could be used in most cases to represent the for structure. The one
exception occurs when the increment expression in the while structure follows the
continue statement. In this case, the increment does not execute before the program
tests the repetition-continuation condition and the while does not execute in the same
manner as the for.

Please refer Appendix for related program: Example 12.cpp & Example 13.cpp.

USER DEFINED FUNCTION

Each program we have presented consisted of function main calling standard library
functions to accomplish its tasks. We now consider how programmers write their own
customized functions.

FUNCTION DEFINITION

Consider a program, with a programmer-defined function square, that calculates and


displays the squares of the integers from 1 to 10 (Please refer Appendix for related
program: Example 14.cpp).

1. Function square is called in main with the expression square (x) in line 11.
2. The parenthesis () in the function call are an operator in C++ that causes
the function to be called.
3. Function square (lines 19-22) receives a copy of the value of argument x
and stores it in the parameter y.
4. Then square calculates y * y (line21).
5. Function square passes the result back to the point in main where square
was called and display the result.

The definition of square (lines 19-22) shows that it uses integer parameter y. Keyword int
preceding the function name indicates that square returns an integer result. The return
statement in square (line 21) passes the result of the calculation back to the calling
function.

Line 4 is a function prototype. The data type int in parenthesis informs the compiler that
function square expects an integer value from the caller.

Page 10 of 85
The data type int to the left of the function name square informs the compiler that square
returns an integer result to the caller.

Another example of function definition can be seen in Example 15.cpp.

INLINE FUNCTION

Definition of inline function cube (Please refer Appendix for related program: Example
16.cpp). Definition of function appears before function is called, so a function prototype is
not required. First line of function acts as the prototype.

FILE SYSTEMS AND DATABASES

CREATING A DATABASE

To create a new blank database, do the following:

1. Click the New toolbar button or choose File | New to open the New File task pane.
Then select Blank Database in the New File task pane.

2. The File New Database dialog box opens as before, where you can enter a name for
the new database and specify the folder in which you want store it. Access opens the
most recently opened folder or, if you are just launching Access, the My Documents
folder. Then it gives a unique to the new database: db1, db2, db3, and so on.

3. After entering a custom name for the new database and opening the folder where you
want to store the database, click Create.

Page 11 of 85

Figure 7.2: Opening the new Database window


SELF-REVIEW EXERCISES (1)

a. Create a database on desktop folder. Save as IKM Besut.

CREATING AND MODIFYING TABLES

The first thing to do when starting a new blank database is to create one or more tables.
To start a new table, do one of the following:

 Click New on the Database window toolbar


 Double-click Create table in Design view
 Double-click Create table by using wizard
 Double-click Create table by entering data

The easiest way to start a new table from a blank table design is to double-click the
Create Table in Design View item in the Tables page of the Database window.

You can also open the New Table dialog box as before and double-click Design View, or
select Design View and click OK. An empty table appears in the table Design window,
ready to add fields as shown in Figure 1.5.

Some new buttons on the Table Design toolbar relate to the task of creating and modifying
a table definition (Please refer Figure 1.6).

Page 12 of 85

Figure 7.3: An empty table design window


Datasheet view Primary key Insert rows Properties

Indexes Delete rows Build

Figure 7.6: Several of these buttons have menu command equivalents on the
View, Edit, or Insert menu.

Adding Fields

To begin adding fields to the table structure, do the following:

1. Click the first row of the field entry area and type the first field name. Field names can
have up to 64 characters, including letters, numbers, and spaces. Don’t begin a field
name with a space, however. You also cannot use any of the characters Access
attaches special meanings to, such as a period, exclamation mark, and brackets.
Using a mixture of uppercase and lowercase letters can help explain the field to the
user, but Access doesn’t differentiate between cases in field names.

2. Choose an appropriate data type from the Data Type drop-down list.

3. Enter an optional description that can provide additional information about the field.
The description appears in the status bar when the field is selected in a datasheet or
form.

4. Move to the Field Properties panel and set any desired properties for each new field,
such as a default value, a custom format, or a validation rule.

Because the most commonly used field type is Text, Access automatically specifies a new
field as a Text field by default. To change it to another type, select from the drop-down list

Page 13 of 85
in the Data Type box (Please refer Figure 1.7).

Figure 7.7: Once you get used to the names of the available data types,
you can simply type the first letter the type name and Access then fills in
the name.
Specifying Field Data Types

Text
The Text data type is the most common data type and can contain any combination of up
to 255 characters and/or numbers. You would use the Text type for storing values that
contain combinations of numbers and letters, such as addresses and job descriptions.
Even when you think the field will contain only numbers, but you aren’t expecting to
perform any calculations with the values in the field, using the Text type is better. For
example, ZIP codes might seem like numbers, but they often contain a dash, which isn’t
considered a number or a leading 0 that would be truncated. In addition, you won’t be
computing the sum or average of all ZIP codes, so using a Text type is more efficient.
Access gives Text fields a default size of 50 characters, but you can reduce the size to 1
or increase it up to a maximum of 255 characters. If you expect the field to contain more
characters than 255, you should consider using the Memo field type instead, which can
contain much more data.

Memo
Use a Memo field to store long, but variable-length, text possibly relating to the other field
data. For example, you could add comments to your employee records about their
efficiency on the job or their skills when dealing with customers. You don’t expect every
record to include memo data, but when one does, the text can vary in size from a few
words to up to 65,535 characters.

Number
Select the Number data type when you plan to sort on the values or used them in
calculations, such as hiding up the labor hours for a plumbing job or the hours worked by
a certain employee during the fall season. If you’re working with dollar sales figures, it’s
better to use a Currency type because you can choose from several monetary display
formats. Currency values also maintain higher precision during calculations.

Currency
Use the Currency type when you want to store monetary values, such as the cost and bid
price of contracted jobs. Currency fields can be used in arithmetic calculations, just like

Page 14 of 85
the Number fields. You have many more ways to specify the display appearance of
Currency fields than Number fields, including how to indicate the negative values.
Currency values are accurate to 15 digits to the left of the decimal point and 4 digits to the
right. Using Currency instead of the Number data type prevents inaccuracies caused by
rounding off the results of calculations to two decimal points.

AutoNumber
When you specify an AutoNumber field, Access guarantees each record in the table has a
unique value in the field, thereby creating a field you can use as a primary key. Access
generates a unique value for the field as you enter each new record. You have a choice of
two types of AutoNumbers: Long Integers and Replication ID numbers. If you choose
Long Integer, you have a choice of how Access generates new values: Increment or
Random. The most commonly used are incremental numbers, which start with 1 and
simply count the records as you add them.

Date/Time
The Date/Time type is most useful when you want to sort records chronologically by the
value in the field. You can also use a Date/Time field in calculations to determine elapsed
time. With the Date/Time data type, you have a variety of ways to display the data as well.
Formatting Date/Time and other data types is discussed in the section “Date/Time Fields.”

Yes/No
The Yes/No field is useful when you want the equivalent of a check mark in your records.
For example, suppose you want to know if a transaction has been posted or a job has
been completed. By default, a Yes/No field appears as a check box in a datasheet, as well
as in forms and reports. You can choose to display Yes or No, On or Off, or True or False.
You can also create your own custom display for Yes/No fields.

OLE Object
When you want to embed or link an object from another source in your table, you can use
OLE object type field. With this type of field, you can acquire data from such objects as an
Excel spreadsheet, a Word document, graphics, sound, or other binary data.

Hyperlink
When you want the field to jump to another location, or to connect to the Internet or an
intranet, store the hyperlink address in a hyperlink field.

Lookup Wizard
The Lookup Wizard creates a field limited to a list of valid values. When you select this
data type, a wizard helps you create the list and attaches it to your table. You can type in
the values you want to use or have the Lookup Wizard consult another table for the set of
valid values. Then, as you enter table data, you can choose the value you want from a
drop-down list. The field inherits the same data type as the primary key field in the lookup
list, which is the value stored in the lookup field.

SELF-REVIEW EXERCISES (7.3)

a. Based on ERD in the previous exercise, create tables for the entities.
b. Set the Data Type as follows:

Table TRAINEE

Page 15 of 85
Field Name Data Type
Tra_Name Text
Tra_MatrixNo Text
Tra_Gender Text
Tra_DOB Date/Time
Tra_Address Memo
Tra_Photo OLE Object
Cou_ID Text

Table INSTRUCTOR

Field Name Data Type


Ins_Name Text
Ins_ID Text
Ins_Gender Text
Ins_DOB Date/Time
Ins_PhoneNo Text
Ins_Status Text
Cou_ID Text

Table SUBJECT

Field Name Data Type


Sub_Name Text
Sub_Code Text
Sub_CreditHour Text
Sub_Status Text

Table CLASS

Field Name Data Type


Sub_Code Text
Ins_ID Text
Group Text
Semester Text
Venue Text

Table COURSE

Field Name Data Type


Cou_Name Text
Cou_ShortNam Text
e
Cou_ID Text

Page 16 of 85
Table REGISTRATION

Field Name Data Type


Tra_MatrixNo Text
Sub_Code Text
Session Text
Repeat Yes/No

Setting Field Properties

Field properties determine how the values in the field are stored and displayed. Please
refer Table 1.0 for detail information.

Property Effect
Specifies the maximum number of characters
Field Size allowed in the field. Default is 50 characters. The
maximum is 255 characters.
Determines the display appearance, such as
Format forcing uppercase or lowercase characters. In a text
field, a default format isn’t specified.
Provides a template for data conforming to a
pattern, such as telephone numbers or Social
Input Mask
Security numbers, and adds literal characters to the
field, if desired. Default is none.
Displays a name other than the field name in
Caption
datasheets, forms, and reports. Default is none.
Automatically enters the specified value in the field.
Default Value
Default is none.
Specifies an expression that checks for invalid data.
Validation Rule
Default is none.
Displays this message if the entered data fails the
Validation Text
validity rule. Default is none.
Indicates this field cannot be left blank. Default is
Required
none.
Differentiates between a blank field and a field
containing an empty string of text (“”). Helpful when
Allow Zero Length
a value is known not to exist (such as a fax
number). Default is Yes.
Indicates the table is indexed on this field. Default is
Indexed
No.
Allows string data that is now stored in Unicode
Unicode Compression format to be compressed to save storage space.
Default is Yes.
IME Mode Sets the IME mode for a field when focus is moved
to it. IME is a program that enters East Asian text

Page 17 of 85
into programs by converting keystrokes into
complex East Asian characters. Default is No
Control.
IME Sentence Mode Sets the type of IME sentence. Default is None.
Recognizes and labels the field as a particular type.
Smart Tags
Default is none.

Table 1.0

Formatting Field Data

When you set a field’s Format property in Design View, Access applies that format to the
values in Datasheet View. Any new controls on forms and reports also inherit the new
formatting. Controls added to the form or report design prior to setting the custom formats
are unaffected.

You can use the following custom formatting symbols with any data type:

 ! Enters characters from left-to-right instead of right-to-left, forcing left


alignment
 (space) Enters a space as a literal character when the SPACEBAR is pressed
 “xyz” Displays the characters or symbols within the quotation marks
 * Fills available space with the character that follows
 \ Indicates the character that follows is to be treated as a literal character.
Often used with reserved symbols and characters
 [color] Displays the field data in the color contained within the brackets. You can
use black, blue, green, cyan, red, magenta, yellow, or white

Other custom formatting symbols are valid only for specific data types, as described in the
following paragraphs.

Text and Memo Fields


Text and Memo fields use the same format settings, some of which are character
placeholders that apply to individual characters and other settings affecting the entire
entry. Here are some examples of using the Text and Memo Format settings:

Format Setting Entered As Displays


@@@@-@@-@@@@ 123456789 123-45-6789
> jimmy JIMMY
< JIMMY jimmy
@\! Hello Hello!

Date/Time Fields
Date/Time fields include seven predefined format settings, in addition to some symbols
you can use to create your own custom formats. Here are the formats Access provides.

Setting Description
General Date (Default) Combination of Short Date and Long Time settings.
If no time, only date is displayed, if no date, only time.

Page 18 of 85
Examples:
5/21/04 3:30:00 PM (US)
21/5/04 15:30:00 (UK)
Uses Long Date Regional setting. Examples:
Long Date Friday, May 21, 2004 (US)
Friday, 21 May, 2004 (UK)
Medium Date 21-May-04
Uses Short Date Regional setting. Examples:
Short Date 5/21/04 (US)
21/5/04 (UK)
Long Time 3:30:00 PM
Medium Time 3:30
Short Time 15:30

Date and Time format settings are specified according to the setting in the Regional
Options dialog box in the Windows Control Panel.

Yes/No Fields
Access automatically displays a default check box control when you specify a Yes/No data
type. Any format settings you make are ignored with this choice. To display values in any
other format, first change the Display Control setting on the Lookup tab to a text box or
combo box, and then you can have some fun formatting Yes/No field values. Access
provides three predefined formats for displaying Yes/No, On/Off, or True/False, but you
can also create a custom format that displays other text for the two values.

To change a Yes/No field Display Control property, open the table in Design View and do
the following:

1. Select the Yes/No field


2. Click the Lookup tab in the Field Properties pane
3. Select Text Box from the Display Control list
4. Return to the General tab to choose the desired display format

The Yes/No custom format contains up to three sections, separated by semicolons. The
first section isn’t used, but you still need to enter the semicolon before entering another
section. The second and third sections specify what to display when the value is Yes and
No, respectively. For example, the following format:

;”Yes, indeed!”[Green];”No, never!”[Red]

displays

Yes, indeed!

in green when the value is Yes, and

No, never!

in red if the value is No.

Page 19 of 85
SELF-REVIEW EXERCISES (7.4)

a. Set the Field Properties for all fields which data type are ‘text’ or ‘memo’ in each table
in IKM Besut database to convert the lowercase into uppercase characters.

Choosing a Primary Key

In a relational database system, being able to gather and retrieve related information from
separate tables in the database is important. To do so, each record in one table must be
unique in some way. The field or fields that contain the unique value is the primary key.
Access neither permits duplicate values in the primary key nor does it permit null values. A
valid unique value must be in the primary key field combination throughout the table.

Setting a Single-Field Key

If your table has a field you’re sure won’t contain any duplicate values, you can use that
field as the primary key. In the table Design View, click the field row you want to use as
the primary key, and then you have three ways to designate the field as the primary key:

 Click the Primary Key toolbar button


 Choose Edit | Primary Key
 Right-click the field row in the upper pane and choose Primary Key from the shortcut
menu

To remove the primary key designation, repeat any one of the previous steps.

To set primary key that combines two or more fields, hold down CTRL while you select
each field.

SELF-REVIEW EXERCISES (7.5)

a. Set the primary key for each table. (Hint: Choose the unique field name that would
identify its table)

Saving the Table Design

Access requires you to save the design before you can switch to Datasheet View to enter
data. To save the table design, click the Save button or choose File | Save. The first time
you save a new table, access prompts you for a name.

The table name can have up to 64 characters in any combination of letters, numbers, and
spaces, but it cannot begin with a space. You can also include characters, except for
those that have a special meaning to Access, such as a period (.), an exclamation point
(!), an accent grave (`), or brackets ([ ]). You also cannot use any control character with an
ASCII value between 0 and 31.

Switching Table Views

Page 20 of 85
If you enter data in Datasheet View and you decide some changes need to be made in the
table structure, you can quickly return to the Design View in one of the following ways:

 Click the View (Design) button


 Choose View | Design View
 If the window isn’t maximized, right-click the Table window title bar and choose Table
Design from the shortcut menu
 If the window is maximized, right-click any empty area in the Table window outside the
datasheet and choose Table Design from the shortcut menu

Use the same methods to switch back to Datasheet View.

Adding Fields

A new field can be added to the bottom of the list of fields or inserted anywhere among the
existing fields. To add one to the bottom, click the first blank field and enter the field
definition. To insert a field among existing fields, click the row below where the new one is
to appear, and then do one of the following:

 Click the Insert Rows toolbar button


 Choose Insert | Rows
 Right-click the row and choose Insert Rows from the shortcut menu

Whichever method you choose, the new blank field row is inserted above the row that
contains the cursor and all the fields below are moved down one row. The insertion point
is in the new row ready to enter the field definition.

If you want to add several new rows at once, select the number of contiguous rows in the
table design equal to the number of new fields you want to insert, and then use one of the
previous methods.

Deleting Fields

When you delete a field from the table design, you aren’t only deleting the field name, but
any data entered in the field. Before deleting a field that contains data, Access warns
you’ll permanently lose the data and asks if you really want to delete the field.

To delete a field, in Design View, click the row selector for the field and do one of the
following:

 Press the DEL key


 Choose Edit | Delete Rows
 Click the Delete Rows toolbar button
 Right-click in the row and choose Delete Rows from the shortcut menu

To delete several rows at once, select them all and delete them as a group.

Changing the Field Order

Page 21 of 85
To change the order of fields in both the stored table and in the Datasheet View,
rearrange them in Design View. To move a field to a new position in the table design, click
the row selector to select the row, and then drag the row selector to move the field to its
new position.

You can move several contiguous fields at once by selecting them all, and then dragging
them as a group. To select more than one, use one of the following methods:

 Click the top field row selector and drag through the row selectors until all are selected
 Click the top field row selector and hold down SHIFT while you click the field row at the
end of the group

Changing a Field Name

To change a field name in Design View, simply type the new name. After changing the
name, you must save the table again.

Changing a Field Type

Changing a field type is a little more complicated if the table already includes data. If no
data is in the table, you can safely change any field data type.

To change a field type, do the following:

1. Click the Data Type column.


2. Click the arrow and select the new data type.
3. Save the table design. If Access displays a warning message, respond No to cancel
the changes or Yes to go ahead and make the changes. If no data is in the table,
Access doesn’t display any warnings.

Copying an existing Table Structure

If you already have a table with a structure similar to what you need now, you can save
time by copying the structure to a new table without the data. Then change the field
names and properties as necessary. To copy the table structure, follow these steps:

1. Select the existing table name in the Database window.


2. Click Copy on the toolbar or choose Edit | Copy.
3. If you want to copy the structure to a different database, close the current one and
open the target database; otherwise, keep the Database window open.
4. Click Paste or choose Edit | Paste to open the Paste Table As dialog box.
5. Enter a name for the new table, choose Structure Only, and then click OK.

Page 22 of 85

Figure 7.8
RELATING TABLES

Using the Relationships Window

To open the Relationships window, choose Tools | Relationships, or click the


Relationships button on the Database toolbar. If no relationships are defined in the current
database, the Show Table dialog box appears in a blank Relationships window.

Relationships are usually drawn between tables, but you can also include queries. To add
the tables you want to relate from the list, do one of the following:

 Double-click the table’s name or select the table and click the Add button
 To select multiple adjacent tables, select the first table to be included, hold down
SHIFT as you select the last table in the list to be included, and then click the Add
button. If the table names aren’t adjacent in the list, hold down CTRL while you select
the names

After you add all the tables you want to work with in the Relationships window, click Close.

The Relationships window shows the field lists of the tables you choose. The lists display
the primary key field, if any, in boldface. Use the scroll bars to see all the fields, or resize a
field list box by dragging the bottom border to see more names or the right border to see
complete field name. You can also drag the field list boxes around in the window for better
viewing.

Figure 7.9: Show Table


dialog box

Page 23 of 85
Figure 7.10: Relationships window

Drawing the Relationship Line

It couldn’t be easier to relate two tables. You simply drag a field (usually the primary key)
from one table and drop it on the corresponding field (the foreign key) in the other table.
The field names needn’t be the same, but they usually need to be the same data type and
contain the same kind of information. If you intend to enforce referential integrity, the fields
must be the same data type. If the fields are Number fields, they must also have the same
Field Size property.

To relate the TRAINEE table to the COURSE table by Cou_ID, do the following:

1. Click the Cou_ID field in the TRAINEE field list and drag it to the Cou_ID field in the
COURSE field list.
2. Drop the linking field into the child table. The Edit Relationships dialog box opens.
3. Verify the field names that relate the tables, and then do one of the following:

 If you want to change the field at either side of the relationship, you can select a
different field from the drop-down field list under the table name
 If you want to add another relationship between the same tables that relates two
different fields, move to an empty row in the grid, click the down button, and choose
from the list for each table
 If you choose the wrong foreign key, choose Cancel in Edit Relationships dialog box
and start over in the Relationships window
 If you type the first few letters of the field name in the Edit Relationships dialog box
grid, Access will fill in the rest for you
 To complete the relationship, choose create and return to the Relationships window

Page 24 of 85
Figure 7.12: Edit Relationships
dialog box

Enforcing Referential Integrity

Referential integrity is a set of rules that attempts to keep a database complete and
without loose ends. No related records can exist without a parent. When you want Access
to enforce the referential integrity rules on the relationship you’re defining, check Enforce
Referential Integrity in the Edit Relationships dialog box. If, for some reason, the tables
already violate one of the rules, such as the related fields not being of the same data type,
Access displays a message explaining the violation and doesn’t apply the enforcement.

When you check the Enforce Referential Integrity option, two options become available
that let you override some restrictions. Check both options.

The Cascade Update Related Fields option lets you change the value in the primary key
field in the parent table and Access automatically changes the foreign key value in the
child table to match. If the primary key in a table serves as a link to more than one table,
you must set the Cascade Update Related Fields property for each of the relationships. If
not, Access displays a message that referential integrity rules that would be violated by
the cascading operation and refuses to delete or update the record.

The Cascade Delete Related Records option enables you to delete a parent record, and
then Access automatically deletes all the related child records. When you try to delete a
record from the parent table of a relationship with this option selected, Access warns you
this record and the ones in related tables
will be deleted. For example, if you
delete an Employee record, Access
automatically deletes all the
records for that employee in the related
tables.

Page 25 of 85
Figure 7.13: Enforcing Referential
Integrity

Figure 7.14: A complete relationships layout between tables

SELF-REVIEW EXERCISES (7.6)

a. Create relationship among tables in IKM database.

Editing a Relationship

To edit an existing relationship, do the following:

1. Open the Relationships window as before.


2. If you don’t see the relationship you want to change, choose Show Table from the
Relationships menu, double-click the missing table, and choose Close.
3. When you see the join line that presents the relationship you want to change, do one
of the following to open the Edit Relationships dialog box:
 Double-click the line
 Right-click the line and choose Edit Relationship from the shortcut menu

4. Make the changes you want, and then click OK.

Page 26 of 85
Deleting a Relationship

To delete a relationship, click the join line to select it and do one of the following:

 Press DEL
 Choose Delete from the Edit menu
 Right-click the line and choose Delete from the shortcut menu

Changing a Table Design from the Relationships Window

To switch to the Table Design view from the relationships window, right-click anywhere in
the table’s field list box and choose Table Design from the shortcut menu. When you finish
changing the table design, save the changes and close the window. You then return
automatically to the Relationships window.

Printing the Relationships

To print the table relationships diagram, do the following:

1. In the Relationships window, right-click in an empty area and choose Show All.
2. When all tables appear in the layout, choose File | Print Relationships.

If you want more precise information about the relationships you established in the
database - including the attributes such as referential integrity and the relationship type -
you can use the Documenter, one of the Access analytical tools.

1. Choose Tools | Analyze | Documenter. The Documenter dialog box opens showing
eight tabs applying to the database objects and the database itself. If you see a
message saying the Documenter isn’t installed, you can have it installed now.
2. When the Documenter dialog box opens, click the Current Database tab, and then
click the Relationships check box.
3. Click OK to print the relationships in table form. A preview of relationships document
appears after a few moments.

Figure 7.15: Documenter dialog box


Page 27 of 85
ENTERING AND EDITING DATA

Entering New Data


When you open a new table, it appears in Datasheet view, ready for data entry. To add a
new record, do one of the following:

 Click the New Record toolbar button

 Click the New Record navigation button

 Choose Edit | Go To | New Record


 Choose Insert | New Record

To navigate among records, use the vertical scroll bar, the navigation buttons at the
bottom of the Datasheet view window, keyboard shortcuts, or the Go To command in the
Edit menu. To move among fields or columns, use the horizontal scroll bar, the TAB or
ENTER keys, or keyboard shortcuts.

When the insertion point moves to an empty field, type in the data. If you specified a
custom format, the entered value adapts to that format when you move to the next
column. If you created an input mask for that field, the mask appears when you enter the
field and before you begin to type the data.

When the table contains many fields, some of them might not always be visible. Instead of
scrolling right and left to enter data in long records, you can use the Go To Field box on
the Formatting (Datasheet) toolbar.

Copying and Moving Data

You can cut or copy items using the Edit menu or the toolbar buttons. You can also
display the Clipboard side pane and use it to copy-and-paste items.

 Click Copy to add the selected item to the clipboard


 Select one item in the clipboard and click Paste
 Click Paste All to paste all the items to the same document

Copying and Moving Within the Same Table

To copy a record within the same table, first select the record you want to copy by clicking
the record selector – the small gray button to the left of the record. Then click the Copy
toolbar button or choose Edit | Copy. This copies the data to the clipboard. Click the
record selector in the record you want to replace, and then click Paste. The new record
contains an exact copy of the original record. If you want to add the copy as a new record

Page 28 of 85
rather than replace an existing one, select the empty record at the bottom of the
datasheet, and then click Paste. To remove the data, once the record is selected, use the
Cut option instead of Copy.

Access tries to save the copied record when you move out of it. If the table has a primary
key or a unique index, Access won’t let you leave the new record until you replace the
duplicate value with a unique one.

To copy or move than one record, select all the records before choosing Copy or Cut.
When replacing records, select the same number of existing records as you placed on the
clipboard, and then click Paste. If you want to append the new records to the table instead
of replacing existing ones, do one of the following:

 Select the new empty row at the bottom of the datasheet and click Paste
 Choose Edit | Paste Append

Copying and Moving from Another table

To copy or move records from another table, select the records in the source table and
choose Copy or Cut. If you choose Cut, you’re asked to confirm you want to delete the
record(s) from the source table. Then switch to the destination datasheet and select the
blank row at the bottom of the datasheet. When you click Paste, the new records are
added to the destination datasheet.

If you want to replace certain records in the destination datasheet with records from
another table, select the records you want to replace before clicking Paste.

To append records from another table to the existing datasheet, choose Edit | Paste
Append. If the source table has more fields than the destination table, the excess fields
aren’t pasted.

Inserting Pictures

An Object linking and Embedding (OLE) object is created by an application outside


Access and can be inserted into an Access table. Objects can be images, sounds, charts,
video clips, or nearly any product of another application. Source applications can include
Word, Excel, sound or video recorders, or an image scanner.

To insert an image in the picture field:

1. Place the insertion point in the picture field and choose Insert | Object, or right-click the
field and choose Insert Object from the shortcut menu.
2. In the Insert Object dialog box, choose Create from File.
3. Type the path and filename of the image file in the File box, or click Browse and look
for the object.
4. After entering the filename, choose OK to embed the picture in the field.

Page 29 of 85
Figure 7.16: Insert Object dialog
box
When you return to Datasheet view, the field now contains the name of the source of the
OLE object. Other entries indicate other types of objects. To see the image, create a form
by clicking New Object: AutoForm. If you see the filename instead of the picture, double
click the filename.

Adding Custom Input Masks

Input masks can be used with Text, Number, Date/Time, and Currency fields. You cannot
create an input mask for a Memo, AutoNumber, Yes/No, OLE Object, or Hyperlink field.
To create an input mask with the Input Mask Wizard, move the insertion point to the field
in table Design view and click in the Input Mask property. Then do the following:

1. Click the Build button (…) at the right of the field’s Input Mask property. The first Input
Mask Wizard dialog box opens where you can select from a list of ten predesigned
input masks appropriate for commonly used fields. The Try-It box shows how the
mask works when displayed in Datasheet or Form view. Access might prompt you to
save the table design before opening the first dialog box.
2. After selecting the mask similar to the one you need, click Next to move to the second
dialog box. In this dialog box, you can make any necessary changes to the mask, such
as changing the placeholder that displays as the fill-in blanks (the default is an
underline character), and then click Next.
3. Choose to store the literal characters with the data, if desired. This uses more disk
space, but the symbols are available when you want to use the value in a form or
report, rather than having to specify them in the field format in the form or report
design.
4. Click Finish to close the wizard.

Page 30 of 85
Figure 7.17: Input Mask
property

Figure 7.18: Input Mask Wizard

Creating Lookup Fields

You can add either type of lookup field in either Design or Datasheet view. If the field
already exists in the table design and you want to change it to a lookup field, you must
change the data type in Design view. To add a new lookup field to a table, do one of the
following:

 In Design view, add a new field row and select Lookup Wizard from the Data Type list
 In Datasheet view, click in the column to the right of where you want the new lookup
field, and then choose Insert | Lookup Column. You might have to expand the menu
list to see Lookup column

Either method starts the Lookup Wizard that displays a series of dialog boxes in which you
specify the details of the lookup field. In the first dialog box, you decide which type of
lookup field to create: a lookup list that relates to a table or query, or a value list you type
in.

If you choose to type in your list of values, the wizard displays a dialog box where you
specify the number of columns you want in the list and enter the values. If you choose to
get the values from another table, the wizard displays several more dialog boxes in which
you do the following:

Page 31 of 85
Figure 7.19
 Select the source table or query from the current database

Figure 7.20
 Select the fields from the table you want to include

Page 32 of 85
Figure 7.21

 Specify how you want the columns to look and whether to hide the primary key in the
lookup table

 Specify which field in the table is the key field


 Enter a name for the lookup field
Figure 7.22

Page 33 of 85
Figure 7.23

Print Table Data

The quickest way to print table data is to click the Print button with the table open or with
the table name selected in the Database window. You can also right-click the table name
in the Database window and choose Print from the shortcut menu.

EXTRACTING INFORMATION WITH QUERIES

Creating Select Queries

As usual, Access gives you a choice of ways to begin a new query design:

 Click the New command button on the Queries page in the Database window
 Click the New Object toolbar and select New Query
 Choose Insert | Query

All three approaches open the New Query dialog box. As you can see, you can call on
wizards for help with several types of queries.

Figure 7.24: New Query dialog box

A query, like a table, can be viewed as a datasheet or a design. The Datasheet view

Page 34 of 85
shows you the data that results when you run the query. The design view is where you
can look at the query structure and make changes to the query design or even create a
new one. The third query view is the SQL view, which shows the SQL statements Access
creates behind the scenes to implement the query. The SQL view has no counterpart with
table objects.

To switch to Design view, click the View toolbar button and choose Design View from the
drop-down list, or choose View | Design View. The Query Design window looks a lot like
the Advanced Filter / Sort window with two sections:

Figure 7.25: Select query in Design view

 The upper pane is the table pane, which displays the field lists for all the tables in the
query
 The lower pane is the Query By Example (QBE) design grid, which shows the
elements of the query design

To create the new query, do the following:

1. Choose New in the Queries tab of the Database window.


2. Select Design View and click OK. The show Table dialog box opens with three tabs
that display a list of Tables, Queries, or Both in the current database.
3. Select any table and choose Add. You can see the field list added to the query table
pane behind the dialog box.
4. Double-click any other table in the Show table list, and then choose Close.
5. Keep the query window open for adding fields to the design grid.

Adding/Removing Fields

To add all the fields in a table to the grid at once, do one of the following:

 Double-click the asterisk (*) at the top of the field list. This method places the table or

Page 35 of 85
query name in the Field row of the column followed by a period and an asterisk – for
example, TRAINEE.*
 Drag the asterisk from the field list to an empty column in the grid. This method does
the same as the previous one
 Double-click the field list title bar to select all the fields, and then drag the group to the
grid. Access places each field in a separate column across the grid in the order in
which they appeared in the field list

To add fields to the grid one at a time, do any of the following:


 Double-click the field name to place it in the first empty column
 Drag the field to an empty column or insert it between filled columns
 Select the field name from the Field row drop-down list. The list in a blank column
contains all the fields in all the tables in the table pane, as well as the table names with
a period and asterisk

Figure 7.27

To delete a field from the grid, click the column selector and press DEL, or choose Edit |
Delete Columns. If you remove the check mark from the Show cell in a column with no
Sort or Criteria entries, the field is automatically removed from the grid the next time you
open the query.

Running and Saving the Query

As you progress with the query design, a good idea is to run the query to see if you’re
getting the information the way you want it. You have three ways to run the query:

 Click Datasheet view


 Click Run
 Choose Query | Run

Save the new query design before adding the sort order and filter criteria.

1. Return to the Query Design view and click Save.

Page 36 of 85
2. Enter a custom name in the Save As dialog box, and then choose OK.

Specifying the Record Order


Setting a sort order in a query design is the same as setting it in an advanced filter. You
choose from the Sort cell list box in the column containing the field you want to sort by. If
you want to sort on more than one field, make sure you have the fields arranged in the
proper order from left to right. They needn’t be adjacent.

Showing Highest or Lowest Values

You use the Top Values box on the toolbar to specify how many or what percentage of the
records to include in the results. The Top Values list includes 5, 25, and 100 records, and
5 percent and 25 percent of the values to choose from, as well as All. You can also type
any percentage or number of values you want directly in the box.

Access selects the records starting from the top of the list, so before you select the Top
Values setting, you must sort (descending) on the field you want to display the highest
values. If you want the lowest values, sort in ascending order. If you specified a sort on
any other field in the query, make sure the sorted field is to the right of the top values field,
so the values will be subordinate to the Top Value list.

Adding Selection Criteria Using Wildcards and Operators


Access has several classes of operators: arithmetic, comparison, concatenation, and
logical.

Operator Description Example Limits Records to


Arithmetic Operators
+ Addition =Cost+50 Values equal to 50 more
than the value in the Cost
field.
- Subtraction =Cost-50 Values equal to 50 less
than the value in the Cost
field.
* Multiplication =Cost*50 Values twice the amount in
the Cost field.
/ Division =Cost/2 Values half the amount in
the Cost field.
\ Integer division =Cosat\2 The integer portion of
values that results from
dividing the Cost field
value by 2.
Mod Modulo division =Cost Mod 2 The remainder of dividing
the Cost value by 2.
Comparison Operators
= Equals =Books or Text value Books.
=”Books”
> Greater than >7/15/03 or Dates later than July 15,
>#7/15/03# 2003.
< Less than <1500 Values less than 1500.

Page 37 of 85
>= Greater than or equal to >=15 Values greater than or
equal to 15.
<= Less than or equal to <=1/1/04 or Dates on or before January
<=#1/1/04# 1, 2004.
<> Not equal to <>NY Values other than NY.
Between… Between two values, Between 100 Numbers from 100 and
And inclusive And 500 500, inclusive.
In Included in a set of In(“Germany”, Either Germany or France.
values ”France”)
Is Null Field is empty Is Null Records with no value in
the field.
Is Not Null Field is not empty Is Not Null Records with a value in the
field.
“” Field contains zero-length =’”” Records with zero-length
string string in the field.
Like With wildcards, matches Like C* Any text value that begin
a pattern with C.
Logical Operators
And Both conditions are True >=10 And Values between 10 and
<=100 100, inclusive.
Or Either condition is True Books or Either Books or Videos.
Videos
Not Not True Not Like AB* All values except those
beginning with AB.

Using a Single Criterion


You add a single selection criterion to a Criteria cell in the query design grid, exactly the
same as in an advanced filter. For example, if you want to see information from the……,
do the following:

Using Multiple Criteria


To apply more than one selection criterion, you combine them with the And or Or
operators, using the same logic as with filters;

 Use And to require both criteria be met to include the record in the query result.
 Use Or to return records that satisfy either expression.

CREATING ADVANCED QUERIES

Parameter Queries
To start a parameter query, start with a normal select query and, instead of entering the
criteria in the Criteria cell, enter the text for the prompt enclosed in brackets ([ ]). The text
you enter becomes the prompt in the dialog box, so be sure it’s informative enough for the
user to know how to respond. You cannot use the field name itself as the prompt, but you
can include it in the prompt text.

CREATING FORM

Page 38 of 85
Forms generally serve to define screens with which to edit the records of a table or query.
In this unit we will see how to create a form, and how to operate it for the editing of
records and changing its design.

Introduction

To create a form we need to position ourselves in the database window with the Form
object selected, if we then click on the button a window opens with the various ways
we have to create a form:

 Design view opens a blank form in design view, and we then need to incorporate the
various objects that we would like to appear in it. This method is not used much as it is
easier and faster to create an autoform, or to use the wizard and afterward modify the
design of the created form to adjust it to our needs. We will see ahead in this unit how
to modify the form design.
 Form wizard uses a wizard that guides us step by step in the creation of the form.
 Autoform consists of automatically creating a new form that contains all the data from
the source table.

According to the type of form that we select (columnar, tabular,...) the form will present the
data in a distinct way, when we click on one of the options, a sample will appear on the left
side with the way in which the data will be presented with this option. E.g Autoform:
columnar presents one record on a screen, meanwhile Autoform: tabular presents all the
records on one screen and every record in a row.

Figure 7.28

Page 39 of 85
In order to use this function we first need to fill out the Choose the table or query where
the object's data comes from: with the name of the source. This will be the only data to
introduce, and once introduced we select the kind of autoform and click on OK button, and
Access does the rest.

 Chart Wizard uses a wizard that guides us step by step in the creation of a graphic.
 Pivot table wizard uses a wizard that guides us step by step in the creation of dynamic
table.

The Form’s wizard

To start the wizard we can do it as describe in the last point or a faster way would be from
the Database window with the Forms object selected, by double clicking on the Create
form using wizard option.

Figure 7.29

The first window of the wizard appears:

Page 40 of 85
Figure 7.30

In this window we are asked to introduce the fields to include in the form.

Firstly we select from the Table/Queries box the table or query that we are going to get the
data from, this will be the form source. If we want to extract data from various tables it
would be better to first create a query to obtain this data and then select this query as the
form source. Next we will select the fields to include in the form by clicking on the field and
then the button or simply double click on the field. If we selected the wrong field click
on the button and the field will be removed from the selected fields list. We can
select all the fields at the same time by clicking on the button or deselect all the
fields at once using the button .

Next we click on the Next> button and the window seen in the following example will
appear...

Page 41 of 85
Figure 7.31

In this screen we select the data distribution within the form. By selecting a format it will
appear on the left side the way it will be seen in the form. Once we have selected the
distribution of our choice click Next and the following window will appear:

Figure 7.32
In this screen we select the forms style, we can select between the various defined styles
that Access has. By selecting a style it will appear on the left side as it will in the form.

Once we have selected a style of our choice we click on the Next button and the last
screen of the forms wizard will appear.

Figure 7.33

In this window we are asked for the title of the form, this title will also be the name
assigned to the form. Before clicking on the Finish button we can choose between:

 Open the form to view or enter information, in this case we will see the result of the
form ready for the editing of data, e.g.:

Page 42 of 85
Figure 7.34
 Modify the form's design, if we select this option the Form design view will appear
where we can modify the aspect of the form, e.g.:

Figure 7.35

Editing Data in a Form

To edit the data of a table using a form, we need to open the form by positioning ourselves
in the Database window with the Forms object selected and click on the button, or
simply double click on the name of the form in the Database window.

The source data of the form will appear with the appearance defined in the form (Form
view). We can then search for data using the navigation buttons we know

, replace values, and modify it as if we were in


the Datasheet view of a table, the only thing that changes is the appearance of the screen.

The Form Design View

The form design view is that which allows us to define a form, here we need to indicate to
Access how to present the source data in the form, and here we can use the controls we
will see ahead.

 To enter into the design view we need to position ourselves in the Database window

Page 43 of 85
with Forms selected, and then click on the button.

The Form design window will appear:

Figure 7.36

 The area consists of three sections:

\The Form Header section, here we put what we wish to appear at the beginning of the
form.
The Detail section, here the source records of the form appear, either various records or
one per screen, depending on the type of form. Even though various records are
visualized on one screen, we need to indicate the design corresponding to just one record
in the Detail section.

The Form Footer section, here we need to put what we want to appear at the end of the
form.

Using the View menu, and then the option Form header/Footer option we can close or
open the header and footer.

Page 44 of 85
Figure 7.37
The mark to the left of the option indicates to us whether the sections are open or closed,
if we remove the sections we lose all the controls associated with them.

To open them we just need to select the option again.

 Around the design area we have various rulers that permit us to measure the
distances and the controls, we also have available to us a grid that helps us to place
the controls within the design area.

To hide or see the ruler or the grid we have the Ruler and Grid options in the View menu,
as we can see in the example above.

The Form Design Bar

If you have entered into Form design and the bar does not appear, you can make it
appear from the View menu, Toolbars, Form design option. Next we will explain the
various buttons that make up this bar.

The first allows us to pass from one view to another, if we drop down this menu we
can select between Design view as we are describing at present, Form view which

Page 45 of 85
presents the source data to us in the way we defined in the design view, and the
Datasheet view which we already know, the other views do not enter as part of our
course.

Figure 7.38

 The Save button allows us to save the changes we are making without exiting the
form.
 The File Search button allows us to search for archives.
 After this we have the Print and Print preview (to see the effect before sending
the form to the printer).
 Later we have the Cut , Copy , Paste , and Copy Format buttons to apply
these same actions to the controls of our form. In order for the Cut, Copy, and Copy
format options to be available we first need to select the control/s which we want the
action to apply to. E.g., select the control to copy, click on the Copy button, position
yourself over the area where we want to copy to and click on the paste button.
 The Undo and Redo buttons are to undo the previous actions performed if
we have made a mistake or to redo them after undoing them.
 To insert a hyperlink we have the button.
 The next button makes the Field list box appear or disappear, here; all the data
source fields appear and are easier to add into the design area as we will see ahead.
 The button makes the Toolbox appear or disappear, here all the control types
appear and are easier to add into the design area as we will see ahead.
 With the Autoformat button we can change our form's aspect with one click to a
different predefined format; these are the same styles that appear with the wizard.
 All forms have an associated code page in which we can program certain actions
using the VBA language (Visual Basic for Applications), this code page can be
accessed by clicking on the button.
 With the button we can make the Properties dialog appear or disappear of the
selected control.
 The button starts up the expression, or macros or code builder.
 If we want to go to the Database window we have the button.
 To create a new table, query, form, macro, etc... without exiting our form we can use
the button, on dropping down we need to indicate what type of object we want to

Page 46 of 85
create in the database.
 Finally we can access the Access help by clicking on the button.

The Toolbox

Figure 7.39
To define how the information within a form will appear, and in what format it will be, we
use controls. A control is nothing more than an object that shows data, performs actions,
and/or is used as decoration. E.g., we can use a text box to show data, a command button
to open a form or report, or a line or a rectangle to separate or group controls in order to
make them more legible. In the Toolbox we have a button for each type of control that can
be added to a form.
If the Toolbox does not appear, click on the button on the toolbar.

If we want to create various controls of the same type we can block the control by double
clicking on it (it will appear enclosed in a darker line), as from this moment we can create
all the controls we want of this type without having to double click every time. To unblock,
all we need to do is click on the button.

There is a wizard that will help us to define the control, to activate it wizard click on
button.

The Toolbox includes the following types of controls:

 A Label serves to visualize a fixed text, text that we write directly into its control or
Caption property.
 A Text box is usually used to present data stored in a source field of the form. This
type of text box is called a dependant text box because it is dependant of the data in
one specific field, and if we edit data in the Form view we will be changing the data at
the source. Text boxes can also be independent, e.g. to represent the results of a
calculation, or to accept the entry of a users data. The data in an independent text box
is not stored anywhere. In the Control source property we have the name of the
associated table's field (when it is dependant) or a calculation formula if we want it to
present the result to us in this case the formula needs to be preceded by a = sign.
 An Option Group is used to present a limited group of alternatives. A group of
options makes it easier to select a value as the user only needs then to click on the
value he requires. There should only be a few options, otherwise it would be better to
use a list box or a combo box instead of an option group.

Page 47 of 85
 When we insert a group of options the wizard will appear to help us to define the
group.
 The Toggle button is usually used to add a new option to an existing Option Group;
it can be used to present a Yes/No field; if the field contains a Yes value the button will
appear depressed.
 The Option button is usually used to add a new option to an existing Option Group,
it can be used to present a Yes/No field; if the field contains a Yes value the button will
appear like this , if not , like this .
 The Check box is usually used to add a new option to an existing Option Group, it
can be used to present a Yes/No field; if the field contains a Yes value the button will
appear like this , if not , like this .
 The Combo box . In many cases it will be easier to select a value from a list than to
remember it in order to type it. A list of possibilities also helps to assure that the value
introduced is correct. If we do not have sufficient space to show the list at all times the
combo box is used as it shows only one value (that which is associated with the
control), and if we want to see the list we can drop it down with the arrow to the right.
When we add a combo box to the design area the wizard will open to help us to define
the control.
 The List box . The difference between the combo box and the list box is the list
appears visible at all times in a list box. Like a combo box, a list box can also contain
one or more columns that can appear with or without headers. When we add a list box
to the design area the wizard will open to help us to define the control.
 The Command permits the execution of an action with simply a click, e.g. to open
another form, to delete a record, to run a macro, etc... On clicking the button it does
not only execute the corresponding action, but the button also appears depressed and
then released. It also has an associated wizard that permits us to create buttons to
perform more than 30 different predefined actions.
 The Image is used to insert images into the form; this image does not vary on
changing the record.
 An Unbound object frame is used to insert controls, e.g. a sound, a Word
document, a graphic, etc... These controls will not vary when we change the record.
 A Bound object frame is used to insert an image or other object that will change
from one record to another.
 A Page break does not have any effect on the Form view, but rather on the preview
and at the moment of printing.
 The Control tab is used when we want to present many fields for each source
record but they do not fit on one screen and we want to organize them in various tabs.
 We can also add a Subform . A subform is a form that is inserted into another. The
primary form is called the principal form, and the form within this is called the subform.
A form/subform combination is often referred to as a hierarchical form, a
principal/detail form, or a principal/secondary form. Subforms are very effective when
we want to show the data of a table or query in relation to another. E.g., we can create
a form to show the data in the Courses table with a subform to show the students
recorded in this course.
 The principal form and the subform of this type are linked, so that the subform will only

Page 48 of 85
present those records that are related with the actual record of the principal form (that
the subform will only show those students that are recorded in the active course).
 A Line is used to add a line to the form.
 A Rectangle is used to add a rectangle to the form.
 Finally, we can add more complex controls with the button.

Working with Controls

 Selecting controls.

To select a control just click on it. When a control is selected it appears enclosed in some
boxes, we call these boxes movement controllers (the bigger) and size controllers (the
smaller) as we can see in the image below.

To select various controls we can click on one of the controls to select, maintain
depressed Shift key and click on each one of the controls to select.

If we want to select various adjacent controls there is an easier way: left click on the
mouse over the background of the design area and without letting go drag it, we see that a
box appears in the design area, and when we release the mouse button all the controls
that enter into this box will remain selected (it is not necessary for the control to be entirely
in the box).

 Adding controls

To add a new source field to a form, the fastest and easiest way is to open the Fields box
(if not already open) by clicking on the button on the toolbar. All the source fields will
appear in this box. Next click on the field you want to add and drag it to the place in the
form where you want it to appear. Access will automatically create a tag with the name of
the field and an associated text box.

If we want to add another type of control like an image, open the Toolbox, click on the type
of control that we want to add, and let go of the mouse button, we see that the cursor has
taken on a different form. We now position ourselves in the area of the form where we
would like to define the control, left click and maintaining, drag the mouse until we have
the desired size.

 To move a control, we select the control and move the mouse a little until the cursor
takes on the form of a hand. At this moment click and maintain, dragging the control
into its final position. When a control is moved the label is also selected and moves
with the control.

To move only the label, position the cursor over its movement controller, and when the
cursor takes the form of an index finger drag it.

Page 49 of 85
We can move the control without its tag in much the same way, but the index finger needs
to be over the movement controller of the control.

To move various controls at the same time, we select and move one of them and they will
all move the same way.

 Changing the size of the controls

To change the size of a control select it so that the size controllers appear, next move the
mouse over one of the size controllers, and when the cursor takes the form of a double
arrow, left click, maintain, and drag until the control has the desired size.

To change the size of various controls at the same time, we select and change the size of
one of them and they will all change the same way.

 To align various controls, we can move them one by one, guiding them through the
box, but we have an easier method in the Format menu. We select the controls to
align, drop down the Format menu, then the Align menu and select the option
according to how we choose to align the controls, to the left, right, up, down, and to
grid. To see the effect of every option we have a diagram to the left of the option.

Figure 7.40

 Adjusting the size of the controls

If we want various controls to be the same size to leave our form more attractive we have
a very useful tool, the Size option in the Format menu.

We proceed in the same way as with aligning controls, selecting the controls we want to

Page 50 of 85
adjust, drop down the Format menu, then the Size menu, and select the most adequate
option.

Figure 7.41

We can select To Fit, this makes the control the correct size so that all of its contents will
fit.

To Grid: adjusts to the grid.


To Tallest: all contols take on the tallest height.
To Shortest: all the controls take on the smallest height.
To Widest: all the controls take on the largest width.
To Narrowest: all the controls take on the narrowest width.

When we want to align and leave controls at the same size it is best to first adjust the size
and then aline them up, as the aligning is sometimes lost when the sizes are adjusted.

 Adjusting the space between controls

If we want to change the distance between controls, apart from moving them freely in the
design area, we can use the Format menu options.

We select the controls that we want to adjust, drop down the Format menu, and in the
Horizontal spacing menu we select the most adequate option, leaving it with the same
space between controls (Make equal), increasing the space between the selected controls
as shown in the image to the left of the option (Increase), or reduce the space (Decrease).

Page 51 of 85
Figure 7.42

We can do the same with the vertical spacing, selecting the controls that we want to
adjust, drop down the Format menu, then in the Vertical Spacing menu we select the most
adequate option for us, leaving it with the same space between controls (Make equal) as
shown in the image to the left, increasing the space between the selected controls
(Increase), or reduce the space (Decrease).

Figure 7.43

CREATING REPORT

Reports are generally used to present the data of a table or query in order to print them.
The basic difference with reports is that the data can only be visualized or printed (it can
not be edited) and the information can be grouped and totals extracted by group more
easily.

In this unit we will learn how to create a report using the wizard, and how to change its

Page 52 of 85
design once created.

Introduction

To create a form we need to position ourselves in the Database window with the Reports
object selected, if we click on the button a dialog box will open with the different
types of reports that we can create.

 Design view opens a blank report in design view and we then need to incorporate the
different controls that we want to appear within it. This method is not usually used as it
is both easier and more comfortable to create an autoreport or to create a report using
the wizard, and afterwards to edit the design of the report to suit our particular needs.
Ahead in this unit we will see how to edit the reports design.

Figure 7.44
 The Report wizard uses a wizard to guide us step by step through the creation of the
report.

 Autoreport consists of automatically creating a new report that contains all the data of
the source table or query.

The data will be presented differently depending on the type of report chosen, and when
we click on one of the options a model will appear on the left. E.g Autoreport: columnar
presents each record on one page while Autoreport: tabular presents various records on

Page 53 of 85
the same page with a record in each row.
In order to be able to use this option we first need to fill in the Choose the table or query
where the object's data comes from: box with the name of the report's source. This will be
the only data that we need to introduce, and once it has been introduced we select the
type of autoreport and click on the OK button, Access will do the rest.

 The Chart wizard uses an assistant that guides us step by step through the creation
of a graphic.

 The Label wizard uses an assistant that guides us step by step through the creation
of labels.

The Report Wizard

To start the wizard we can use the method explained in the previous point or a faster and
easier method would be from the Database window with the Reports object selected to
double click on the Create report by using wizard option.

Figure 7.45
The wizard's first window will appear:

Page 54 of 85
Figure 7.46
In this window we
are asked to
introduce the
fields to be included in
the report.

Firstly we select
the table or query
from the
Tables/Queries
box where it should extract the data from, this will be the report source. If we want to
extract data from various fields it would be best to create a query to obtain the data and
then to use this query as the source of the report.

Next we select the fields by clicking on the field and then on the button, or simply
double clicking on the field.
If we make a mistake we click on the button and the field will be removed from the list
of selected fields.

We can select all the fields at the same time by clicking on the button, or deselect all
at the same time by clicking on the button.

Click on the Next> button and the next window will appear...

Page 55 of 85
Figure 7.47

In this screen we select the grouping levels within the report. We can group the reports by
way of various concepts, and with each concept add a group header and a footer, and in
the group footer we will normally see the group total.

To add a grouping level click on the field by which we want to group and click on the
button (or double click directly on the field).

A diagram will appear to the right indicating the structure that our report will take on, and
in the central zone the fields that are seen for every record will appear. In our example a
group by city will appear at the top and a group by postal code will appear at the bottom.

To remove a grouping level click on the header corresponding the group and click on the
button.

If we want to change the order of the defined groups we use the button, the upward
arrow will move us up a group, and the downward arrow will move us down a group.
 
With the button we can refine the grouping. Click on this button and the
following screen will appear.

Figure 7.48

The different groups that we have defined will appear in this box, and for every group that
we have the field that defines the group in Group-level fields:, and in the drop down list of
the Grouping intervals: we can indicate whether it should use the complete value
contained in the field to group, or use the first letter, the first two letters, etc... After clicking
on the OK button we return to the previous screen.

Once we have the grouping levels defined we click on the Next> button and we go to the
next window.

Page 56 of 85
Figure 7.49
In this screen we can choose to sort the fields into up to four sort fields. We select the field
by which we choose to sort the records that will appear in the report and whether we want
it in ascending or descending order, in order to select descending we click on the
Ascending button and it will change to Descending.

We can select a different order in each of the sort fields.


This screen also allows us to add totals in an almost automatic way, if we want to add
lines of totals we need to click on the button and the Summary options
dialogue box will appear:

Figure 7.50

A list of the numeric fields that we have in the repot will appear in the dialogue box, and
also the summary functions that can be selected to calculate some total. In order for the
sum of a field to appear we only need to select the box in the Sum column found in the
field row. We can select various totals in this way.

If we activate Detail and summary in the Show section, the lines of details (the source
records) will appear as well as the lines of totals. If we select the Summary only option the

Page 57 of 85
detail lines will not appear.

If we select the Calculate percent of total for sums box it will add a percentage total that
represents the calculated sum over the total of all the records. E.g. if we acquire the sum
of hours for a group, this percentage will be the percentage that represents the hours of
the group within the total hours of all the groups.

Once we have filled in the corresponding options we click on the OK button to go to the
wizard’s next screen.

To continue with the wizard we click on the Next> button and the following window will
appear.

Figure 7.51

In this screen we select the type of data layout within the report. By selecting a distribution
the aspect that the report will take with this distribution will appear in the diagram to the
left.

In the Orientation section we can select from either a Portrait or a landscape printing
(oblong).

Page 58 of 85
With the Adjust the field width so all fields fit on a page the wizard will generate the fields
in this way.

We then press the Next> button and the following screen will appear:

Figure 7.52

In this screen we select the type of style we would like our report to have, we can select
from the various defined Access styles. By selecting a style the aspect that this report will
take with this style will appear in the diagram to the left.

Once we have selected a style we click on the Next button and the wizard’s last screen
will appear.

Figure 7.53

In this screen we are asked the title of the report which will also be the name assigned to

Page 59 of 85
the report.

Before clicking on the Next button we can choose>

 Preview the report; in this case we will see the result of the report for the printing.
 Modify the report's design, if we select this option the Form design window will appear
where we can modify the aspect of the report.

The Report Design View

It is the design view that allows us to define the report, here we indicate to Access how it
should present the source data of the report, and here the controls serve us in much the
same way as when we design a form.

 To enter into the design view we need to position ourselves in the Database window
with reports selected and then to click on the button.

The design window appears:

Figure 7.54

Page 60 of 85
 The design area is normally made up of five sections.

The Report header section, here we put what we would like to appear in the beginning of
the report.

The Page header section, here we put what we would like to appear at the beginning of
each page.

The Detail section, here all the source records of the report will appear, either various
records or just one per page - depending on the report. Even if various records are seen
on a page, we need to indicate the design corresponding to only one record in the Detail
section.

The Page footer section, here we put what we would like to appear at the end of each
page.

The Report footer, here we put what we would like to appear at the end of the report.

We can delete the headers and footers from the View menu, Page Header/Footer and
Report Header/Footer.

Page 61 of 85
Figure 7.55

The tick to the left of the option indicates to us whether the sections are open or closed,
and if we remove a section we also loose all the controls associated with it.

To open them we need to go back and select the option.

 We have rulers around the design area to help us measure the distances and the
controls. We also have a grid available with which to place the controls within the
design area.

To see or hide the rulers or the grid we have the Grid and Ruler options from View menu,
as we can see in the previous image.

The Report Design Bar

If you have entered into the form design and this bar does not appear you can make it
appear from the View menu, then Toolbars, and then Report design.

Next we will describe the various buttons that make up this bar.

 The first one allows us to go from one view to another, and if we drop down the
menu we can select from Design view which we are explaining now, or Print Preview
which presents the source data of the report in the way it will be printed, or the Layout
preview which allows us to quickly examine the design as it will only include one
sample of the report's data. If the report is based on a query that needs parameters it
is not necessary to type any value, we only need to click on the OK button.

Page 62 of 85
Figure 7.56

 The Save button allows us to save the changes made in the design without exiting
the report.
 The Search button allows us to search for files.
 We then have the Print button with which to send the report to the printer, and Print
preview to see the report before sending it to the printer.
 We then have the Cut , Copy , Paste , and Copy format buttons to apply
these same actions to the controls in our report. In order for the Cut, Copy, and Copy
format to be activated we need to first select the control/s onto which we wish to apply
the action. E.g. select the control to copy, click on the copy button, then position the
cursor in the area where we want to leave the copy and click on the Paste button.
 The Undo and Redo buttons are for undoing the last action if we made a
mistake, or redoing an action that we have undone.
 To insert a hyperlink we have the button.
 The next button makes the list of field’s box appear and disappear, in which all the
source data fields appear in order to make them easier to add to the design area as
we will see ahead.
 The button makes the Toolbox appear or disappear in which all the types of
controls appear in order to make them easier to add to the design area as we will see
ahead.
 The button allows us to modify the group levels as we will see ahead.
 With the Autoformat button we can change the aspect of our report to a predefined
design from Access with just one click; these are the same styles that appear in the
report wizard.
 All reports have an associated code page in which we can program various actions
using VBA language (Visual Basic for Applications), this code page can be accesses
by clicking on the button.
 With the button we can make the Properties box of the selected control appear or
disappear. The report's properties are much the same as those of a form.
 The button starts the expressions, or macros or code generator.
 If we want to go to the Database window we have the button.
 To create a new table, query, report, macro, etc... without exiting our report we can
use the button, on dropping it down we can select the type of object we want to
create in the database.
 And finally we can access the Access help by clicking on the button.

Page 63 of 85
The Toolbox

Figure 7.57

To define what information should appear in the report, and in what format it should be,
the same controls can be used as in a form although some controls for example the
command buttons are more appropriate for a form.

In the Toolbox we have a button for each type of control that can be added to the report.
If the Toolbox does not appear click on the button on the toolbar.

When we want to change various controls of the same type we can block the control by
double clicking on it (a dark line will appear around it). As from this moment you can
create all the controls of this type that you want without having to double click on the
corresponding button every time. To remove the block we click on the button.
The box contains the following types of controls:
 The Label serves to visualize a fixed text, text that we type directly into the control
or in its Caption property.
 The Text box is used mostly to present a data stored in a source field of the report.
This type of textbox is called an Dependant textbox because it depends on the data
from one field. Textboxes can also be independant, to present the results of a
calculation for example. In the Control source property we have the field of the table
that is associated (when it is dependant) or the formula of thr calculation when we
want it to present the result of this calculation, in this last case we need to preceed the
formula with a = sign.
 The Options group is used to present a limited combination of alternatives. It is
usually used more for forms, for more detail revise the forms unit.
 The Alternate button is usually used to represent a Yes/No type field, if the field
contains the Yes value the button will appear depressed.
 The Option button is usually used to represent a Yes/No type field, if the field
contains the Yes value the button will appear like this , if not it will appear like this .
 The Verification box is usually used to represent a Yes/No type field. If the field
contains the Yes value the box will appear like this , if not it will appear like this .
 Combo box , Listbox , Options group , Command button and Tab control
. These are usually used more in forms, for more detail revise unit 11.
 Image control to insert images into the report, this image will not change when
changing the record.
 Unbound object frame is used to insert controls like a Word document, a graphic,

Page 64 of 85
etc... They will be controls that do not change when changing a record.
 Bound object frame is to insert an image or an object that will change from one
record to another.
 Page break , is used to force a new page even if you have not reached the end of
the page.
 We can also create a subform . A subreport is a report that is inserted into another.
The primary report is called the principal report , and the report within the principal
report is called the subreport. A report/subreport combination is often called a
hierarchical report, principal/detail report or principal/secondary report.
 Line to add a line to the report.
 Rectangle to add a rectangle to the report.
 And finally we can add more complex controls with the button.

We see that the management of controls in reports is identical to the controls of a form., if
you have any doubt about how to add a control, how to move it, copy it, change its size,
how to adjust its size, or aligning the various controls revise the previous unit.

Printing a Report

Printing a report can be done in various ways.

 Printing directly

If we are in the Database window:

Select the Report tab. Click on the name of the report that we want to print to select it. We
click on the button on the toolbar, the report is sent directly to the printer. In this case
all of the pages in the document will be printed with the options defined at that moment.
Before sending the printing to the document it is convenient to check the defined options
at that moment, and for this we need to open the Print dialogue box.

 Opening the Print dialogue box

If we are in the Database window:

Select the Report tab. Click on the name of the report that we want to print to select it. If
we drop down the File menu and select the Print... option the Print dialogue box will open
in which you can change some of the parameters in the printing as we will explain to you
next:

Page 65 of 85
Figure 7.59
If we have various printers connected to the computer (as we often do when they are
network printers), dropping down the Name: combo box we can select the printer to which
we want to send the printing.

In the Print Range section we can specify whether we want to print the whole report (All)
or just a few pages.
If we only want to print a few pages we can specify the initial page of the interval to print in
the from: box, and in the To: box specify the final page.
If we have records selected when we open the dialogue box we can select the Selected
Record(s) option to print only these records.

In the Copies section we can specify the Number of Copies: to print. If the Collate option is
not selected then it will print a full copy and after that another copy, while if we activate the
Collate option it will print the copies of each page together.

The Print to File option allows us to send the result of the printing to a file in the hard drive

Page 66 of 85
instead of sending it to the printer.
With the Properties button we can access the printer properties window, this window will
change depending on the model printer we have, but will allow us to define the type of
printing e.g. in color or black and white, in high quality or draft copy, the type of paper we
use, etc...

With the Setup ... button we can configure the page, change the margins, print various
columns, etc...

And lastly we click on the OK button and the printer will start. If we close the window
without accepting, nothing will be printed.

 Opening a report in Previous view.

To check whether the printing will come out well it is convenient to open the report
previously on the screen to check if it is ok to go ahead and send it to the printer. To open
a report in preview from the Database window we need to follow these steps:

With the Reports object selected, click on the name of the report to select it.
Next we click on the button and the report preview will open.

The Preview Window

Figure 7.60

In this window we see the report in the way that it will be printed.

To pass over the various pages we have a scroll bar in the lower part of the screen with
the buttons that we know already to go to the first page, to the next page, to a specific
page, to the previous page or to the last page.

Page 67 of 85
At the top we have a toolbar with buttons that are already familiar to us:

 to go to design view
 to send the report to the printer
 to go to the Database window
 to create a new object
 to access help.
 the magnifying glass allows us to draw near or draw away from the report.
 allows us to visualize a whole page on the screen.
 reduces the size of the report in order to see two pages of the report on the same
screen.
 allows us to see up to six pages on the screen at the same time.
 adjusts the size so that a whole page can be seen on the screen, and if
we drop down the menu we can select a zoom porcentage to see the page closer or
further, it has the same function as the magnifying glass but allows more sizes.
 opens the Page setup window where we can change the margins, the
orientation of the paper, etc...
 sends the report to a Word document, dropping down the box we can select to
send it to various Microsoft applications, Excel for example.
 will close the preview without sending the report to the printer.

Sorting and Grouping

As we have already seen, with the wizard's help we can define grouping levels for the
records in the report and extract a special heading or line of totals for each group; we can
also define a determined order for the records that appear in the report.
To define the order of the records, create a new grouping level or modify the levels that
we have already defined in an already defined report, we open it in design view and click
on the button on the toolbar.

The Sorting and grouping dialogue box will open as shown below.

Page 68 of 85
Figure 7.61

In the Field/expression column we indicate the columns which we want to sort or group
and the columns that serve to define groups appear with a symbol to their left.
Normally the name of the column is put, but on occasions we can type an expression e.g.
if we want to group the records of a date field by month, we put the expression
=month(datefield). The expression always needs to be preceded by an = symbol.

The order into which we put the various fields is important. In the previous example we
type State, then City, and finally Zipcode, which means that the records will first be
grouped by State and within the same state the courses will be sorted by City, and then
within the same city will be sorted by zipcode.

We can create up to ten grouping levels, and these levels will be added (one within
another) in the same order as what they appear in the Sorting and Grouping box.

Figure 7.62

In the Sort order column we define the type of order that we want for each field, it can be
in Ascending (in alphabetic order if the field is text type, least to most if the field is
numeric, and oldest to most recent if it is a date field) or Descending, in inverse order.

In the bottom part we have each grouping and sorting columns properties.
The Group header property is where we indicate whether we want to include a group
header; it will contain all the data we want to print only when a group starts. If you change
the property to Yes you will see that a new section appears in Report design window for
the group header.

In the Group footer property we indicate whether we want to include group footer, and it
will contain all the data that we want to print only when the group ends and is normally
used to print the group totals. If you change the property to Yes you will see that a new
section appears in the report design window for the group footer.

Page 69 of 85
In the Group on property we can choose between .

If we select Each value, it will sort the records in the report by field, and every time the
field value changes it will end the group and start a new group of values. If we select
Prefix Characters, in the Group interval property we put a number of characters, and it will
group by n first characters in the field.

The Group interval property serves to indicate a number of characters if we have the
Group in property with a Prefix Characters value.

It also serves to form groups of a fixed number of records e.g. if we want to form groups of
five records, we put Each value in the Group on property and we put 5 in the Group
interval property.

And lastly we have the Keep together property where we can choose between

If we select Whole group it will try to write the group header, the detail section, and the
group footer on the same page, i.e. if after the records of the first group have been printed
and there is half a page left empty but the second group does not fit in this space, it will
skip the page and start the new group on a new page.

If we select With First Detail it will only print the group header if it can also print the first
detail record.

If we select No, it will be printed without maintaining the group header, the detail section,
and the group footer on the same page.

THE RELATIONAL DATABASE MODEL

THE WORLD OF RELATIONAL DATABASE

When you use a computerized database management system such as Access, the
database is called relational. The principle behind a relational database is this: the
information is divided into separate stacks of logically related data, each of which is stored
in a separate table in the file. Tables are the fundamental objects at the heart of a
relational database. They form the active basis for the information storage and retrieval
system.

Once the information is arranged in separate tables, you can view, edit, and delete

Page 70 of 85
information with online forms; search for and retrieve some of or all the information with
queries; and print information as customized reports.

In Access, the term database is more precisely used to define the collection of objects that
store, manipulate, and retrieve data. These components include tables, queries, forms,
reports, pages, macros, and modules.

DATA MANAGEMENT AND DATABASE

Data management is a discipline that focuses on the proper generation, storage, and
retrieval of data.

Typically, efficient data management requires the use of a computer database. A


database is a shared, integrated computer structure that houses a collection of:

 End user data, that is, raw facts of interest to the end user.
 Metadata or data about data, through which the data are integrated.

The metadata provide a description of the data characteristics and the set of relationships
that link the data found within database. In a sense, a database resembles a very well-
organized electronic filing cabinet in which powerful software, known as a database
management system, helps manage the cabinet’s contents.

DATABASE MANAGEMENT SYSTEM (DBMS)

A database management system (DBMS) is a collection of programs that manages the


database structure and controls access to the data stored in the database.

Examples of DBMS software are:


 Microsoft Access
 Oracle
 MySQL

Figure 1.1 illustrates the concept that the DBMS stands between the database and the
user(s). In effect, the DBMS serves as the intermediary between the user and the
database by translating user requests into the complex code required to fulfill those
requests. The DBMS hides much of the database’s internal complexity from the
application programs that use the database. The application program might be written by
a programmer, using a programming language such as COBOL, or it might be created
through a DBMS utility program, such as Microsoft Access.

DATABASE DESIGN

Keep in mind that the DBMS is the database software you buy commercially; you do not
have the option of making design changes to it. Therefore, when we speak of database
design, we mean the design of the database structure that will be used to store and
manage data, rather than the design of the DBMS software. Once the database design is
completed, the DBMS handles all the complicated activities required to translate the
designer’s view of the structures that are usable by the computer.

Page 71 of 85
Why database design is important?
A good database does not just happen; the structure of its content must be designed
carefully. In fact, database design is such a crucial aspect of working with databases.
Even a good DBMS will perform poorly with a badly designed database.

A poorly designed database is likely to become a breeding ground for redundant data, that
is, unnecessarily duplicated data.

A database contains redundant data when the same data about the same entity are kept
in different locations. (An entity is a person, place, or thing about which data are to be
collected and stored). For example, data redundancy exists when a customer’s telephone
number is stored in a customer file, a sales agent file, and an invoice file. If the customer’s
phone number changes, the correction might not be made in all the locations where it
occurs.

Therefore, the existence of redundant data can produce uncorrected data entries, and you
probably won’t know which value is the correct one.

DATABASE SYSTEM COMPONENTS

The term database system refers to an organization of components that define and
regulate the collection, storage, management and use of data within a database
environment. From a general management point of view, the database system is
composed of the five (5) major parts: hardware, software, people, procedures, and data.

i. Hardware

Hardware refers to all the system’s physical devices. The database system’s main and
most easily identified hardware component is the computer, which might be a
microcomputer, a minicomputer, or a mainframe computer. The hardware also includes all
of the computer peripherals such as keyboards, mice, modems, printers, and electronic
devices that are used to connect two or more computers, thereby producing a computer
network.

ii. Software

It takes three types of software to make the database system function fully: operating
system software, DBMS software, and application programs and utilities.
 Operating system software manages all hardware components and makes it possible
for all other software to run on the computers. Examples include disk operating system
(DOS), Windows XP and Linux used by microcomputer; UNIX and VMS used by
minicomputers; and MVS used by IBM mainframe computers.
 DBMS software manages the database within the database system. Some examples
of DBMS software include Microsoft’s Access and SQL Server, Oracle Corporation’s
Oracle, and IBM’s DB2.
 Application programs and utility software are used to access and manipulate the
data in the DBMS and to manage the computer environment in which data access and
manipulation take place.

iii. People

Page 72 of 85
This component includes all users of the database system. They are:
 Systems administrators oversee the database system’s general operations.
 Database administrators manage the DBMS’s use and ensure that the database is
functioning properly.
 Database designers design the database structure.
 System analysts and programmers design and
implement the application programs.
 End users are the people who use the application
programs to run the organization’s daily operations.

iv. Procedures

Procedures are the instructions and rules that govern the design and use of the database
system. Procedures ensure that there is an organized way to monitor and audit both the
data enters the database and the information that is generated through the use of such
data.

v. Data

DATABASE MODEL

Database model is a collection of logical constructs used to represent the data structure
and the data relationships found within the database.

Database models can be grouped into two (2) categories:


 Conceptual models
 Implementation models

The conceptual model focuses on the logical nature of data representation. Therefore,
the conceptual model is concerned with what is represented in the database, rather than
how it is represented. Conceptual model include the entity relationship (E-R) model
discussed later.

In contrast to the conceptual model, an implementation model places the emphasis on


how the data are represented in the database or on how the data structures are
implemented to represent what is modeled. Implementation models include the relational
database model.

STRUCTURED QUERY LANGUAGE (SQL)

Ideally, a database language must enable us to create database and table structures, to
perform basic data management chores (add, delete, and modify), and to perform
complex queries designed to transform the raw data into useful information. Moreover, it
must perform such basic functions with minimal user effort, and its command structure
and syntax must be easy to learn. Finally, it must be portable; that is, it must conform to
some basic standard so that we do not have to relearn the basics when we move from
one RDBMS to another.

Page 73 of 85
SQL meets these ideal database language requirements well. First, SQL functions fit into
two broad categories:

 It is a data definition language: SQL include commands to create the database table
structures, as well as to define access rights to the database.
 It is a data manipulation language: it includes commands to insert, update, delete, and
retrieve data within the database tables.

Second, SQL is relatively easy to learn. Its command set has a basic vocabulary of less
than 100 words. Better yet, SQL is a nonprocedural language: you merely have to
command what is to be done; you don’t have to worry about how it is to be done.

CREATING TABLE STRUCTURES

Format:

CREATE TABLE <table name>(


<attribute1 name and attribute1 characteristics,
attribute2 name and attribute2 characteristics,
attribute3 name and attribute3 characteristics,
primary key designation,
foreign key designation and foreign key requirements>);

Example:

CREATE TABLE VENDOR (


V_CODE INTEGER NOT NULL UNIQUE,
V_NAME VARCHAR(35) NOT NULL,
V_CONTACT VARCHAR(15) NOT NULL,
V_AREACODE CHAR(3) NOT NULL,
V_PHONE CHAR(8) NOT NULL,
V_STATE CHAR(2) NOT NULL,
V_ORDER CHAR(1) NOT NULL,
PRIMARY KEY (V_CODE));

CREATE TABLE PRODUCT (


P_CODE VARCHAR(10) NOT NULL UNIQUE,
P_DESCRIPT VARCHAR(35) NOT NULL,
P_INDATE DATE NOT NULL,
P_ONHAND SMALLINT NOT NULL,
P_MIN SMALLINT NOT NULL,
P_PRICE NUMBER(8,2) NOT NULL,
P_DISCOUNT NUMBER(5,2) NOT NULL,
V_CODE INTEGER
PRIMARY KEY (P_CODE),
FOREIGN KEY (V_CODE) REFERENCES VENDOR
ON DELETE RESTRICT
ON UPDATE CASCADE);

Page 74 of 85
Please refer Appendix for some common SQL data types.

CREATE DOMAIN

Format:

CFREATE DOMAIN <domain_name> AS DATA_TYPE


[DEFAULT <default_value>]
[CHECK (<condition>)]

Example:

CREATE DOMAIN MARITAL_STATUS AS VARCHAR(8)


CHECK (VALUE IN (‘Single’,’Married’,’Divorced’,’Widowed’));

You can use the domain name instead of the attribute’s data type in the CREATE
TABLE command when you define a new table. For example:

CREATE TABLE EMPLOYEE (


EMP_NUM INTEGER NOT NULL CONSTRAINT EMPPK PRIMARY KEY (EMP_NUM
EMP_LNAME VARCHAR(15) NOT NULL,
EMP_FNAME VARCHAR(15 NOT NULL,
EMP_STATUS MARITAL_STATUS NOT NULL,

Another advantage of using domains is that you can draw domain values from other tables
by including a SELECT statement in the CHECK clause. For example, you could have a
table called DISCOUNTBL to store all the valid discount rates a company might offer. In
this case, the DISCOUNTBL table might be defined to contain a single DISCOUNT
attribute. In turn, this table might then contain three rows containing the values 10.00,
15.00, and 20.00. Given the existence of such a table, the CREATE DOMAIN statement
would be written as follows:

CREATE DOMAIN DISCOUNT_RATE AS NUMBER (5,2)


CHECK (VALUE IN (SELECT DISCOUNT FROM DISCOUNTBL));

To delete a domain definition, use the DROP DOMAIN statement. The syntax is:

DROP DOMAIN <domain_name> [RESTRICT | CASCADE]

Example:

DROP DOMAIN MARITAL_STATUS CASCADE;

DATA ENTRY

Page 75 of 85
Format:

INSERT INTO <table name> VALUES (attribute1 value, attribute2 value, … etc.)

Example:

INSERT INTO VENDOR


VALUES (21225, ‘Bryson, Inc.’, ‘Smithson’, ‘615’, ‘223-3234’, ‘TN’, ‘Y’);

INSERT INTO PRODUCT


VALUES (‘BRT-345’, ‘Titanium drill bit’, ‘10/18/02’, ’75, 10, 4.50, 0.06, NULL);

SAVING THE TABLE CONTENTS

Format:

COMMIT <table name>

Example:

COMMIT PRODUCT

LISTING THE TABLE CONTENTS

Format:

SELECT *
FROM <table name>

Example:

SELECT *
FROM PRODUCT;

Or

SELECT P_CODE, P_DESCRIPT, P_INDATE, P_ONHAND, P_MIN, P_PRICE,


P_DISCOUNT, V_CODE
FROM PRODUCT;

MAKING A CORRECTION

Example:

UPDATE PRODUCT
SET P_INDATE = ‘01/18/2002’
WHERE P_CODE = ’13-Q2/P2’;

Page 76 of 85
UPDATE PRODUCT
SET P_INDATE =‘01/18/2002’, P_PRICE = 15.99, P_MIN = 10
WHERE P_CODE = ’13-Q2/P2’;

RESTORING THE TABLE CONTENTS

ROLLBACK;

DELETING TABLE ROWS

Example:

DELETE FROM PRODUCT


WHERE P_CODE = ‘2238/QPD’;
PARTIAL LISTING OF TABLE CONTENTS

Format:

SELECT <column(s)>
FROM <table name>
WHERE <conditions>;

Example:

SELECT P_DESCRIPT, P_INDATE, P_PRICE, V_CODE


FROM PRODUCT
WHERE V_CODE = 21344;

Please refer Appendix for mathematical operators used in following examples.

SELECT P_DESCRIPT, P_INDATE, P_PRICE, V_CODE


FROM PRODUCT
WHERE V_CODE < > 21344
SELECT P_DESCRIPT, P_ONHAND, P_MIN, P_PRICE
FROM PRODUCT
WHERE P_PRICE < = 10;
SELECT P_CODE, P_DESCRIPT, P_ONHAND, P_MIN, P_PRICE
FROM PRODUCT
WHERE P_CODE < ‘1558-QW1’;

VISUAL BASIC INTERFACES

The Integrated Development Environment


Much of the popularity of Visual Basic comes from its Integrated Development
Environment or IDE for short.

Running the IDE


You can choose from several ways to launch the Visual Basic IDE, as is true for any
Windows executable:

Page 77 of 85
 You can run the Visual Basic 6 environment from the Start Menu; the exact
path to the menu command depends on whether you have installed Visual basic as
part of the Microsoft Visual Studio suite.
 You can create a shortcut to the IDE on your desktop and run it by simply
double-clicking on it.
 When Visual Basic is installed, it registers the .vbp, .frm, .bas, and a few
other extensions with the operating system. Therefore, you can run the environment
by double-clicking on any Visual Basic file.
 If you have installed Microsoft Active Desktop, you can create a shortcut to
the Visual Basic IDE on the system taskbar. This is probably the fastest way to run the
IDE: it’s similar to a desktop shortcut, but you don’t have to minimize other windows to
uncover it.

Selecting the Project Type

The first time you run the Visual basic IDE, you’re asked to select the type of project you
want to create, as you can see in Figure 1.1. Choose Standard EXE and click Open button
to start working with a regular project that, once compiled, will deliver a stand-alone EXE
application. You can also decide to tick the “Don’t show this dialog in future” check box if
you want to avoid this operation the next time you launch the IDE.

Figure 7.65

Page 78 of 85
IDE Windows

Figure 7.66

Page 79 of 85
Figure 7.67

Your Very First Visual Basic Program

Adding Controls to a Form


 Launch the Visual Basic IDE, and select a Standard EXE project. You should
have a blank form near the center of the work area.
 Create four TextBox controls-two for entering the rectangle’s width and
height and two for showing the resulting perimeter and area.
 Create four Label controls for clarifying the purpose of each TextBox control.
 Create a CommandButton control named Evaluate that starts the
computation and shows the results.

Setting Properties of Controls


 Change the caption property of Label1, Label2, Label3, and Label4 to
&Width, &Height, &Perimeter, and &Area respectively.
 Change the caption property of CommandButton control to &Evaluate and
the caption property of the form itself to Rectangle Demo.
 To select multiple controls, you can click on each one of them while you
press either the Shift or the Ctrl key. Select all Label controls, TextBox controls, and
CommandButton. When you select a group of controls, then press the F4 key.
 Double-click on the Font item in the Properties window. Select a Tahoma font
and set its size to 11 points.
 Finally, we must clear the Text property of each of the four TextBox controls
so that the end user will find them empty when the program begins its execution. You
must set the Text property to an empty string for each individual TextBox control on
the form. You can deselect other controls by clicking on them while you press either
Shift or the Ctrl key.

Naming Controls
 One property that very control has and that’s very important to Visual Basic
programmers is the Name property. This is the string of characters that identifies the
control in code.
 Microsoft suggests that you always use the same three-letter prefix for all the
controls of a given class. The control classes and their recommended prefixes are
shown in Table 1-1.

Control Class Prefix Control Class Prefix

Page 80 of 85
CommandButton cmd Data dat
TextBox txt HScrollBar hsb
Label lbl VScrollBar vsb
PictureBox pic DriveListBox drv
OptionButton opt DirListBox dir
CheckBox chk FileListBox fil
ComboBox cbo Line lin
ListBox lst Shape shp
Timer tmr OLE ole
Frame fra Form frm

 Rename the Text1 through Text4 controls as txtWidth, txtHeight,


txtPerimeter, and txtArea respectively.
 Rename the Command1 control as cmdEvaluate.
 Rename the Label1 through Label4 controls as lblWidth, lblHeight,
lblPerimeter, and lblArea respectively.

Moving and Resizing Controls


IDE offers you many ways to modify the position and size of your controls without much
effort.

 Select one or more controls, and move them as a single entity using the
mouse.
 Move one or more controls with arrow keys while you press the Ctrl key. The
steps along the x- and y-axes are determined by the Grid Units settings.
 Resize the selected control(s) by using the arrow keys while you press the
Shift key. You can also resize a control by dragging one of the blue handles
surrounding it when it is selected. Like the move operation, the resize step depends on
the Grid Units settings.
 Center a control or a group of controls on the form, either horizontally or
vertically, using the Center In Form submenu of the Format menu.
 Align a group of controls with respect to another control using the commands
in the Align submenu of the Format menu. The control used as a reference in the
aligning process is the one that was selected last (that is, the one with blue handles
around it).
 Resize a group of controls by selecting them and invoking a command in the
make Same Size submenu of the Format menu. All selected controls will be resized to
reflect the size of the control that was selected last.
 You can align or resize a group of controls by selecting them, pressing F4 to
display the Properties window, and then manually modifying the Left, Top, Width, or
Height properties. This procedure is useful when you know the absolute position or
size of the controls.

Setting the Tab Order


You can set the correct Tab order sequence by assigning a proper value to the TabIndex
property for all the controls that can receive the input focus, starting with 0 for the control
that should receive the input focus when the form appears and assigning increasing
values for all the others. Here’s a trick well known among Visual Basic programmers that
solves the problem with relatively little effort:

Page 81 of 85
 Select the last control in your planned Tab order.
 Press the Ctrl+Shift+T key combination to activate the Properties window.
For most controls, this combination selects the TabIndex properties; for others, you
might need to press it more than once.
 Press the 0 key, thus assigning a 0 to the TabIndex property of the selected
control.
 Click on the next to last control in the Tab order, and press the 0 key again;
this assigns a 0 to the TabIndex property of the current control and 1 to the TabIndex
property of the last control. This occurs because Visual Basic prevents you from using
the same TabIndex value for two or more controls on the same form.
 Repeat step 4, working backward in the Tab order sequence and pressing
the 0 key after selecting each control. When you reach the first control in the
sequence, the TabIndex property for all the controls on the form will be set correctly.

Adding Code

To write code within the Click event, you just select the cmdEvaluate control and then
press the F7 key, or right-click on it and then invoke the View Code command from the
pop-up menu. Or you simply double-click on the control using the left mouse button. In all
cases, the code editor window appears, with the flashing cursor located between the
following two lines of code:

Private Sub cmdEvaluate_Click ( )

End Sub

Visual Basic has prepared the template of the Click event procedure for you, and you
have to add one or more lines of code between the Sub and End Sub statements. In this
simple program, you need to extract the values stored in the txtWidth and txtHeight
controls, use them to compute the rectangle’s perimeter and area, and assign the results
to the txtPerimeter and txtArea controls respectively:

Private Sub cmdEvaluate_Click ( )

‘Declare two floating point variables.


Dim reWidth As Double, reHeight As Double

‘Extract values from input TextBox controls.


reWidth = CDbl(txtWidth.Text)
reHeight = CDbl(txtHeight.Text)

‘Evaluate results and assign to output text boxes.


txtPerimeter.Text = CStr((reWidth + reHeight) * 2)
txtArea.Text = CStr(reWidth * reHeight)

End Sub

Running and Debugging the Program

You’re finally ready to run this sample program. You can start its execution in several

Page 82 of 85
ways: by invoking the Start command from the Run menu, by clicking the corresponding
icon on the toolbar, or by pressing the F5 key.

In all cases, you’ll see the form designer disappear and be replaced (but not necessarily in
the same position on the screen) by the real form.

You can enter any value in the leftmost TextBox controls and then click on the Evaluate
button (or press the Alt+E key combination) to see the calculated perimeter and area in
the rightmost controls.

When you’re finished, end the program by closing its main (and only) form.

Refining the Sample Program

Our first Visual Basic project, Rectangle.vbp, is just a sample program, but this is no
excuse not to refine it and turn it into a complete and robust, albeit trivial, application.

The first type of refinement is very simple. Because the txtPerimeter and txtArea controls
are used to show the results of the computation, it doesn’t make sense to make their
contents editable by the user. You can make them read-only fields by setting their Locked
property to True. Some programmers prefer to use Label controls to display result values
on a form, but using read-only TextBox controls has an advantage: The end user can copy
their contents to the clipboard and paste those contents into another application.

A second refinement is geared toward increasing the application’s consistency and


usability. Let’s suppose that your user uses the Rectangle program to determine the
perimeter and area of a rectangle, takes note of the results, and then enters a new width
or a new height (or both). Unfortunately, an instant before your user clicks on the Evaluate
button the phone rings, engaging the user in a long conversation. When he or she hangs
up, the form shows a plausible, though incorrect, result. How can you be sure that those
values won’t be mistaken for good ones? The solution is simple, indeed: as soon as the
user modifies either the txtWidth or the txtHeight TextBox controls, the results fields must
be cleared. In visual basic, you can accomplish this task by trapping each source control’s
Change event and writing a couple of statements in the corresponding event procedure.
Since Change is the default event for TextBox controls – just as the Click event is for
CommandButtons controls – you only have to double-click the txtWidth and txtHeight
controls on the form designer to have Visual Basic create the template for the
corresponding event procedures.

This is the code that you have to add to the procedures:

Private Sub txtWidth_Change( )

txtPerimeter.Text = “”
txtArea.Text = “”

End Sub

Private Sub txtHeight_Change( )

txtPerimeter.Text = “”

Page 83 of 85
txtArea.text = “”

End Sub

The purpose of the next refinement that I am proposing is to increase the program’s
robutness. To see what I mean, run the Rectangle project an press the Evaluate button
without entering width or height values: the program raises a Type Mismatch error when
trying to extract a numeric value from the txtWoidth control. If this were a real-world,
compiled application, such an untrapped error would cause the application to end
abruptly, which is, of course, unacceptable. All errors should be trapped and dealt with in
a convenient way. For example, you should show the user where the problem is and how
to fix it. The easiest way to achieve this is by setting up an error handler in the
cmdEvaluate_Click procedure, as follows.

Private Sub cmdEvaluate_Click( )

‘Declare two floating point variables.


Dim reWidth As Double, reHeight As Double
On Error GoTo WrongValues

‘Extract values from input textbox controls.


reWidth = CDbl (txtWidth.Text)
reHeight = CDbl (txtHeight.Text)
Ensure that they are positive values.
If reWidth <=0 or reHeight <=0 Then GoTo WrongValues
‘Evaluate results and assign to output text boxes.
txtPerimeter.text = CStr ((reWidth + reHeight) * 2)
txtArea.Text = CStr (reWidth * reHeight)
Exit Sub
WrongValues:
MsgBox “Please enter valid width and Height values’, vbexclamation

End Sub

Ready, Compile, Run!

At some time during the program development, you might want to create an executable
(EXE) program. There are several reasons to do this: compiled programs are often (much)
faster than interpreted ones, users don’t need to install Visual Basic to run your
application, and you usually don’t want to let other people peek at your source code. To
create EXE program, run the make projectname command from the File menu.

Question

Page 84 of 85
1. What is if/else statement used for

_________________________________________________
_________________________________________________
_________________________________________________

2. Give the three type of computer language

_________________________________________________
_________________________________________________
_________________________________________________

3. What is Arithmetic Operator

_________________________________________________
_________________________________________________
_________________________________________________

REFERENCE
1. Programming Microsoft Visual Basic, Francesco Balena, Microsoft Press
2. C++ How to program, Deitel, Prentice Hall.
3. Database system, Rob Coronel, Course Technology.
4. Upgrading & Repairing PCs, Scott Mueller, Que
5. Network +, Drew Bird & Mike Harwood, Que.

Page 85 of 85

You might also like