Using Foxpro - John W. Zumsteg
Using Foxpro - John W. Zumsteg
¢
‘3
—
Advanced techniques
Received
|
Digitized by the Internet Archive
in 2022 with funding from
Kahle/Austin Foundation
https://archive.org/details/usingfoxproo000Zums
ROUéeS fess
Using FoxPro,
John W. Zumsteg
QOuc
CORPORATION
LEADING COMPUTER KNOWLEDGE
wb
Mp a
[heskehieaqoeRetslienaib
rary
Received
| CS a
Using FoxPro.
Copyright © 1990 by Que® Corporation.
This book is sold as is, without warranty of any kind, either express or
implied, respecting the contents of this book, including but not limited
to implied warranties for the book’s quality, performance, merchanta-
bility, or fitness for any particular purpose. Neither Que Corporation
nor its dealers or distributors shall be liable to the purchaser or any
other person or entity with respect to any liability, loss, or damage
caused or alleged to be caused directly or indirectly by this book.
A Dil GO 8765432
“Peace of mind isn’t at all superficial to technical work. It’s the whole thing.”
—Robert M. Pirsig
Zen and the Art of Motorcycle Maintenance
iii
Publishing Director Production Editor
Lloyd J. Short Jo Anna W. Arnott
Jay McNaught
Product Director
David Maguiness Technical Editor
Lawrence Peters
Book Design and Production
Dan Armstrong Indexer
Bill Basham
Hilary Adams
Claudia Bell
Brad Chinn
Don Clemons
Sally Copenhaver
Tom Emrick
Dennis Hager
Tami Hughes
Bill Hurley
Jodi Jensen
Larry Lynch
Lori A. Lyons
Jennifer Matthews
Cindy Phipps
Joe Ramon
Dennis Sheehan
Louise Shinault
Bruce Steed
Mary Beth Wakefield
Nora Westlake
John Zumsteg
ohn Zumsteg has worked with microcomputers and
database management programs since their intro-
duction to the computing world. Experienced on a
range of computers, he prefers desktop computers and
systems like FoxPro because they bring computing
power to everyone. Mr. Zumsteg has developed many
PC database systems, primarily in the airline industry,
and is currently the Director of Management Informa-
tion Systems for Horizon Air, the regional airline of the
Northwest United States. In this role, he is responsible
for the design, development, and implementation of
large and complex database programs, as well as con-
ducting classes in all areas of PC applications.
CONTENTS AT A GLANCE
Introduction
Vi
TABLE OF CONTENTS
INTPOCUCTION me Wiese: Bd 2 ee ee 1
Hows lOwUSe hOXero ands DhistBOOKk= eee eee ee 1
ThesAudiEencernawk ooh oe a I eee D,
‘TREZAPpPeoach ys bak oe cc ds ek 2k DR eee 2,
Somes Database History a on. ban 5 ac ee emer 3
WnorsnouldsReadmihts Book? ea ee eee 4
HowalowWse This: Book: cca ieee Oe ee eee 4
FoxPro Fundamentals
Vii
Using Windows, «sitar aayetac.3.9 8 reer getoss mecetaete a One eae 46
Windows and the: MOUSe7i.cy a er ao aa 46
Windows and, the Keyboard). 425-100 95) ee ee 47
Using Dialogs. ie ona tales oar ses ra eee eee nee 48
Text Buttons 20k at en ne ne ee ee 48
Check Boxes ei IR Se ae ee, ee 48
Radio: BUtlOnS 3 sc3 «ae 2 a ee ee we 49
ScrollableListS)...0250 35 Sees on ee I es 49
Pop-Up: Controls vac. 2.« Spa ae eee eee 49
VEX: BOXES isc iene 9 oie nb SE. BER ae ee Ree 50
Moving Around ina Dialog... : #oob.eo eee ee 50
Chapter Summary ioe) a inte Gave doped oe eta ake ees 51
Viii
Moving Objects On-Screemss hs, aes tas ae eee 85
AACLCINGS LEX to (Ne: SCLOEN «cs rats ci ceweer aon 85
AQP BOXeS tO (he SCLECh a wae eee te 86
Using Picture and PunctionsCoges es asi ee 87
Generating the Format Screen from FoxView.......... 90
Wising they FOXV ieWw SCLECI.. 3:oie sacus san ea cee ee eee 90
EGiting invData-Entty Pields a. 20. 62 3s bee 92
Vie wins Informations = soci cna « 6500 diereane, See Ope Re 92
sine the Browse Window 25.0.4. 40046 3 Ae ere OZ
Changing the Browse Window ..-.. pan eee 93
Wsine Browse Options <5 ye eee eee eee 96
Finding Specific: RECOLdS 2a. ot ra ee eee 96
ising: Seeks and sPING ven ove eee ee eee 96
Using Locate and Continue on Nonindexed Fields ..... O77,
Deleting Data 2 ti5 ii. tae cin ee on cater Ee 98
Marking Data occ trie nv sheen ats eae nan deeaks taae a 98
Recalling a Record: can Fs wa vais sae ee ne te 99
PACKING: HE Data ase sere. :c00.5 gruorsses-loataut nonSathana Wp Realered AS)nhs 100
Chapter SUMMALY «oc... > vases een Se ee eee 100
Il Intermediate FoxPro
Xi
Re-using, a Previous: Command), 27 /)0e.a: oe 1s siesta 249
Editing and Re-using Previous Commands............... 249
Using the Programming Language ss. en mick nee re 250
Creating a Simple: Progtam 2/7. en-0. pe oa. ee ere 250
Using. the-Ttace Window, ccctcc2.. ei cn en ie? 251
Chapter: Summary caw. is ieecosc oat purer iaentse eek eee 252
Xii
10 Creating Applications with FoxPro.............. 311
Designing ATPADDMGALON ety 24.8 fours Cres ee MeO ree ccs 5EZ
Including Functionality in the Application............... 312
Delininesthe Menus SImClUre. ee ee eee ee 512
Using the Menu and Pop-up Menu Structure............. 313
Creatine andiUsine Menus 2 Aint ola e ee cree ee ee 314
Defining the: Menu crc sonic teen eee oa Oe ee Ie ee 515
Defining the MenutPadss..05 024.) 55.08 2 -ae eee 316
Defining the Action When a Pad is Selected............. 316
ACUVALING CNCHMCNT sgh ci o's hee ae ee Aly
DeActivatinetheeviens...mirs te yey eee Peet oeOme arene 318
Creating and Using Pop-up Menus? 7e0 .2es ea. nee coe 318
Detining*a’ Pop-up Menu a! ees ees eee 318
Using “The PROMPT. FIELD Options 424. aie)
Using The»PROMP IpFILES ‘Option’ 25-4607 are 320
Using-The PROMPIsSTRUCIURE; @ptionis.. ee 320
Defining Bachs Barocco Cie fer eore cea ee S22
Taking Action.onta Pop-up Choice?” 2.4... ee 522
Adding Help Systems. see ese otet 1 mess, coro tes ae 525
Creating the Help Database.4-.5%.490- «10 eee ee 326
Providing a FoxPro: Typei Help System —. = anes 2) eee 326
Creatine a Context-Sensitive Help System cow 2) .cane oe 326
Detiningtand Using Windowss2 2. 4-10. Soe rae nee 328
Definine-a Windows eta rs ie RI te ee: 329
Puttingthe: Window On-screen aay see ae ee eee S511
Wsing Colors a8 cee eat kee oe a ee eee eee 352
Using a; COO Rta oar ciate nyo Ce oe ee eee 333
Using +a. Colon Pairs acta iahiase War shar how ene ringer Oe 335
Using Color Pair Lists and Color’Schemes..<....4. 922.5. 334
Using the ColorPicker To Set. Colotss: 275 an. n. eee 555
Deciding between Color and Monochrome.............. 355
ChaptersSummary a ote cance vs 9 cea ee 336
xiii
Using DO WHILEZENDDOW si. cise ain ane 2 cece rae 345
Using FOR. ENDEOR jo. nc. soot ern es aut tt Rn ee 347
Using-SCAN. ENDSCAN ©eis aticiy nei trae eum t sates afagae 348
Usitig- DO"GASE. ENDCASE. (Senna oan ee nae are 348
Using Screen Input and Output.c.8. oe ps comes acres iets 350
Using INPUT and WALT s.3 55 5 ghee ck ene ere eee eee 550
Using. the ?-and 17? Statements)...0. ..cn eee 351
Usingi(@ SA Y..GET i, ye nde eee eee 352
Using SAY To Put Information On-Screen............. apy
Using GET and READ To Get Information ............ 353
Combining the SAY and GET Commands ............. 55D
Using FUNCTION Clauses To Format a Data Field ..... 356
Using PICTURE Clauses To Format a Data Field ....... 457
Usinge-Other;GEI- Options aa rie tr eer 358
Creating Structured: Programs smcne, jee te ate Ne ee es 358
Using ‘Subprogramsianerrp eee tae wee oe eee 360
Using Procedure: Files: pats rs sr eee ae cere tee se he 361
Wsing Basic, Utility: Programs. wee eee ee 363
Reading Lo Geta Valid: Character samp a ee 363
Using Memory Variables for Database Input ............. 365
Chapter Summary. 7.sae ocut esi ore cs een ana reeneen ee 365
XiV
ACKNOWLEDGMENTS
XV
TRADEMARK
ACKNOWLEDGMENTS
Apple, Mac, and Macintosh are registered trademarks of Apple Computer, Inc.
XVi
Introduction
A good database manager does more than store and report data; it gives
you new ways to look at the data, better capabilities to see the meaning
of that data, and quicker ways to access what you need. FoxPro has an
extraordinary amount of power, allowing complex database systems to
be developed. A good-sized company could be run on a FoxPro-based
Management Information System.
Unlike many other programs, FoxPro is fun to learn. Every step brings
more power to your computer, and improves your ability to mold and
manipulate your data to meet your needs.
The Audience
Users of FoxPro and FoxBase + span a wide range of experience, but this
book concentrates on those who can be categorized as beginning users to
intermediate users.
Users who have never used a database manager—or even a personal com-
puter—will be able to start with this book and build a comfortable level
of skill with FoxPro or FoxBase+.
Users who have “played around” with FoxPro or FoxBase + and now need
to do some serious work will be able to use Using FoxPro as a guide to
learning how to organize and implement a database, no matter how sim-
ple or sophisticated.
Users who are experienced with FoxBase+ and who need to make the
transition to FoxPro will find this book helpful in learning the graphical
user interface approach that FoxPro takes. Learning to use FoxPro’s win-
dows, dialog boxes, and pull-down and pop-up menus is certainly easier
with Using FoxPro as your guide.
The Approach
Using FoxPro is divided into three parts, which correspond roughly to
“beginning FoxPro,” “beginning-to-intermediate FoxPro,” and “intermedi-
ate FoxPro” sections. Each part begins with a quick start, which is a
hands-on, step-by-step guide to achieving results with FoxPro. By going
through the quick starts only, you can learn enough about FoxPro to use
the program productively. After the quick start in each part are several
chapters that delve more deeply into the topics introduced in the quick
start. In these chapters, you will learn enough about the topic at hand to
use the many options and powerful capabilities of FoxPro and FoxBase +.
If you’re new to the database management world, you should start at the
very beginning, working through Quick Start 1. This quick start will give
you an overview of database management: how to design and define your
database; enter, edit, and view data; and report on that data. Then work
through the chapters in Part I to deepen that knowledge and become
familiar with the ways to use FoxPro. When you're familiar with these
basic capabilities, you can repeat this process in Part II to learn how to
tap the real power of FoxPro.
More advanced users can use Part III, which covers how to use FoxPro
and FoxBase+ to create simple programs and applications. Many users
will eventually feel the need to reach this level of expertise, and Quick
Start 3 will start them toward that goal.
Like FoxPro, which can be used by people with any level of computer and
database management expertise, Using FoxPro has something for you if
you’re new to the computer world or new to database management, or
if you are experienced in other programs and want to learn FoxPro. In
Using FoxPro, you learn how to design a database and how to use FoxPro
to bring that database into being. You learn how to create reports,
queries, and data-entry screens. If after harnessing these FoxPro capa-
bilities you find a need for more sophisticated applications, Using FoxPro
also provides an introduction to using FoxPro’s sophisticated program-
ming language.
But those first databases were not easy to use. Ashton-Tate’s dBASE I
required that every command be entered from the keyboard in a highly
structured syntax. dBASE III and dBASE III Plus, the most well-known
microcomputer database programs, improved on that cryptic command
approach, but the concept was the same.
In 1986, Fox Software introduced FoxBase+ , which was a dBASE III Plus
look-alike. FoxBase + was faster and had some additional features, primar-
ily for people developing sophisticated turn-key applications. Foxbase+
4 Using FoxPro
evolved into FoxBase 2.10, and FoxBase 2.10 evolved into FoxPro, but
with an unusual detour resulting in a revolutionary, easy-to-use interface
for such a powerful product.
Fox Software decided, in 1987, to port FoxBase 2.10 to the Apple Macin-
tosh. Originally, the company wanted to move FoxBase as is, keeping the
same command-line interface of the PC version. However, Fox Software
ended up rewriting the program to make use of the intuitive, mouse-based
Macintosh interface. When the company wanted to upgrade FoxBase +,
Fox Software ported the Foxbase/Mac system to the PC—windows, mice,
and all.
For the user already familiar with other database management programs
(including FoxBase 2.10), Using FoxPro provides the bridge to new ways
to accomplish old tasks. At the same time, the more experienced reader
will learn how to use the more powerful FoxPro features.
The novice will be best served by working through each section of the
book, using the program while you work. Nothing can match the learning
experience of actually trying something and seeing it work.
Introduction 5
FoxPro
Fundamentals
Includes
An Overview of FoxPro
Start
Getting Started
with FoxPro
=H oxPro provides an amazing amount of database power, yet that power
= is easier to use than any other database program. This quick start
shows you how to get started with that power in the quickest, easiest
fashion. Much of what you will do in this quick start receives more atten-
tion in the rest of the book, but if you follow along with this tutorial, you
will learn enough to get going with FoxPro.
Creating a Database
Let’s start with a hypothetical situation. Your boss wanders into your
office and comments that, because she bought you that fancy computer to
help you be more productive, she would like to see you doing something
besides flying an F-15 in pursuit of MIG-23s. In fact, she would really like
to see some reports on your company’s customers and, later on, maybe a
way to track contacts with those customers. After assuring her that you
can do that, you gulp and decide it’s time to learn FoxPro. Turning to
your trusty, if somewhat unfamiliar computer, you prepare to delve into
database management, FoxPro style.
To create and use your first FoxPro database, follow these steps:
CD \FOXPRO
MD CUST
CD7CuUsT,
PATH = \FOXPRO
FOXPRO
10 Part I: FoxPro Fundamentals
Fig. QS1.1.
The opening
FoxPro screen.
Across the top of the screen is a menu bar, with the options System, File,
Edit, Database, and so on. You use these menu options to tell FoxPro what
to do. FoxPro functions are grouped into these areas and become avail-
able through menus that pop up when you select the top level menu.
In the lower right corner of the screen is a bordered box, with the word
Command across the top. This is a window. FoxPro, revealing its Macintosh
heritage, is a strongly window-oriented program. Nearly all you do with
FoxPro will be in various windows. FoxPro has a View window, to look at
information about the databases you’re using; a Browse window, to view a
database’s information; and other windows in which FoxPro will do the
things you ask of it. Most windows can be moved and resized, to enable
you to customize FoxPro to your liking.
2. Next, using the mouse, move the mouse pointer to the File option
in the menu and press the left mouse button. FoxPro displays the
File pop-up menu, shown in figure QS1.2.
You also can open the File pop-up menu from the keyboard by
pressing the F10 key, which activates the Main menu. Use the left-
and right-arrow keys to move across the menu to the File option,
and press Enter. You will see the File pop-up menu shown in
figure QS1.2.
Quick Start 1: Getting Started with FoxPro 1 1
Fig. QS1.2.
Save The File pop-up
Save as... menu.
Revert
Printer Setup...
Print...
Quit
3. Next, you need to tell FoxPro that you want to create a new
database. Choose New from the File menu by either highlighting
that option and clicking it with the mouse, or by pressing N to
select New.
4. FoxPro displays the New dialog (see fig. QS1.3). Select Database
to tell FoxPro that you are creating a new database. Then choose
OK. FoxPro displays the Structure dialog, shown in figure QS1.4.
Fig. QS1.3.
The New dialog.
Database
Program
File « OK »
Index
Report <« Cancel >
Label
Form
12 Part I: FoxPro Fundamentals
Fig. QS1.4.
Structure: Untitled
The Structure Name Type Width Dec
dialog. Field
«Insert?
<Delete>
« OK »
<Cancel>
Before you get to this point, you will have thought about your database
and what it must contain. Database design can be as simple as writing
down the fields of information you want to keep in the database. FoxPro
is now waiting for you to enter that database design into the Structure
dialog.
6. Move to the Width field and enter 30. This tells FoxPro to reserve
30 characters for the CUST_NAME field. Press Enter to move to
the first field of the next line. Continue entering fields, field types,
and field widths, using the following definitions:
CUST_NAME Character 25
ADDR_1 Character 2S
ADDR_2 Character 2S:
CITY Character 15
STATE Character 2
ZIP Character 9
PHONE Character 10
Quick Start 1: Getting Started with FoxPro 1 4
CONTACT Character 10
CREDIT Numeric 8 72
LAST_PUR Date 8
LAST_AMT Numeric 8 Z
PREFERRD Logical 1
When you enter the Type for the CREDIT and LAST_AMT fields,
select Numeric from the Type menu by using the pop-up menu
and highlighting Numeric, or by pressing the letter N; FoxPro fills
in the rest.
Do the same for the Date fields, choosing Date from the menu, or
by pressing D and letting FoxPro fill in the rest of the field type.
The Structure window should look like the one in figure QS1.5.
Fig. QS1.5.
Structure: C:\FOXPRO\BOOK\CUSTOMER.
DBF The CUSTOMER
Name Type Width Dec :
database defined
t CUST_NAME Character in the Structure
t ADDR_1 Character «Insert?
+ ADDR_Z Character dialog.
+ CLTY. Character <Delete>
t STATE Character
+ ZIP Character
z PHONE Character
t CONTACT Character « OK »
t CREDIT Numeric
+ LAST_PUR Date <Cancel >
7. Next, choose OK. The Save As dialog appears so you can name
your new database. Enter customer and select Save. Foxpro saves
your database design and asks you if you want to enter records
now. Choose Yes.
Congratulations! You have just created a real FoxPro database, ready to
receive data and go to work for you.
Regular editing functions are available while entering or editing data in all
FoxPro fields, either in the database or any of the dialogs requiring text
entry. The backspace key is a “destructive” backspace. It moves the cursor
one character to the left and erases that character. The right- and left-
arrow keys move the cursor right and left, without erasing characters. The
14 Part I: FoxPro Fundamentals
Home key moves the cursor to the first character in the field; the End key
moves it to the last character. The Ins key toggles Insert mode on and off.
Press it once to insert characters into the text. Press it again to overwrite
existing characters.
Now you can enter some data into the database by following these steps:
»>Cust_name
»Addr_1 j
mAddr_Z td
3. When you have finished the first record, which occurs when you
press Enter on the last field, FoxPro presents you with a data-
entry field for the second record, just below the first. Enter the
second record, and continue to enter more records, making up
names and addresses until you have entered at least 15 records
into the database.
move to the first or last record in the Browse window, respectively. Con-
tinue to press the up- or down-arrow keys to scroll the window up or
down.
Move the mouse pointer to a place on the Vertical Scroll Bar that is
between the scroll-down symbol and the thumb (the diamond shape in
the scroll bar) and click. Your window will move a full screen down
through the database. If the window shows 10 lines, scrolling down a page
causes the window to move down 9 lines; the line that was last on the
page now becomes the first line. Clicking in the scroll bar between the
scroll-up symbol and the thumb scrolls the window up one screen.
From the keyboard, you should use the PgUp and PgDn keys to move the
window up and down a full screen in the database. The first time you
press PgUp or PgDn, the highlight moves to the first or last record visible
in the Browse window. Pressing PgUp or PgDn again causes the window
to scroll a full page up or down.
Using the thumb is most advantageous in large databases. If you drag the
thumb halfway down the scroll bar, the Browse window will show
the records halfway through the database. If you drag the thumb three-
quarters of the way down the bar, the window will show the records
three-quarters of the way through the database. The position of the thumb
in the Vertical Scroll Bar corresponds to the position in the database of
the records appearing in the Browse window.
Keyboard users looking for a way to use the thumb will be disappointed;
this feature is one of the very few FoxPro features available to mouse
users and not keyboard users.
To scroll the window to the right, move the mouse pointer to the bottom
margin of the window, which is a Horizontal Scroll Bar. Place the pointer
over the scroll-right symbol and click. The window now shows fields that
were not visible before, and the first field, CUST.NAME, has disappeared
(see fig. QS1.8). Clicking on the scroll-left symbol moves the window to
the left.
From the keyboard, you can scroll right and left by using the Tab and
Shift-Tab keys. Press the Tab key several times in succession, the highlight
moves across the fields and, when it reaches the right-most field, causes
the window to scroll to the right to bring more fields into view. Shift-Tab
reverses the process.
You can drag the window anywhere off the screen. Move the mouse
pointer to the top margin of the window, press the left button and move
the mouse while holding the button down. The entire window moves
with the mouse pointer. Figure QS1.9 shows the window moved partly off
the screen.
Quick Start 1: Getting Started with FoxPro | ee
From the keyboard, you can move the screen by pressing Alt-W to acti-
vate the Window pop-up menu, and selecting Move. You also can go
straight to the Move option by pressing Ctrl-F7. The window will start
flashing and you can move it with the arrow keys. Press Enter to stop the
Move process.
Fig. QS1.9.
The Browse
window, dragged
partly off the
LJ CUSTOMER screen.
To change the shape of the window, move the mouse pointer to the small
dot in the lower right corner of the Browse window. This is the Sizing
18 Part I: FoxPro Fundamentals
symbol. Use the mouse to drag the symbol. You will see the window
change shape as you drag. When the window is the shape and size you
want, release the button.
To change the shape of the window from the keyboard, select Size from
the Window pop-up menu, or press Ctrl-F8. The border of the window
flashes, and when you press the arrow keys, the bottom right corner
moves, sizing the window. Again, press Enter to stop the process.
The last thing you can do to a window is zoom it, making it fill the whole
screen. Move the mouse pointer to the Zoom symbol in the upper right
corner of the Browse window and click it. The window “zooms” to fill the
whole screen (see fig. QS1.10). Click the Zoom symbol again and the win-
dow returns to its old size.
To zoom from the keyboard, select Zoom from the Window pop-up menu
or press Ctrl-F10. Repeat the process to return the window to its original
Size.
If you have ever worked with a Macintosh computer, moving, sizing, and
zooming windows is second nature to you. In the PC world, FoxPro is the
first database management program to use windows extensively and
efficiently.
Although windowing programs are built for mouse users, you can still use
windows from the keyboard.
Quick Start 1: Getting Started with FoxPro 19
From the keyboard, use the arrow and Tab keys to move to the
CUST_NAME field in the first record. You can edit it normally.
To delete characters from the keyboard, hold the Shift key down
while using the right- and left-arrow keys to move the highlighted
(red) portion of the field. When you have highlighted what you
want to delete, press Del to remove it.
a
Lt CUSTOMER =
5. You can bring back the record marked for deletion by repeating
the process for deleting it. Place the mouse pointer in the space
left of the left-most field in the Browse window and click. The
Deleted Record symbol disappears and the record is returned to
the database. From the keyboard, select the record and choose
Recall from the Record menu (Recall replaces Delete in this menu
if the selected record is marked for deletion) or press Ctrl-U
again. Deleting a record is a toggle action—do it once and the
record is marked for deletion; do the same thing again and the
marking is removed.
Quick Start 1: Getting Started with FoxPro ? 1
You have created a database and added, edited, and deleted records from
it. An index on a database tells FoxPro in what order to show the data.
You can tell FoxPro to set up an index on the CUST_NAME field. When
you open the database and tell FoxPro to use that index, all records are
listed in alphabetical order, even though they may have been entered ran-
domly. If you create an index on the ZIP field, the records will appear in
ZIP code order. An index is automatically updated whenever you add or
delete a record, or change the entry in the field on which the database is
indexed. To create an index for your database, perform the following
steps:
1. Choose View from the Window menu. The View window opens
(see fig. OS1.13)).
Fig. QS1.13.
« View > Work Areas « Relations > & Q 3
The View
«On/Off > >» CUSTOMER window.
A
—B- ¢
<Files > ae
= R=
« Misc > =e
—F-
«Browse? Sh
-J-
« Open >
3. Next, you see the Open Index File dialog (see fig. QS1.15).
FoxPro doesn’t know whether you’re going to create a new index
or use one that already has been created (in an earlier FoxPro
session). Because this will be a new index, choose New.
Directory CUST
« Open
< Cancel
{C J All Files
Quick Start 1: Getting Started with FoxPro 23
Fig. QS1.16.
INDEX ON:
The Index On
CUST_NAME dialog.
ADDR_1
ADDR_Z « OK »
CITY
STATE < Cancel >
ZIP
<Expr...?
{C J Unique
CHOM srt
5. You move to the Save As dialog, where you must enter a file
name for this index file. Enter custname and choose Save to save
the file. CUSTNAME becomes the DOS file name for the index file.
Because it must adhere to the DOS rules for file names (eight
characters long), you should leave out the underscore you used as
a name in the database.
FoxPro also can sort a database, physically rearranging the records into
the requested sort order. In a small database, sorting and indexing are sim-
ilar, but in larger databases, sorting can take much longer. FoxPro index-
ing is so efficient that you will seldom, if ever, need to sort a database.
the Report Writer also gives you a quick and easy way to create simple
reports from one database. Now, to satisfy the boss, create and generate
your first FoxPro report:
1. Choose New from the File menu. In the File New dialog, select
Report and OK. FoxPro responds by presenting the Layout window,
shown in figure QS$1.18. The Layout Window is like a table top on
which you arrange elements of your report: fields from the
database, labels for the fields, titles, and lines.
Report:
Column Layout
Form Layout Fieldi Fieldz2
XXXXXX_XXXXXX
Titles XXXXXX XXXXXX
] Fields...
« « Cancel >
Fig. QS1.20.
The Layout, with
Detail the default Quick
Detail | a See
Detail ADDR 1 Report fields in
Detail si ADDR_Z place.
Detail i CITY
Detail ST
Detail i ZIP
Detail #4 PHONE
Detail CONTACT
Detail i CREDIT
Detail LAST_PUR
Detail _ LAST_AMT
Detail
PgFoot
PgFoot
PgFoot
“
26 Part I: FoxPro Fundamentals
To see how this report would look if you ran it right now, choose Page
Preview from the Report menu. FoxPro runs the report and places the
output in a Page Preview window (see fig. QS1.21).
Bill’s Plumbing
Fig. QS1.21. e 2323 N. 23rd
Page Preview of ae Re eeaer
the Quick Report. ua
98332
2868823932
Oscar
8.86
/
8.88
Comar
33423 Airport Drive
Cinncinnatti
OH
< More > Column: 8
AS you Can see, your report is a success. It is, however, a little on the plain
side. Close the Page Preview window by choosing Done in the lower left
corner to return to the Layout. To improve the appearance of your report,
follow these steps:
1. First, replace the cryptic field labels with something you and
other users will better understand. Make space for these labels by
moving the database fields to the right. Move the CUST.NAME
field by dragging until the field is about 15 columns to the right
of its original position. If you’re working from the keyboard, place
the cursor on the CUST_NAME field and press Shift-space bar. You
can use the arrow keys to relocate the field. Repeat this process
with all the database fields, moving them to the right so that you
have room for meaningful labels. When you're finished, the layout
should look like the one in figure QS1.22.
Fig. QS1.22.
Moving the
database fields
CUST_NAME
on the Layout.
Note that there is a minor bug if you enter the text-edit mode by pressing
Ctrl-space bar; FoxPro will add a space at the cursor position. You must
delete this space by pressing the Backspace key.
Continue editing and moving the labels until the layout looks like figure
QS1.23.
Fig. QS1.23.
Changing and
Detail 4 moving the field
Detail Customer Name CUST_NAME 5,
Detail Address ADDR_1 labels on the
Detail ADDR_Z Layout.
Detail City CITY State ST Zip ZIP i
Detail Phone PHONE
Detail x Contact CONTACT
Detail Credit Limit CREDIT
Detail Last Purchase Date LAST_PUR
Detail Last Purchase Amount LAST_AMT
Detail Preferred Customer? P
Detail
Detail
PgFoot
PgFoot
PgFoot
“
Now, choose Page Preview from the Report window to see what your
report looks like (see fig. QS1.24).
ee ES Ee eee a ne ee
Much better, but the addition of a title and some lines will improve it
even more:
2. Move the cursor to the second line in the PgHead Band. Choose
Add Text from the Report menu. An object named TEXT OBJECT
appears on the Layout view at the position of the cursor. Press
Shift-Enter or Shift-Click to edit this object and change the name
to Customer Database Report. Move the new title to the center of
the page.
3. Move the cursor to the left margin of the bottom line of the
PgHead Band and choose Box from the Report menu. If you have
a monochrome monitor, you will see the Box dialog, shown in
figure QS1.25, asking what type of box to add.
4. Choose the default, Single Line. When you do so, you return to
the Layout, which now contains a highlighted box object. Size the
box by placing the cursor anywhere on the box frame and
pressing Ctrl-space bar. The box will blink. The right and bottom
sides of the box will move; use the arrow keys to move these
sides until the box is the size you want. Press Enter to accept the
box size.
Fig. QS1.25.
The Box dialog,
showing the
Box:
different types of
box borders
eee
( ) Character... « Cancel >
available
monochrome
on
monitors.
[CX] Float as Band Stretches
If you want to see how this report will appear in page preview, choose
Page Preview from the Report menu (see fig. QS1.27).
40 Part I: FoxPro Fundamentals
The polished
report in Page Customer Name Bill’s Plumbing
Preview. Address 23Z3 N. 23rd
This new version is a much more readable report, certainly proof that
your computer is good for more than playing F-15 pilot.
1. Choose Save from the File menu. When the Save As dialog
appears, enter the name REPORT/ in the text box and choose
Save (see fig. QS1.28). FoxPro saves your report with the name
REPORT1.FRX (it automatically appends the FRX extension, which
FoxPro uses to identify this as a report file).
Directory CUST #
« Save »
REPORT1_
3. Choose Report from the Database menu to run your report. You
will see the Report dialog, shown in figure QS1.29, in which you
tell FoxPro which report to run.
Plain
No Eject
Summary
Heading
To Print « OK »
To File
Console On ( ) Console Off « Cancel >
4. Click Form. FoxPro shows you the Report File dialog (see fig.
QS1.30). Select REPORT1.FRX by clicking it or by using the Tab
key to highlight it, then choosing OK. When you return to the
Report dialog, the report name is entered below Form.
Fig. QS1.30.
Report File: The Report File
dialog, used to
REPORT1. FRX choose which
report to run.
Directory CUST
« Open »
« Cancel >
{ J All Files
42 Part I: FoxPro Fundamentals
Summary
FoxPro is a visually oriented program. Each action you choose from the
menus causes FoxPro to respond, often with a window asking for more
information. Unlike any other database system available on IBM PC
compatible computers, FoxPro does not ask you to learn complicated
command structures that must be entered from a command line. Develop-
ing and using databases in FoxPro requires that you know only what
choice to make from the Main menu; from there, FoxPro presents the
options and the choices you need to make.
In this quick start, you have learned how to design a database and define
it in terms FoxPro understands. You can enter information into the
database, edit, delete, and extract it in the form of reports. FoxPro’s
strength is that it gives you the power to do all this on increasingly
sophisticated databases without much more effort. Throughout the range
of database complexity, you will use the same basic tools and operations.
An Overview of
FoxPro
What Is a Database’?
A database is simply a collection of data with some organization to it. A
database can be a file cabinet, a stack of file cards, or a notebook. A com-
puterized database is simply a collection of data organized and placed into
computer files instead of notebooks or file cards. The advantage of com-
puterizing a database is your ability to easily change the data, view it in
different ways, and generate accurate reports. A computer lets you access
the same data you had in your notebook, for example, but faster, more
accurately, and in more ways than you could have when the data was in
written form.
FoxPro enables you to use the two most important types of PC database
files: flat files and relational database files.
33
3 4 Part I: FoxPro Fundamentals
Flat Files
If you store the number, name, address, and telephone number of every
employee in your company, you have aflat file because the file has only
two dimensions. Its width represents one record in the file, and its length
represents the number of records in the file. Figure 1.1 illustrates a flat
file. Programs that work only with flat files are called file managers.
Relational Files
The power of FoxPro is in its capacity to work with files that are related;
FoxPro is a relational database manager. How can files be related? How
can those relationships make a database more powerful? Suppose that you
already have created the employee number, name, and phone number file
shown in figure 1.1, and now you want to store information about your
company’s organizational structure—namely, which employees work in
which departments. You can create another flat file that includes the
employee number, the department in which that employee works, and the
employee’s title. These two files are related, and the employee number
field is the tie between them. In database design, you can illustrate this
relationship as shown in figure 1.2.
In this example, you have one record for each employee. If you want a
report of each department’s employees, with phone numbers, you need to
tell FoxPro that the two flat files are related. Then FoxPro can get the
right information from each file. When FoxPro looks at a record in the
Chapter 1: An Overview of FoxPro
35
System File Edit Database: Record Program Window Browse
department file, the program looks at the employee number and automat-
ically finds the record in the employee file with the same employee num-
ber. No matter how much you move through the department file, FoxPro
keeps the employee file in sync, making available any information for that
employee (see fig. 1.3).
13.
Fig 13
FoxBase+ eventually evolved into Version 2.10, which was even faster
and added a number of features not included by its competitors. Most of
these features, though, were of benefit only to programmers who were
developing full “turn-key” systems in FoxBase+. For the beginning to
intermediate nonprogramming user, FoxBase+ Version 2.10 was still a
dBASE III PLUS clone, with the continued advantage of being faster in
many areas.
Chapter 1: An Overview of FoxPro
37
FoxBase +/Mac: FoxBase+ in the
Macintosh Interface
In 1988, FoxBase + took an interesting detour into the world of the Apple
Macintosh. Originally, Fox Software planned to convert FoxBase+ to the
Macintosh environment with only minor changes; the result was to be
FoxBase + running on the Macintosh. In the process, though, FoxBase+
got the Macintosh “religion.” In the end, FoxBase+ was almost com-
pletely rewritten for the Macintosh, to take full advantage of the Mac’s
graphical user interface. FoxBase + /Mac uses windows, dialog boxes, and
all the other easy-to-use features for which the Macintosh is famous. When
the time came for Fox Software to upgrade FoxBase+ in the PC world,
the Macintosh version of FoxBase + was the base.
The Apple Macintosh is known for being easy to use. Its user interface
depends on multiple windows to present information from the program to
you, dialog boxes to get information from you about what you want to do,
and a mouse for you to navigate through the windows and dialog boxes.
FoxPro has brought this graphical user interface to the PC database world,
and you will find that working with it becomes second nature quickly.
Windows
FoxPro presents information in windows. When you tell FoxPro to show
you the database, the program does so in the Browse window. When you
want to enter or edit data, you use a data-entry window. Many different
windows can be present on-screen at one time, and you can resize the
windows and move them to make the ones you want to view more visi-
ble. Figure 1.4 shows two databases in Browse windows.
Fig. 1.4.
aS
West Hill Florist 32981 2nd Ave So
a,
The Browse Northuest Microsystens,In] 18968 127th Pl
ae SCIL P.0. Box 2231
*S & C Autos 3342 E. Elwood
Comair 33423 Airport Drive
Cross Continent 4423 Wilson Rd
Northend Music SouthCenter Mall
Bill’s Plumbing 2323 N. 23rd
Studio 11 Art 2231 Fourth
OshKosh Cow Company 5534 E. Dairy Rd
Metropolitan Corp 8823 E. Military Rd
Hess Aviation Inventory 3342 Aviation R
T.Moore & Associates unknown
Oriental Cuisine 4432 International Ave
ay
A dialog box is a form of window; FoxPro uses dialogs to get information
from you about what you want to do. Figure 1.5 shows the Preferences
dialog. A dialog may contain several different types of elements, each rep-
resenting a different type of choice to be made. These choices, and how
to make them, are examined later in this chapter.
Chapter 1: An Overview of FoxPro 39
Fig. 1.5.
The Preferences
Wrap words Tab size: 4 dialog.
Auto indent
Make backup C J] Use these preferences
Add line feeds as default for .PRG
Compile when saved files
Ctrl-Z sensitive C J Save preference
Left justify
Right justify
Center justify <Cancel>
The Mouse
You can use the mouse to accomplish just about everything in FoxPro. As
with the Macintosh, the only time you really need to use the keyboard is
to enter numbers and text.
The Keyboard
m9 many cases, keyboard users of FoxPro will claim that they can do
things as fast from the keyboard as mouse users, and often they will be
right. Most of FoxPro’s commands can be issued with just one or two key-
strokes. Even inveterate mouse users will find that the keyboard com-
mands are quick and convenient.
PeSSmaLO
For many users, pressing these keys is faster than using the mouse to pull
down the File menu and selecting Browse from it. If you’re using only the
keyboard, you will not feel terribly disadvantaged (although using a
mouse 7s faster in many areas). And, if you’re a mouse user, you will find
that you will want to use the keyboard on many occasions.
emcee
Fig. 1.6. CT ee
The Command =zB —a =
=
_=
window. = = i
= =m a a | = oe =
cane) rT] oa =a a Pee e) =a =a =
z= 2] fe] = rT] =a = 2)
=a a = = = = S =
fo = = = =a = = P=
a P| om = = = a] = Pe]
ne = a aso tal con
FoxPro 1.88 €c) Fox Software 1984,1989, U.S./Canadian Edition t XPD@02327
USE CUSTOMER.
DBF
BROWSE LAST
Commands can be
Entered in the ——>
Command Window
Chapter 1: An Overview of FoxPro 41
FoxPro Capabilities
What can FoxPro and FoxBase+ do for you? Like any good database man-
ager, FoxPro and FoxBase+ give you the power to manage incredible
amounts of data, regardless of its complexity. If you can organize the data
at all, FoxPro and FoxBase+ give you data-entry, organizing, and report-
ing tools to make sense of it. As you become more familiar with these
programs, you will find that the FoxPro and FoxBase+ programming lan-
guage enables you to build more sophisticated applications. If you want,
you can use the advanced features of these two programs to develop fin-
ished turnkey applications for yourself and other users.
More than anything else, your ability to customize screens makes them
easier to use. Compare the default data-entry screen shown in figure 1.7
with the custom screen shown in figure 1.8. Which would you rather use?
Customer Name
Fig. 1.9.
Customer List
A FoxPro report.
City
State
Zip
Phone 2862289932
Contact Wilson
Credit Limit 100.88
Last Purchase Date 11/81/89
Last Purchase Amt 23.68
Preferred Customer .
You can see that this program, executed with a DO command (from the
Program menu or Command window), saves you from executing several
commands every time you want to open and look at this database.
SELECT 2
USE deptment INDEX enplnane
REINDEX
SELECT 1
USE
SELECT 2
USE
RETURN
Each of the menu pads has a pull-down menu associated with it, showing
all the options for that main menu selection (see fig. 1.12). Not all main
menu pads can be selected at all times, and not all options are available at
all times. When an option is unavailable, it is dimmed and you cannot
select it. For example, if you select the Record menu pad when no
database is open, nearly all the options—which do things to a database
file—are unavailable.
Chapter 1: An Overview of FoxPro 45
caeBar
ses eerl on|| Fig. 1.11.
Menu Pads The FoxPro main
menu.
Fig. 1.12.
The File pull-
down menu.
Prfinter Setup...
@rint...
Quit
To select a main menu pad with a mouse, simply click the pad. To activate
the pull-down menu associated with a main menu pad, point to the pad
and drag the pointer downward; the pull-down menu appears imme-
diately. To select an item, continue dragging the pointer until the item
you want to select is highlighted and then release the mouse button. The
pull-down menu disappears, and FoxPro proceeds to do what you asked.
4 Part I: FoxPro Fundamentals
From the keyboard, selecting a main menu item is just as easy. Pressing
the Alt key or the F10 key highlights the first main menu pad, System.
Now you can use the right- and left-arrow keys to highlight the main
menu pad you want, or you can press the key corresponding to the first
letter of your menu choice. For example, pressing F highlights the File
menu pad. Pressing Enter brings up the pull-down menu associated with
that pad. To select from the options, use the up- and down-arrow keys to
move the highlight and press Enter when your chosen option is high-
lighted. The pull-down menu disappears, and FoxPro starts to work.
You also can activate a pull-down menu from the keyboard by pressing
simultaneously the Alt key and the key corresponding to the first letter of
your menu choice; the pull-down menu appears with the first option high-
lighted. As an example, pressing Alt-F causes the File pull-down menu to
appear.
Using Windows
FoxPro presents everything in windows. Windows can be opened, sized,
moved, zoomed, and closed. Some dialog boxes are windows of a sort and
also can be moved—but not sized or zoomed. Each of these actions can
be done with the mouse and from the keyboard, but they are more easily
done with the mouse.
After a window is opened (which occurs when you select a menu choice
that calls for a window), you may want to change the window’s size or
move it. To move a window with a mouse, simply put the pointer in the
title bar and drag the window to where you want it. You can drag the
window almost off the page, leaving only one border visible.
To resize a window, put the mouse pointer in the lower right corner,
where a small dot is located. Now drag that corner until the window is
the size and shape you want, releasing the mouse button to set the new
size. You also can zoom a window to take up all the screen by clicking the
Zoom symbol, the three horizontal lines in the upper left corner of the
window; clicking there again returns the window to its original or resized
dimensions.
Chapter 1: An Overview of FoxPro 47
Title Bar
You close the window by clicking the Close Window symbol, which is in
the upper left corner of the window, or by choosing Close from the Win-
dow menu.
Working with FoxPro windows by using a mouse is quick and easy. If you
have a mouse, you will never use the keyboard to move and resize
windows.
To resize a window, choose Size from the Window menu or press Ctrl-S.
Again, the borders start to flash. Now, however, using the four arrow keys
affects only the right and bottom margins, causing the window to change
its size. When you have changed the window to the size you want, press
Enter to set that size.
You also can zoom a window from the keyboard by pressing Ctrl-Z or
choosing Zoom from the Window menu. If the window does not occupy
all the screen, FoxPro will expand the window to do so; if you already
have zoomed the window, FoxPro will shrink it back to its original size.
Using Dialogs
Dialogs are the primary means of communicating with FoxPro. As with
windows, moving around dialogs is easier if you have a mouse, but key-
board users do have all the capabilities available to them.
Text Buttons
Text buttons are enclosed in angle brackets; examples include <Add...>
and <Modify...>. A text button enclosed in double angle brackets is the
default; <<OK>> is an example. When chosen, a text button causes FoxPro
to take some action. If an ellipsis follows the text button, another dialog
will open specific to that action. For space considerations, however, this
book omits the angle brackets when referring to one of these buttons.
With a mouse, choose a text button by moving the mouse pointer to the
button and clicking. From the keyboard, move the highlight to the text
button you want to choose and press Enter.
Check Boxes
A check box is a pair of square brackets next to an option. You use a
check box to turn on and off a setting described by the option name. For
example, there are check boxes for wrapping words, autoindenting, mak-
ing backups, adding line feeds, and so on. An X in the check box means
that the setting is turned on; no X means that the setting is turned off.
With a mouse, you can turn a check box on and off by pointing to the box
and clicking. If you’re using the keyboard, move the highlight to the box
and press Enter to change the setting. The text for some check boxes has
an underlined letter; you can change the setting of these options by press-
ing the key that is underlined.
Chapter 1: An Overview of FoxPro 49
Radio Buttons
Radio buttons are a series of choices, each with parentheses next to it;
you can select only one of the choices at a given time, just as you can
select only one station-selection button on your car radio. When you
choose one button, the others go off.
Figure 1.14 shows the Save Current Document As dialog with several ele-
ments. The elements present in this dialog are examined in the following
sections.
Fig. 1.14.
The Save Current
Save Current Document As:
Document As
rC..] dialog.
SAMPLE. PRG
« Save
SAMPLE. PRG
Scrollable Lists
The scrollable list appears in the box under the words Save Current Docu-
ment As. A scrollable list presents a list through which you can move
upward and downward to make a selection. With a mouse, use the scroll
bar to move through the list, and click on an item to select it. From the
keyboard, scroll through the list with the up- and down-arrow keys, and
select an item by pressing Enter while that item is highlighted.
Pop-Up Controls
Pop-up controls are boxes that have pop-up menus associated with them.
You can identify a pop-up control by the double line on the right and
bottom margins of the box. In figure 1.14, you use the Drive pop-up con-
trol to choose on which drive you want FoxPro to save the file. To acti-
vate the associated pop-up menu, point the mouse to the pop-up control
50 Part I: FoxPro Fundamentals
and drag downward to see the menu and make your selection. If you're
using the keyboard, tab to the pop-up control and press the space bar;
then use the up- and down-arrow keys to highlight your selection and
press the space bar again to activate it. Your new selection appears in the
pop-up control.
Text Boxes
A text box is simply a field that you use to give FoxPro some textual infor-
mation, such as a file name. If you’re using the keyboard, you can reach
the text box by tabbing to it; then enter the text from the keyboard.
Mouse users click the mouse in the text box and then enter the text.
Table 1.1
Keys Used To Move Around in a Dialog
Key Function
Chapter Summary
In this chapter, you learned that FoxPro and FoxBase + can give you con-
trol over large and complex data files and that, as you progress, FoxPro
and FoxBase +’s power grows with you. By working carefully through the
quick starts and the chapters that follow, you will become proficient in
the many areas of this powerful and easy-to-use program. You already
have become familiar with FoxPro’s unique windowing environment. Now
you're ready to move on, defining and creating your databases.
52 Part I: FoxPro Fundamentals
Designing and
Creating a Database
=TJT oxPro may be the most powerful and easy-to-use database system in
the PC world, but it cannot read your thoughts. You must tell FoxPro
what information you want to store in your database. And, for all its
power, FoxPro can be very inflexible sometimes. When you tell FoxPro
about your databases, you must be precise. As nice as it would be, you
cannot give FoxPro a command such as,
FoxPro can make a database designer lazy. You can make changes to a
FoxPro database so easily that you will be tempted to create your
databases “on the fly” and then change them later when you find they’re
not quite right. You can (sometimes) get away with this on simple
databases, but you will not always be creating simple databases. Changes
to big, multiple-file databases can be made as quickly, but the changes can
ripple through the entire database, affecting screens, reports, and pro-
grams. The time to think about your database and understand clearly what
you need from it is before you start talking to FoxPro. This is true for
even the simplest database. If you follow this practice for all your
databases, you will find the complex ones much easier to design and
implement.
In this chapter, you learn how to translate what you want from your
database system into something that FoxPro can understand and act on.
You go from the database idea to the database design to the database defi-
nition, which is what you describe to FoxPro. You learn how to define
and create indexes that affect the presentation and the processing of your
databases.
53
54 Part I: FoxPro Fundamentals
An old management saying goes, “If you don’t know where you're going,
any road will get you there.” That certainly applies to database design;
seldom will you build one or two files and find that’s all you need. Once
you get the database fever, you will think of more and more applications.
If you can, at the beginning, give your database a long-term goal.
It is, however, in the short term that you must get that first database up
and running. Again, clearly define what you want the first applications to
do. Do you want your inventory database to help your salespeople? Or
your credit department? You probably have a good idea of what you want
this application to do, but you should write down the objectives. These
objectives can be the first pieces of documentation in your database
dictionary
The first thing you should do is design all the reports that you want and
all the computer screens that you need. Be as clear and complete as you
can. Draw the reports on a piece of paper if that helps; do the same with
inquiry screens. Then you can ensure that the necessary data—and only
the necessary data—goes into the database. Figures 2.1 and 2.2 show a
sample inquiry screen and a sample report for a simple inventory
database.
Inventory Database
Stock Status Report
End of Report_
56 Part I: FoxPro Fundamentals
The second step in designing your database is to identify and name all the
pieces of data that you have put on your reports and screens. Because
FoxPro databases have a 10-character limit for data names, keep the
names short to ease the transition from paper to FoxPro. The data dictio-
nary in table 2.1 lists the data names given to the data for the sample
report and screen.
Table 2.1
Data Dictionary for Inventory Database
Report Data Elements
date
time
part _ number
keyword
description
quantity_on _ hand
reorder_ point
automatic_ reorder?
cost
total_rpt _ items
total_reorder_ items
part _ number
keyword
description
supplier
quantity_on _ hand
reorder_ point
automatic_ reorder
cost
price
comments
Is it essential to put all this in writing? Yes! One of the great mysteries of
the computer system design world is how everyone agrees that docu-
menting a system is absolutely necessary, but no one ever does it. I once
inherited responsibility for a huge inventory and purchasing system in
which my company had invested over $250,000; the documentation for
that system was a few handwritten notes and some comments in the code.
We ended up throwing out that system because we couldn’t make
changes to it.
Chapter 2: Designing and Creating a Database 57
So start right now to document all systems you create, no matter how
simple, by putting things on paper and storing the paper where you will
be able to find it. Probably the best investment you can make to ease your
database chores is a three-ring notebook and paper.
By defining what information must come out of a database, you also define
the information that has to go into it. Look at each piece of data that you
have defined as an output of your database. Where will the database get
that piece of data? Most of the data will enter your database in the same
format as it comes out. The part number that appears on the report and
inquiry screens will go into the database and be stored as is. But other
information may have to be calculated. If one of the outputs of the system
is, for example, the average invoice amount of a customer, the database
will not store that value, but it will store each invoice amount and can
calculate the average invoice amount.
You should read the database dictionary you are creating and make sure
that you understand how each piece of information will be derived. Table
2.2 shows a data dictionary listing the source of each piece of data.
Table 2.2
Data Dictionary for Inventory Database
Report Data Elements
date FoxPro
time FoxPro
part _ number inventory_ record
keyword inventory_ record
description inventory_ record
quantity_on _ hand inventory_ record
reorder_ point inventory_ record
automatic_ reorder? inventory_ record
cost inventory_ record
total_rpt _ items computed
total_reorder_ items computed
I
How do you decide whether you need only one database file or more
than one to store your data? This topic is covered in greater depth in Part
II, but for now, a quick introduction to database design will help.
Generally, in designing databases, you identify the clumps of data and put
them together into a database file. Then, if you want to tie together those
two files to look at all the orders for one customer, for example, you tell
FoxPro that a relation exists between the ORDER and CUSTOMER files.
FoxPro can provide both customer and order information at the same
time, correctly tied together.
Chapter 2: Designing and Creating a Database 59
If this seems confusing, fear not; by the time you get to Part II of this
book, which explores the multiple-file capabilities of FoxPro, your experi-
ence at designing and implementing single-file databases will have pre-
pared you well.
Now, back to your database. You have defined what data you want out of
your database, and you know what fields will store that information. Next,
you need to tell FoxPro about these fields. Besides the field names, you
must identify the order in which you want the fields in the database and
the characteristics of each field. You must lay out the data in the order
you want FoxPro to store it. Table 2.3 shows a listing of how you might
store an inventory database.
Table 2.3
Storing an Inventory Database
Database Definitions
part _num
keyword
descr
supplier
qty-onhnd
qty_ rorder
auto_rordr
cost
price
comments
picture.) All the data you put into, store, and get out of FoxPro must be
one of these types of data.
Character Data
Character data is text data—strings of letters and numbers. Examples of
character data include the following:
This sentence could be a (rather long) character field.
AX-4423-ABX
88923.23
Note that a number can be character data. You would, for example, store
a Social Security number as a character string, although it contains only
numeric digits 0 through 9.
A good rule of thumb in designing your database and its data types is to
use character data whenever possible. If you’re not going to perform
mathematical calculations on a number, store it as character data.
The reason for this rule lies in a database manager’s strengths. Nearly all
database managers, including FoxPro, are more efficient at working with
character strings. Database managers have more functions for character
strings, looking up data is faster with character strings, and it is more
accurate to store numbers as character strings. You will find your database
faster and more efficient, though sometimes slightly bigger, if you use
character strings wherever possible. Don’t go overboard, though; it is ter-
ribly complicated to do mathematical calculations on character data. If
you're going to add, subtract, multiply, divide, or perform some other
mathematical function on a number, store it as a number.
A character field can hold letters, numbers, and punctuation marks, plus
the special graphics characters used to draw boxes and symbols. Essen-
tially, if you can enter something from the keyboard, FoxPro will accept it
into a character data field.
You also must tell FoxPro how wide each character field is. Without con-
straining your database, keep character fields as small as possible. If you
need 25 characters for a name field, define it as such. But if you need only
20 and define the field as 25, you will store 5 extra spaces for every
record you put into your database. Those spaces add up, wasting disk stor-
age space and slowing down FoxPro.
Chapter 2: Designing and Creating a Database 61
Numeric Data
A numeric field holds numbers on which you want to do some calcula-
tions; this type of field holds numbers, a decimal point, and a leading plus
or minus sign. The widest a numeric field can be is 20 characters (but
FoxPro maintains only 16 significant digits internally). The plus or minus
sign and decimal point each use a space.
If you define a numeric field to be 20 digits long, only the first 16 digits
will be accurate; the two digits on the far right of the number may not be
accurate due to FoxPro’s limitation.
Float Data
A float field, like the numeric type, holds numbers, a decimal point, and a
leading plus or minus sign. A float field can be 20 places wide and, like the
numeric type, the decimal and plus or minus sign take one place each.
The float and numeric data types may sound identical, but internally, Fox-
Pro stores these two types differently. Operations on numeric fields are
faster, but sacrifice a small degree of accuracy when many calculations are
carried out on one value. Float data requires slightly longer processing
time, but maintains a higher level of accuracy. Float data is designed for
scientific processing; numeric data will provide an adequate level of accu-
racy for all but the most demanding calculations.
Logical Data
Logical fields can have one of two values: true or false. When entering
data into a logical field, you can enter only an upper- or lowercase T for
true, Y for yes, F for false, or N for no. No other values are accepted into a
logical field.
Date Data
Date fields hold—you guessed it—date information. The format can be
MM/DD/YY or the European DD/MM/YY, but you have to tell FoxPro
which date format you want with the SET DATE command.
FoxPro has extensive date manipulation capabilities. You can add to a date
a value representing a number of days. FoxPro will calculate the future
date representing the original date plus the number of days you added.
This feature is sophisticated enough that if you add .25 days to a date field
four times, the date field will increment by one day.
62 Part I: FoxPro Fundamentals
Memo Data
Memo fields have always held the promise of extraordinary capabilities,
but FoxPro brings that promise to fruition. A memo field enables you to
store any amount of textual data in a field that has been defined as only 10
characters wide in your database structure and all the input and output
screens.
To enter or see a memo field, you move to that field and press the Ctrl-
PgDn key combination. A full-screen text editor opens up the memo field;
you then can enter data or edit existing data in the field. The only limit on
the amount of information you can put into a memo field is disk size. You
can look for strings in a memo field, copy parts of a memo field to other
memo fields, or replace one memo field (or part of one) with another.
You will discover many uses for memo fields. One interesting use I have
seen is in a FoxBase+ system used for computer system design. The
memo fields store descriptions of the processes of the system, of the
database structure of the system, and of all the data dictionary informa-
tion. Some of these memo fields hold many pages of information.
Picture Data
The Picture field type is a vestige of FoxPro’s Macintosh heritage. The
Macintosh version of Foxbase+ can store graphics in a Picture field type.
FoxPro also has a Picture field type, but only to allow a FoxPro database
to import directly a Foxbase+ database created in Foxbase +/Mac. Once
the database with a Picture type is in FoxPro, you cannot see or work
with it. Fox Software says future versions of FoxPro may fully implement
the Picture field, but for now, you cannot use it.
Table 2.4
Database Dictionary
Database Definitions
Decimal
Element Name Type Length Places
Now you have defined what information you want to store, but you
haven’t told FoxPro in what order you want that information presented. If
you don’t tell FoxPro how to order the database, it presents it in the order
in which you entered it. If you enter the XYZ Company, the MNO Com-
pany, and the ABC Company, FoxPro will always list them in that order.
Although that may suit you for about 10 minutes, you will soon like to see
them in alphabetical order in one report, in ZIP code order in another,
and maybe in phone number order in a third. Or maybe you would like to
see your database sorted by ZIP code and alphabetically by company
name within each ZIP code. FoxPro can do it.
You could tell FoxPro to sort the database each time you want to look at
it differently. In a sort, FoxPro moves each record to its correct sorted
position. Sorts can take an amazingly long time on big database files, so
FoxPro provides a better way: indexes.
An index is a separate file that tells FoxPro the order of the database
records based on an index expression. Consider the example of the XYZ,
MNO, and ABC companies. If you defined an index on company name, the
index would tell FoxPro to present the companies alphabetically when
showing this database on-screen or processing it in a report. When you
have this index file open, any addition, deletion, or change of the database
automatically updates the index. Change the XYZ Company to the DEF
Company and the index immediately tells FoxPro to present the second
record, then the third, then the first, which reflects the new company
names. With the power of indexing, there is almost no reason to sort a
database. In fact, in five years of working with FoxPro, I have included a
sort routine in only one application.
64 Part I: FoxPro Fundamentals
A single-field index is the simplest index and the easiest to define. You use
this index when you want your database to be presented in an order
based on only one field. If you want the database listed on ZIP codes and
don’t care about the order of companies within the ZIP code, you define
an index on only ZIP codes.
1. In the Expression Builder dialog, pull down the menu from the
expression box titled String. You will see the many FoxPro
functions that take action on character strings, whether they are
database field values, memory variable values, or text strings you
enter. Figure 2.4 shows the String function pop-up menu.
Fig. 2.4.
The String
eee © function pop-up
CHR )
CHRTRANC, , menu.
CURDIR¢)
Field Names: DBF¢ ) Variables:
FIELD( >
> PART_NUM FILTER() > ALIGNMENT
KEYWORD FGETS(, ) BOX
DESCR FKLABEL( ) INDENT
SUPPLIER FREADC , ) LMARGIN
QTY_ONHND FULLPATHC , > PADVANCE
QTY_RORDER GETENU( ) PAGENO
PRICE GETFILEC, > PBPAGE
COST ei
so)
ne
di
eee
}le LEFT(, ) PCOLNO 2
40>
ed
Al
ae
>
4a
LOWER( )
LTRIMC )
MESSAGE( )
v
2. Scroll through the string functions and pick the function Upper©
by double-clicking it with the mouse or selecting it with the up-
and down-arrow keys and then pressing Enter. FoxPro places the
function Upper© in the Expression Builder box. This function
causes FoxPro to change all the characters in a character string
you place in the parentheses to uppercase characters. Characters
already in uppercase are not changed. For example, if you use the
expression
Upper("FoxPro”)
Upper(CUST_ NAME)
tells FoxPro to index the database on the values in the CUST_NAME
field, but only after converting them to uppercase. The actual values in
CUST_NAME are not changed.
Fig. 25.
The completed INDEX ON: ‘expr?
Es) |Es
expression in the UPPER( invntry->part_num)_
Expression
Builder. Field Names: Database: Variables:
FoxPro expressions can be quite complex, with many fields and functions.
Many index expressions will be combinations of fields. In your example
inventory database, you might want to list suppliers alphabetically, then
by the part numbers that come from that supplier. To do this, you would
define an index on the expression
SUPPLIER + PART_NUM
Deserts
INUNTRY =
E-2515C ; INTEGRO
E-Z515E ; INTEGRO Fig. 2.7.
E-2516A : INTEGRO Using the index
E-2516B . INTEGRO ;
E-2516C INTEGRO expression Upper
E-2516D j INTEGRO (CUST_NAME) +
E-2524 ; : INTEGRO ZIP
A-41813-123 4 : WASNER 722-59 .
B-1826 INTTEGRO
61934-8
61934-9
RMP4-128 SHOE RETAINER SPRING
8615-1648 SHOE ADJUSTMENT LEVER L.H
8615-1784 SHOE ADJUSTMENT SPRING R.
4019-26 SHOE LINING R.H.
4019-17 SHOE ADJUSTMENT LEVER R.H
XPPZ-915 SHOE ADJUSTMENT WEDGE GUI
XPP2-926 SHOE RETRACTING SPRING
Now you have accomplished the hard part of creating a database: you
have defined it and designed it. All that remains is to tell FoxPro what you
decided.
68 Part I: FoxPro Fundamentals
Fig. 2.9.
The New dialog.
Database
Program
File « OK »
Index
Report « Cancel >
Label
Form
Chapter 2: Designing and Creating a Database 69
The Structure dialog, shown in figure 2.10, is the heart of the definition
process. In this dialog, you define the fields of the database to FoxPro.
<Insert>
<Delete>
« OK »
«Cancel >
Notice that the structure is Untitled. You can save the structure at any
time during the definition process. You are asked for a name, which must
be a legal MS-DOS name (it must start with a character; contain only char-
acters, digits, or an underscore; and can be no more than eight characters
long without spaces). FoxPro automatically appends a DBF extension,
indicating that this is a database file, but you will never need to work with
the extension.
The number 3999 in the lower right corner represents the maximum
length of a FoxPro record. As you add fields to your database definition,
this number will be reduced by the length of each field. You can tell how
much room you have left in your database definition by referring to this
number.
You can insert or delete fields, if you want. Should you realize that you
have left out a field (remember, the order you choose is the order in
which they initially are displayed in Browse windows), you can highlight
the field that the omitted field should follow and choose Insert, which
will put a new, empty field before the highlighted field. The order of the
field has little effect on FoxPro’s performance, but it helps to have the
fields you most want to examine at the top; they will always appear in the
Browse window.
70 Part I: FoxPro Fundamentals
You also can move fields up and down in the structure. Use the arrow
keys to highlight the arrow symbol in the far left column. Press the space
bar to choose the field. Now move the up- and down-arrow keys to move
the field up and down in the structure. When you have moved the field to
the right place, “drop” it by pressing the space bar again.
Press Tab again to move to the Width column, where you enter the width
you defined for the field. Memo, logical, and date fields have set lengths
that you can’t change. If the field is numeric or float, you also must define
the number of decimal places. Pressing Enter or Tab again moves to the
next empty line. Press Tab from an empty line to move to OK, and you are
finished. Figure 2.11 shows a complete customer database structure.
Fig. 2.11.
A completed Structure: Untitled
Name Type Width Dec
Structure dialog.
+ PART_NUM Character I
3 KEYWORD Character <Insert>
+ DESCR Character
+ SUPPLIER Character <Delete>
+ QTY_ONHND Numeric
+ QTY_RORDER Numeric
+ Numeric
+ Numeric « OK »
t AUTO_RORDR Logical
t COMMENTS Memo <Cancel >
When you click 0K, you see the Name File dialog in which you give the
database a name. The scrollable list shows database files that already exist,
so you know what names not to use for the new one. FoxPro asks
whether you want to enter database records. Answer Yes, and you see the
default data-entry window; answer No, and you return to the FoxPro Com-
mand window.
CREATE dbf_name
You see the FoxBase+ input screen in which you enter the field names,
types, and sizes (see fig. 2.12). FoxBase+ users don’t have the flexibility
of moving fields or the scrollable lists of types, but the process is the same
otherwise. When your’re finished, press Esc to return to the FoxBase +
command line.
| a cE a a
CREATE (2s Se
Enter the name field.
TET ‘ON CRNA
Field names begin with a letter and may contain letters, digits and underscores
If you want to set indexes on this database, now is the time to do so.
Defining Indexes
Just as you defined the database structure to FoxPro, you must define the
indexes you want FoxPro to maintain on the database. Do this by first
whys Part I: FoxPro Fundamentals
opening the database (if you haven’t already done so), and then selecting
View from the Window menu. You see the View dialog, shown in figure
2.13. From this dialog, choose Setup, and you see the Setup dialog, shown
in figure 2.14.
Fig. 2.13.
« View > Work Areas « Relations >
The View dialog.
<On/0ff > > INUNTRY 4
+
‘Files >
«Browse?
«Close >
> PART_NUM
KEYWORD
DESCR
SUPPLIER
Fields: 18 Length: Index expr:
Index filter:
Lod Setekields:..
€ 2 On ¢*) OFF
Pa Filter...
{C ] Format...
The Setup dialog controls how FoxPro will present your database, either
on the screen or in reports. Before you define the indexes, you should
look at several other display options.
Chapter 2: Designing and Creating a Database 73
The FILTER command does just that; you tell FoxPro to filter the database
records according to a criteria you set and to act as if only those records
meeting the criteria exist. If, for example, your filter is
ZIP = '98058'
FoxPro ignores all records without that ZIP code, acting as if they don’t
exist. Again, you can set a filter from the FoxPro Command window with
the same command FoxBase+ users would enter:
The FORMAT command enables you to specify a Form file you have cre-
ated with FoxView to be used when entering, editing, or displaying
records.
Creating Indexes
To define the index, select the work area containing the database, open
the Setup dialog, and select Add. You see the Open Index File dialog
shown in figure 2.15.
Fig. 2.15.
Open Index File:
The Open Index
Drive File dialog.
Directory CHAP1
« Open
« Cancel
{ J] All Files
74 Part I: FoxPro Fundamentals
From the Open Index File dialog, select New to tell FoxPro this index file
does not already exist. Next, you see the Index On dialog, shown in figure
2.16. If you want to index on a single field name, select that field and
press Enter. The field name appears next to the Expr text box, telling you
that FoxPro will create an index on that field.
Fig. 2.16.
The Index On INDEX ON:
dialog. PART_NUM
KEYWORD
DESCR « OK »
SUPPLIER
QTY_ONHND « Cancel >
QTY_RORDER
CEXpP a
C J] Unique
COROT aimee
FoxBase + users, and FoxPro users who like the speed of the command
line, can create indexes more quickly from the command line with the
command
FoxPro or FoxBase+ will open the database dbf_name and attach the
index files tndex_namel and index_name2, the first index named will be
the controlling index.
In FoxPro you also can use the View Setup dialog to add index files. You
also can tell FoxPro at this time which index file will control the database.
From the FoxPro Command window, or in FoxBase + , you can change the
controlling index from the command line. If you have opened the
database and index files with the command
SET ORDER TO 2
This command tells FoxPro and FoxBase+ to use the index listed second
in the original opening index list as the controlling index. To set the con-
trolling index to the PHONE index, you enter
SET ORDER TO 3
76 Part I: FoxPro Fundamentals
In FoxPro, if you have opened the database file and attached the indexes
through the View Setup dialog, the way the indexes are listed in the
scrollable list index window is the order you refer to in the SET ORDER
command syntax.
To define a view, set up your database and index files with the filters,
fields, and formats you want in the View window. From that window,
select Save from the File menu. You see the Save View As dialog, shown in
figure 2.17. When you select Save, all information about which database
files are open; which indexes are attached to them; and which filters,
fields, and formats are in effect are saved to the View file. To return to
that environment, select Open from the File menu, click the View radio
button, and select your view.
Chapter 2: Designing and Creating a Database “fap
Fig. 2.17.
Save View as:
The Save View as
dialog.
Directory
wes |CHAP1
C J] All Files
INUNTRY_
From the FoxPro or FoxBase + command line, you save a view with the
following command:
Chapter Summary
Designing and defining your database is the heart of your database system.
In this chapter you have learned how to analyze the objectives and
requirements of your database, and how to translate those objectives and
requirements into a Fox database. This is an important milestone because
now you can create one, two, or many databases to suit your needs. Fox-
Pro places no limits on how many databases you can create and use.
78 Part I: FoxPro Fundamentals
Entering, Editing,
and Viewing
Information
ae you might imagine, database systems need data. Once you have
=> defined the database structure to FoxPro, it’s time to start using the
real power of this program: its capability to receive data, store it, and pre-
sent it in useful ways.
In this chapter, you learn how to enter data into a FoxPro database, how
to edit that data, how to look at it in different ways, and how to delete it.
If you use only FoxPro’s default data-entry screen and the default View
window, you will gain much from your database, but if you go a step or
two further, learning how to use some of FoxPro’s sophistication, your
database management system will be much easier to use and much more
powerful.
ey)
80 Part I: FoxPro Fundamentals
tom data-entry and inquiry screens in FoxPro), each field of the database
has a text field in which you enter information.
Fig. 3.1.
FoxPro’s default
data-entry screen
Sor INVNTRY.
»>Comments Memo
When you are entering data, if you don’t fill a field completely, but are
done with the entry, press Enter to move to the next field. If you fill the
field, FoxPro sounds a beep and moves you to the next field. If you like,
you can change these settings in the View Set-up On/Off dialog. Set Beep
to Off and Confirm to On. When Confirm is On, you must confirm that
you’re finished with data entry in a field by pressing Enter.
When you have filled all fields for a record, FoxPro moves to the first field
of the next record (see fig. 3.2). This pattern continues until you press
Esc, to stop, or you choose another window from the Window menu.
Chapter 3: Entering, Editing, and Viewing Information $1
From other places in the FoxPro environment, you can display the data-
entry window by choosing Append from the Record menu. The window
displays a blank record for you to fill. As before, when you're finished
with one record, another is presented.
If you make a mistake but don’t realize it until you have left the field, you
can use PgUp or PgDn to move to the field with the mistake in it. Then
you can use the standard text-editing functions to correct your mistake.
You can even move back to previous records to correct errors.
FoxView can create very complex and sophisticated screens for entering
and viewing data (accessing up to 25 different databases at once), yet it
can be used by a beginner to create simple screens. To understand how
FoxView works, in this next section you create a screen for the INVNTRY
database.
82 Part I: FoxPro Fundamentals
FOXVIEW
FoxView begins with a Logo screen, which you clear by pressing Enter.
Next, you see a screen that looks much like an MS-DOS screen (see
fig.73:5)).
You can enter many commands from the prompt on the screen, but for
now, all you need to do is tell FoxView what database file you want to
create a screen for. To do this, enter
When you type the USE filename command, FoxView creates a table that
contains all the information FoxPro needs to present information about
each field. FoxView also creates a default screen. You could use the
Chapter 3: Entering, Editing, and Viewing Information $3
screen as is, but FoxView’s purpose is to enable you to change the screen,
making it more pleasing to the eye and easier to use.
To see the default Screen FoxView has created, press the F10 key. A new
screen opens, and you see a list of your database fields, with an area for
data entry for each field (see fig. 3.4). As you can see, this screen is a little
primitive. Figure 3.5 shows a more pleasing screen, which you can design
and create in FoxView.
Part_num
Keyword
Descr Fi
IZ. 3.4.
Supplier
Qty_onhnd The default form
ee
ric
FoxView creates
Cost for INVNTRY.
Auto_rord
Comments
A custom-
Part Number: Keyword: Description: designed form
eee LP Rae for INVNTRY.
Supplier:
Qty Onhand:
Reorder Level:
Automatic Reorder?
Comments:
84 Part I: FoxPro Fundamentals
In the default screen, a data area exists for each of the fields in your
database as does a label associated with the data area. Each of these label/
data-area combinations are called objects. In FoxView, you can move
these objects to new locations and modify how they present data and
receive data from the keyboard. You also can add new objects, such as a
text string or boxes. Initially, it is easier to accomplish this on-screen, but
later you will see how to make changes in the FoxView table of this
screen.
If you want to see the table that FoxView has created for this data-entry
screen, press F10. You can see that the table, shown in figure 3.6, main-
tains information about each of the fields, including its location on-screen,
what database field information it will accept or display, the label for the
field, and other necessary information. As you make changes to the data-
entry screen, they are reflected in the table. Likewise, if you make a
change to the table, it is reflected in the screen. You can switch between
the Screen and Table views by pressing F10 at any time. For screen
design, you will find the Screen view easier to work with, because it is a
real WYSIWYG (What You See Is What You Get) screen. As you make
changes, remember that you cannot undo them; a change is recorded
immediately.
C: INUNTRY. DBF
t. Als Field Typ Wid Dec Label Hue Row Col Pag (Fld) (Atr) Place
1 CPart_num Z 1
Fig. 3.6. Z Keyword CKeyvord DD
3 Descr (Descr
Table view for 4, Supplier CSupplier
the default 5. Qty_onhnd CQty_onhnd
6 Qty_rorder CQty_rorder
INVNTRY form. iG Price (Price
8 Cost [Cost
3 Auto_rordr CAuto_rordr
18.
8 Comments
DovDoDvDDDODDOWOVWOVOD
OO
x=PMZ2ZZZOO[Comments ee
HDBDDD
DDDFP
bw ee
Owonornu
®&
08
oc0
vea
Nove
the database designer, you know what each field means, but if someone
else uses this screen, will they know that Auto_rorder defines whether
that part should be automatically reordered at a certain point? Probably
not, so you need to change the rather cryptic labels to something more
understandable.
To do this, move the highlight, using the Tab or arrow keys, to the object
whose label you want to change; the selected object will change color.
When you reach the object you want to change, press the space bar. The
current label appears in the lower left corner of FoxView. You use Fox-
Pro’s standard text-editing functions to change the label. When you press
Enter, FoxPro accepts the change and places it on-screen. As you change
the label in the lower left corner text window, it also changes on-screen.
You cannot leave this field without recording changes. You can, of course,
edit the field back to its original state.
Moving objects on-screen also is easy. Select the object you want to move
by highlighting it and pressing F3. You use the arrow keys to move the
object to the new location.
To move several objects at once, press F6, use the arrow keys to select
the objects, and press Enter to finish the selection. The F3-Move function
moves all objects selected.
Many times, certain fields look better if the label for the field is above the
field, such as the top row on the INVNTRY screen. To accomplish this,
select the field and press Ctrl-T. The data-entry field moves below the
label. Figure 3.7 shows the data screen with new labels and a better
design. Still, it seems a little stark, but FoxView will help you remedy that
problem.
Fig. 3.7.
The redesigned Part Number: Keyword: Description:
INVNTRY
database form. Suppl ier:
Price:
Cost:
Qty Onhand:
Reorder Level:
Automatic Reorder?
Comments:
edited and
Supplier:
moved to form a price:
title. Cost:
Qty Onhand:
Reorder Level:
Automatic Reorder?
Comments:
To add a box, select the Box menu by pressing Ctrl-B. You are presented
with a pop-up menu showing the different types of boxes available (see
fig. 3.9). Choose the box you want. FoxView returns you to the screen,
with a new “box object” in place and selected. Use the arrow keys to
move the box on the form. Pressing F4 enables you to size the box. It’s
easiest first to move the upper left corner of the box to where you want
it, and then change the box’s size.
Now that you have the FoxPro screen as you want it to look (as shown in
figure 3.10), you may want to improve the way the data fields handle
their data.
It is easiest to work from the Table view when specifying how you want
fields to look, so if you’re in the Form view, press F10 to move to Table
view. You can see the table has columns for each object on-screen. In the
table, you can change any of the characteristics of each object, including
8 Part I: FoxPro Fundamentals
Qty Onhand:
Reorder Level:
Automatic Reorder?
Comments:
color, size, and appearance. For now, you will be working with the Picture
column, which controls the appearance of data in the field. To reach the
Picture column in Table view, press Tab until the Table scrolls to the
right, bringing into view the Picture, Range, Valid, and Calc columns.
FoxPro and FoxView use two types of codes to determine how data
appears in a data field and what data FoxPro accepts into that field. These
two codes are called Function codes and Picture Template codes.
Although these codes appear similar and have similar actions, the scope of
their actions differs. Function codes apply to the entire field. If you put
into the Picture column the code to make characters uppercase (@!), that
function applies to all characters in the field—all characters will be forced
to uppercase, regardless of what the user enters. To enter a Picture clause
or Function code, Tab until the Picture column for the chosen field is
highlighted. Then type the Picture clause or Function code wanted.
You can combine Function codes and Picture Template codes in one field.
You can specify a Function code to apply to the entire field, such as the
code to put negative numbers in parentheses, and then specify Picture
Template codes to place dollar signs, commas, and decimals in the
number.
Chapter 3: Entering, Editing, and Viewing Information 89
"@function_code picture_code"
When using these codes in FoxView, leave out the double quotation
marks. The @ character identifies the subsequent characters as Function
codes. You can place multiple Function codes after the @ ("@!R”, for
example), but at least one space must separate the last Function code
from the first Picture Template code.
Function and Picture Template codes are, at best, confusing for beginning
FoxPro and FoxBase+ users. Some examples follow:
The R Function code specifies that characters other than Picture Template
codes exist in this picture. Codes other than Picture Template codes are
displayed but not stored when the data is entered. The value for this data
field in the database is 1223.
When designing a database, you often will know that the data going into
numeric fields should fall into a certain range. You can tell FoxPro not to
accept values outside the range; if the user tries to enter such a value,
FoxPro will beep and prompt for the data again. FoxPro will continue
doing that until the data is in the range or the user leaves the data-entry
screen. You set the range using the Range column in FoxView. You are
prompted for the upper and lower range limits.
7 Part I: FoxPro Fundamentals
To convert your screen design to a Format file, press Esc to access the
FoxView menu, and then use the arrow keys to choose Gen. If Select
From Template List is not highlighted, use the up- and down-arrow keys
to highlight it, and press Enter. From the next window, titled TEMPLATES,
choose FORM1 Format File Generator. FoxView asks you to provide a
name for your format file. Enter the name (for this example, you enter
INVNTRY, the same as the database) and press Enter. FoxView creates the
FoxPro program code for the Format file. If you want to see this code to
learn how FoxPro provides screen input and output, you can open this
program file from the FoxPro File menu.
Now, having finished your FoxView chores, choose Quit from the File
menu (saving any files FoxView asks you to save) and return to FoxPro.
Now choose Append from the Record menu. Instead of the dull default
screen, your masterpiece appears, ready for your input. The Format file
operates on Append and Change commands. You can use all options on
the Record menu to find a specific record, and then select Change from
the Record menu to edit the record with your custom form. Figure 3.12
shows the custom screen with a record in place for editing with the
Change option of the Record menu.
Chapter 3: Entering, Editing, and Viewing Information OI
{ ] All Files
Key Function
Viewing Information
Now that you have learned how to get data into your database, it is help-
ful if you also are able to see that data. Reports may be important, but
even more important is your capability to look at the data on-screen and
to browse through it, reviewing and changing it if necessary. For this type
of database work, FoxPro provides the versatile Browse window.
As you can see, the Browse window is a standard FoxPro window. It can
be moved, sized, and zoomed like any other window, using the keyboard
or a mouse. You can move up, down, and sideways in your database by
clicking the appropriate mouse markers or using the PgUp, PgDn, and Tab
keys. If you want to make a change in the Browse window, move the high-
light to the appropriate field and make the change. The Browse window is
Chapter 3: Entering, Editing, and Viewing Information
93
System File Edit Database Record Program Window Browse
rightly named; you can browse through your database much as you
browse through a department store.
The Browse window can make your browsing easy. You can split the win-
dow, change the sizes and the order of the fields, show only a subset of
the fields and, in general, customize the Browse window to your
purposes.
In the Setup dialog you also can specify a filter condition. A filter is essen-
tially a database record sieve. To set up a filter, you tell FoxPro, using the
Expression Builder dialog that appears when you mark Filter in the Setup
window, what condition must be met before a record can be displayed.
You can, for example, set the filter to
and FoxPro will display in the Browse window only those records in
which the value in the ZIP field is greater than 90000. Like the fields mod-
ifier, the filter is in effect until you turn it off or specify another.
9 Part I: FoxPro Fundamentals
Database:
<Cancel >
INUNTRY i,
sass « OK »
Often you will want to view several fields that are too far apart to see in
the Browse window at the same time. You move fields in the window by
selecting the field you want to move and choosing Move Field from the
Browse menu. Then you use the left- and right-arrow keys to move the
field. Mouse users can accomplish this task even more easily; you grab
the heading of the field you want to move and drag it to its new loca-
tion. Figure 3.15 shows the QTY-ONHND field moved between the
PART_NUM and KEYWORD fields.
Gty_onhnd|keyword
[Descr_
189468 FRAME
Fig. 3.15. 203128 ARMATURE
The OTY_ONHND 2047168
ers TORQUE CONVERTER
field moved 232719
within the Sater
Browse window. 301739 SEAT CUSHION
323468 SEAT CUSHION
449261-0C
5861468
5807808
5818583-18 PISTON ROD
5828807-88 SDeKRePN
OTHEN
WwW
DOAN
OY W7 SINGLE SWITCH
Chapter 3: Entering, Editing, and Viewing Information 95
To do this, choose Resize Partition from the Browse menu. You can use
the right-arrow key to move the Browse window to the right, revealing
another identical window underneath. (Mouse users can drag the partition
marker in the lower left corner to move the top window.) You can move
the top window as far as you want (within the bounds of the Browse win-
dow). Figure 3.16 shows the partitioned Browse window. You now have
two Browse windows in which you can scroll left and right indepen-
dently. To move from one window to the other, press Ctrl-H.
Notice that the two partitions scroll together vertically as if they are
linked together. If you want to unlink them, choose Unlink Partitions from
the Browse menu so that the two are independent both horizontally and
vertically. When you jump from one partition to the other, however, the
second partition will always scroll to make the record currently selected
in the first window also active in the second. Suppose that, in a 1,000-
record database, you had the first record active in the left partition and
were showing the last record in the right. Jumping from the left to the
right window would cause the right window to scroll so that the first
record would also be active in that partition. If this seems confusing, just
try it a time or two.
96 Part I: FoxPro Fundamentals
To seek a record, choose Seek from the Record menu. FoxPro presents
the Expression Builder dialog to create the seek expression (see fig. 3.17).
The expression must match the indexed expression, which is shown in
the border above the Expression Builder window. If your index is a com-
bination of fields or some other valid FoxPro expression, your seek value
must be the same, or FoxPro returns an error message. If FoxPro suc-
cessfully locates the record, use the Browse option to show the field at
the top of the Browse window, and use the Edit option to put the found
record in the Edit window.
Chapter 3: Entering, Editing, and Viewing Information 97
If FoxPro cannot find the field you’re looking for, it returns a NO FIND mes-
sage. (Unfortunately, this message may be under the Browse window. If
the Browse window returns with the first record highlighted and that isn’t
the record you’re seeking, the seek was unsuccessful.) If the Near setting
is on (set in the View On/Off window), the database will be positioned
immediately after the closest record. If Near is set to off, the database will
be positioned at the first record of the database.
You also can use the Find option to search for character strings, but any
experienced FoxPro user will recommend that you use Seek; it is more
versatile and reliable.
From this dialog, use the Scope option to tell FoxPro which record num-
bers to find—all, the next record, a specific record number, or the rest of
the records. If you select For or While, you will build an expression in the
Expression Builder dialog. You enter the expression you’re searching for
and the field in which you’re searching. If the expression is valid, FoxPro
will start at the beginning of the database and look through each record
until it finds one matching your locate expression.
98 Part I: FoxPro Fundamentals
Once you find the first record that matches your locate expression, you
can find subsequent ones by choosing Continue from the Record menu.
FoxPro resumes the search from the record it just located until it finds
the next one matching your locate expression. You can go on until you
reach the end of the database file, and you can continue these subsequent
searches as long as the Scope, For, or While clauses are valid.
Deleting Data
Although some databases seen to grow eternally, the time always comes
when you must delete data. FoxPro makes this an easy process, even giv-
ing you the chance to change your mind before it actually throws your
data out of the system. Up to a certain point, deleted data can be recalled
into the database.
Marking Data
Deleting data in FoxPro is a two-step process. First, you mark a record for
deletion, then you pack the database. Packing a database permanently
removes all records marked for deletion. Until you pack a database,
marked records are not really gone.
You can mark a record for deletion as you browse through the database.
When you come to a record that you want to delete, press the Ctrl-T key
combination. A mark will appear to the left of the first field in the
database, telling you that the record has been marked for deletion. If you
make a mistake, press Ctrl-T again, the record’s deletion mark disappears,
and the record is not deleted.
You also can delete data from the Record menu; when you choose Delete,
you see the Delete dialog. The Scope option refers to the number of
records, beginning with the current one, that you want to delete. If you
choose Scope, the Scope dialog appears to get that information from you.
Chapter 3: Entering, Editing, and Viewing Information 99
Deleting with the For option enables you to build an expression to delete
every record in the database that meets the expression. If you want to
delete all records that have a 0 in the QTY-ONHND field, you would spec-
ify the expression ’
QTY-ONHND = 0
FoxPro then marks for deletion every record in the database whose
QTY-ONHND field contains 0.
The Whi le option of the Delete dialog also enables you to build an expres-
sion that FoxPro will evaluate to determine whether to mark a record for
deletion. Like the For option, you use the Expression Builder dialog to
build the expression.
The For option evaluates every record in the database; you are saying to
FoxPro, “For every record that meets this expression, delete it.” On the
other hand, the While option tells FoxPro, “Start at the current record,
and step through the database, marking each record for deletion while
they meet the expression.” With the While option, FoxPro stops marking
when it comes to the first record that does not meet the expression;
when using For, FoxPro skips over records not meeting the expression
and continues until the end of the database.
For all practical purposes, a record marked for deletion is ignored by Fox-
Pro. Reports don’t report them, inquiries don’t find them. Some Scope
commands count records marked for deletion in their actions, but should
this become a problem, the SET DELETED ON command causes them to be
ignorerl. Records marked for deletion appear in the Browse window
unless you select SET DELETED ON; then they will not appear, though they
remain in the database.
Records marked for deletion still take up space in the database, and Fox-
Pro must pass over them in operations. Anytime you can streamline your
database by reducing its size, you will improve FoxPro’s efficiency. Don’t
allow your database to be cluttered with deleted records; if you find
you're deleting many records, pack the database frequently to remove
them.
Recalling a Record
You can bring back a record marked for deletion by using the same set of
actions you used to mark it. Ctrl-T unmarks a single record. Choose the
Recall option from the Record menu to use the Scope, For, and While
commands. When you recall a marked record, it is unmarked, and it
rejoins the other records as a full member of the database.
100 Part I: FoxPro Fundamentals
To pack a database, choose Pack from the Database menu. The Pack
option discards records marked for deletion and reclaims the space they
used, Once you have packed a database, records marked for deletion are
gone permanently. If you have index files opened, FoxPro automatically
updates the indexes to reflect the deleted records.
Chapter Summary
Entering, editing, viewing, and deleting data in a database are the day-to-
day, mundane tasks of data management. These tasks are seldom much
fun, yet they are as essential as database design and fancy reports. As
you work with FoxPro, you will become experienced at using the tools
FoxPro provides to ease the tasks of entering data, and reviewing and
deleting it.
Sorting and
Summarizing Data
= ow that you have learned how to design a database, define it to Fox-
= Pro, and enter and edit information in it, you’re probably ready to
get something out of it. The strength of any database system is its capacity
to show you summaries of information in new and different ways. With
FoxPro, you can view and summarize your database from many new
perspectives.
In this chapter, you learn how to tell FoxPro what information you want
from your database; how to build FoxPro expressions, which are really
nothing more than filters on the database, allowing you to specify explic-
itly which records and data FoxPro should use when processing your
commands; and how to sort and index a database in different ways, pro-
viding different perspectives on the information in the database. Memory
variables, which you use to store and display summary information, also
are introduced. And you will put this information together to learn how to
use the Scope, For, and While commands to summarize data on just the
parts of the database you specify.
101
102 Part I: FoxPro Fundamentals
the Database menu. FoxPro brings up the Sum dialog, which gives you
four options: Expr, Scope, For, and While. Choose Expr, and the Expression
Builder dialog appears (see fig. 4.1). Here you tell FoxPro what you want
summed. By selecting the qty_onhnd field and then choosing OK, you tell
FoxPro to sum all the values in that field. Make this, selection now, return
to the Sum dialog, and then choose OK.
Fig. 4.1.
The Expression
SUM
Peo] Gow] Fon] Ce]
Clause: <expL>
Builder dialog.
On the screen, FoxPro tells you how many records it has summed and
shows the results of the summation (see fig. 4.2). You can use the Sum
option when you need to know the total of a numeric field in your
database.
If you use the Average option in the Database menu, you get the same
dialogs, and FoxPro tells you the average value of a numeric field—the
total amount of all the fields divided by the number of records FoxPro
summed.
Choosing Count from the Database menu brings up the Count dialog (see
fig. 4.3). The Count dialog looks much like the Average and Sum dialogs,
but it has no Expr option. Count simply counts records. For now, choose
Scope from the Count dialog, and the Scope dialog appears (see fig. 4.4).
Chapter 4: Sorting and Summarizing Data 103
= Command.
use inyvntry
SUM
<
Fig. 4.3.
The Count
Memory Variables: dialog.
feakScope.,
fo) For...
< Cancel >
Co Whilles..
To Variable:
Fig. 4.4.
The Scope dialog.
Eee Scopes...
« Locate »
C&T For...
« Cancel >
{C J] While...
These three Database menu options— Average, Count, and Sum—can pro-
vide information about your database, but they are rather limited. FoxPro
is not limited, though; using expressions, you can have FoxPro do sophis-
ticated searches and summaries for you.
Examining Expressions
Perhaps the best way to understand the term expression is to see how it is
specified on the command line of FoxBase + or in the Command window
of FoxPro. Suppose, for example, that in the INVNTRY database, you want
to get the total of the inventory on-hand for all parts with a cost greater
than $4. First ensure that the INVNTRY database is open and then issue
the command
The expression is
The preceding expression was a simple one. Now suppose that you want
to count how many records exist whose PART_NUM starts with IN and
whose QTY_ONHND is zero. The expression is
is open and the controlling index is on the keyword field. You will per-
form a Locate operation on this database. Locate requires an expression to
tell FoxPro what record to locate. With the INVNTRY database opened
and indexed on keyword, choose Locate from the Record menu.
Figure 4.5 shows the Expression Builder dialog that FoxPro uses to get the
Locate expression; this dialog appears when you choose For or While from
the Scope dialog after you select Locate from the Record menu.
Fig. 4.5.
The Expression
FOR Clause: <expL> : q
Builder dialog.
In the Title bar of the Expression Builder box, you see the phrase FOR
Clause: <expL>. FoxPro is telling you that it needs to construct a logical
expression (one that evaluates to either true or false). FoxPro will evalu-
ate the logical expression for each record in INVNTRY, stopping the
search when it reaches one for which the logical expression evaluates to
true.
To find the first record in the INVNTRY database with a keyword of SEAL,
select the field KEYWORD from the field picker. The phrase
invntry—>keyword
appears in the Expression Builder box. The cursor is at the end of this
phrase. Enter
= SEAL!
Choose OK and Locate from the Scope dialog to send FoxPro on its Locate
mission.
108 Part I: FoxPro Fundamentals
When you have a valid expression, select OK. Immediately, FoxPro starts at
the first record in the database to see whether the value in the keyword
field is SEAL. As mentioned earlier, expressions are actually logical tests.
In this case, for each database record, FoxPro evaluates this equation:
KEYWORD = “SEAL”
If the expression is false, FoxPro goes to the next record. If the expression
is true, FoxPro stops and points to the record.
To see that FoxPro has really accomplished its task, browse the INVNTRY
database; you will see that the first record with a keyword of SEAL is
highlighted.
Math Functions
Math functions return a numeric value, usually taking a numeric value as
input. SUM() is a math function, returning as a numeric value the sum of
Chapter 4: Sorting and Summarizing Data 109
specified fields. The input to a math function is often numeric, but not
always. The LEN() function, for example, takes as input a character vari-
able and returns the numeric length of the variable; LEN(“This is so much
fun!”) returns 19, the length of the string argument. Another example of a
math function is MIN(<expr1>,<expr2>[, <expr3>...]), which returns
the minimum value of the input arguments. The opposite of MIN is MAX.
SQRT(<exprN>) returns the square root of the numeric argument.
String Functions
String functions return character strings, usually taking character strings as
arguments. String functions are valuable tools for modifying strings. If, for
example, you want to change all characters in a field to uppercase letters,
you can simply specify the expression
Logical Functions
Logical functions always return a true or false value. A logical function
used often in FoxPro programming is EOF(), which stands for End Of File.
If the database is currently positioned at the end of the file (actually, on
the “phantom” record that exists after the last real record), EOF() returns
TRUE, telling you that you’re at the end of the file. Another logical func-
tion is BOF(), which is the converse of EOF(). BOF() returns TRUE if the
current position in a database is at the beginning of a file.
Date Functions
FoxPro is proficient at manipulating and working with dates. The date
functions return different types of results, but all are related to dates in
some way. An example of a date function is DOW(). When you give
DOW() a date argument, it returns a number representing the day of the
week. Another date function is MONTH(), which returns the number of
the month in the date argument.
1 10 Part I: FoxPro Fundamentals
Note: | You often cannot enter a date value directly from the key-
board. If, for example, you enter the function
? DOW(12/25/90)
FoxPro gives you the error message Invalid function argu-
ment value, type or count. The DOW() function requires a
date, but because of the 12, FoxPro thinks you have put in a
numeric function. To put a date into this function, use the
Character To Date function, CTOD(). Give the CTOD func-
tion a character string with a valid date; the character string is
converted to a real FoxPro date and is fed to DOW():
? DOW(CTOD("12/25/90"))
You get back the answer 3, which means that December 25, 1990, will fall
on the third day of the week (Sunday = 1). You will get to know two
date functions well, particularly if you advance to writing FoxPro and Fox-
Base+ programs:
Now that you know the basics of functions, you can learn how to put
functions to use.
The best way to learn the difference between For and While is with an
example. Figure 4.6 shows the Browse window of a simple database with
one character field and one numeric field. The database is indexed on
Name, so it is in alphabetical order.
Assuming that no Scope clause is in effect, For tells FoxPro to look at all
the records in the database and include those that meet the expression.
For example, telling FoxPro to sum on the expression
FOR age < 30
On the other hand, While tells FoxPro to start at the current location in
the database and process records while the expression is true; in this case,
FoxPro will stop as soon as it reaches a record for which the expression is
false. Asking FoxPro to sum on the expression
gives you the sequence shown in figure 4.8 and a result of 28.
expression, you get the sequence shown in figure 4.9 and a result of 101.
eT
112 Part I: FoxPro Fundamentals
First, index the database on the expression you used in the For clause.
This action organizes the database so that all the records that pass your
Chapter 4: Sorting and Summarizing Data 1 1 4
evaluation are grouped together. Second, use Seek to find the first of the
records that will pass; use the same expression you indexed the database
on. Then use While to do your summarizing or searching. Because Seek
puts the database pointer at the first record that will evaluate to true on
the expression, While steps through the group of valid expressions and
stops when it meets the first that fails. If you use this procedure, FoxPro
will not have to search the entire database. Figure 4.10 shows how this
process works.
Expression: SEEK 31
WHILE age < 58
Fig. 4.10.
JAMISON
DAVIS ;
Using SEEK to
WILSON change the
GRIFFEY
JOHNSON eps r
starting ;
point
SEEK 31 positions database AJAX Of WHILE.
pointer here ———————> STEWART
WHILE age < 5@ processes MARK
these records JAMES
JERROLD
OZGOOD
PETERSON
ZUMWALT
WHILE age < 5@ evaluates FALSE, stops —» § HESS
GENTRY
BUSH
SMITH
1 14 Part I: FoxPro Fundamentals
You also can use memory variables for storing the results of calculations.
To store the results of a SUM operation, use this form of the command:
The memory variable TOT-ONHND now contains the value that resulted
from the SUM command. You can see this value by using the ? command:
? TOTONHND
The memory variable types are the same as the field types in a database:
character, numeric, logical, and date. You don’t have to tell FoxPro what
type of memory variable you want to create; assigning the value does that.
You can change the types simply by reassigning a new, different value:
° Command
= 1080 Fig. 4.12.
2008 Adding memory
inv_val + add_amt ; variables.
Fig. 4.13.
Command .
i HOMUAT Adding memory
add_amt variables of
add_amt : ;
? inv_val + add_amt differing types.
Memory variables can be used anywhere you would otherwise use actual
values. If you want to count all records in a database that have a cost of
more than $4, you can give FoxPro the following expression:
TEST_COST = 4.00
COUNT FOR (COST > TEST_COST)
Sorting
When FoxPro sorts a database, it copies the records into a new database
in an order that you specify. If you want the new database sorted alpha-.
betically based on customer name, FoxPro can do that; if you want the
database sorted by ZIP code and then alphabetically by customer name
within each ZIP code, FoxPro can do that also. FoxPro can sort a database
on any expression you can build.
To create a sorted database, choose Sort from the Database menu. The
Sort dialog appears (see fig. 4.14). Use this dialog to tell FoxPro the sort
order you want followed.
Chapter 4: Sorting and Summarizing Data 1 17
Database: Output
Rar Save Asa. >) 0) J) Fields
7... <Cancel >
INUNTRY Alon
Ee while:... « OK »
The first field or expression you specify is the primary sort of the new
database; all records are sorted according to that order. If you specify a
second sort, FoxPro sorts all records with the same primary sort field in
the order of the second sort. If, for example, you choose supplier as your
primary sort and PART_.NUM as your secondary sort, the new database
will have each supplier’s records grouped together in alphabetical order,
and within each supplier’s name, all the supplier’s part numbers will be
sorted alphabetically. Figure 4.15 shows the Sort dialog with the Sort
order identified.
Database: Input
{ J\ Scope... C J] Fields... <Cancel >
INUNTRY ERABE OP sins
{C ] While... « OK »
1 18 Part I: FoxPro Fundamentals
You can sort just a subset of records in a database. If you want to sort just
records for one supplier, you can choose For and build an expression to
do that. FoxPro then selects only the records that pass the FOR test and
sorts those into the new database.
If you want to sort on an expression, choose Expr and the Expression
Builder dialog appears (see fig. 4.16). You can sort on any expression,
such as a combination of fields or part of some field. Figure 4.16 shows a
sort expression of the two leftmost characters in the PART_NUM field of
each record.
When you have completed describing your sort order to FoxPro, select
OK. FoxPro extracts the necessary records and sorts them, giving you
information about its progress. When FoxPro is done, the new database is
ready for your use.
Indexing
Indexing is a different way to order a database, but to the user, the results
are often identical. When FoxPro indexes a database, a separate index file
is created that tells FoxPro the order it has to access the database records
to put them in the right order. Here is a simple example of a database:
AAA Company
XYZ Company
BED Company
ZUM Company
DED Company
ISL Company
ACS Company
SER Company
AWN
OMY
KWN RSV Company
Creating a new index is much faster than sorting; FoxPro and FoxBase +
are superior performers in indexing.
Creating an Index
Creating an index is simple. Open your database and choose Setup from
the View window. You will use the right side of the Setup dialog (see
fig. 4.17) to add (and later modify) index files. To start, select Add.
Chapter 4: Sorting and Summarizing Data 1? 1
The Open Index File dialog appears (see fig. 4.18). FoxPro doesn’t know
at this point that you want to create an index. You have only told the
program to add one to the database, and you may simply want to add an
existing index. To tell FoxPro that you will be creating a new index,
select New.
Fig. 4.18.
Open Index File:
The Open Index
Drive File dialog.
Directory
« Open »
« Cancel >
{ 1 All Files
122 Part I: FoxPro Fundamentals
Fig. 4.19.
The Index On INDEX ON:
Gtalog. PART_NUM
KEYWORD
DESCR « OK »
SUPPLIER
QTY_ONHND « Cancel >
QTY_RORDER
<Expr...>
{C J Unique
jar
The index expression can be any valid expression. For example, you can
build an INVNTRY database index that presents the information in alpha-
betical order by supplier and within each supplier by PART.NUM by
building the expression
When you choose fields from the field names list, FoxPro appends the
field name to the database name and the alias symbol (—>). The alias and
field names will be in lowercase letters. If you type the expression into
the Expression Builder, you can omit the database name and the alias sym-
bol. You also can enter uppercase letters; FoxPro expressions are not
case-sensitive.
Expressions can be complicated. Suppose that you don’t want to have the
database in supplier and then PART_NUM order. Instead, you want the
database in supplier order and within each supplier by the value of the
inventory on-hand for each part. You can use the expression
Chapter Summary
All the topics covered in this chapter bear on ways to get different views
of your database. You will build expressions to limit searches to records
that meet your criteria, you will use Scope to limit how much FoxPro and
FoxBase + search. Sorts and indexes make the database more efficient and
show you different ways to look at your database.
Now that you understand how to see different views of your data, you will
learn how to retrieve that information in the form of reports, the topic of
the next chapter.
124 Part I: FoxPro Fundamentals
Creating Reports
in FoxPro
Most important, you learn how to group data, which allows you to calcu-
late subtotals and calculated fields on specific parts of the report. When
you're finished with this chapter, you will be an expert at creating the
reports you need to show off your database.
125
126 Part I: FoxPro Fundamentals
The Layout window is like a blank sheet of paper on which you design
your report. You place objects on the blank sheet. These objects are
database fields you want included in the report, and text fields to make
the report more readable. Later, you add lines and boxes (which are
objects) to improve the readability of your report.
On the left of the Layout view you see lines labeled PgHead, Detail, and
PgFoot. These lines refer to bands, which FoxPro uses to create the
report. Each band represents a part of the report page. PgHead is an
abbreviation for Page Header, which is the top part of each page of the
report. Although FoxPro starts by putting four lines in the PgHead, you
can change this to any size necessary. PgFoot is the Page Footer, which is
the bottom of each report page. Again, you can adjust the four lines to any
size you need, including zero lines.
The Detail band is where the action is. In this band you place the fields
you want reported for each record of your database. FoxPro creates one
Chapter 5: Creating Reports in FoxPro 127
Detail band for each record you want included in the report. A Detail
band can be any size necessary, from one line to many. You also can
instruct FoxPro to “stretch” character fields vertically, so that there is
always enough room to show the entire field.
Fig. 5.2.
The Report
Report Expression: Expression
« Expr... ? dialog.
If you know what data you want in this field (a database field, for exam-
ple), you can type the name in the Expr text box. You also can select Expr
to display the Expression Builder, from which you can select the database
field or build an expression to be displayed. Figure 5.3 shows the Expres-
sion Builder with a database field selected.
128 Part I: FoxPro Fundamentals
The Expression |
Report ‘expr>: |
Builder.
If you select a field from the Field Picker scrollable list, that field (with a
prefix identifying the database) is placed in the Expr text box.
You can continue adding database fields until all the fields you want
printed in the report are on the Detail band. Figure 5.5 shows the Layout
window with the report fields in the Detail band.
UNTITLED.
FRX
R: 4C: 14 Detail
PgHead
PgHead
PgHead . .
PgHead Fig. 5.4.
Detail The Layout
: aban : window with the
Detail # first field added.
PgFoot
PgFoot
PgFoot
PgFoot
Fig. 5.5.
The Layout
Mi are
basic report.
You can click Move in the lower left corner to scroll down a page, and
you can use the horizontal scroll bar to move left and right if the report
doesn’t fit on-screen. Keyboard users can use the arrow keys to move up,
down, right, and left.
Page Preview makes report creation simple because you can try things
and see the results immediately, repeating the process until you have it
right. For those programmers who have worked in the “code-run-recode-
run-recode-run” process of report writing, Page Preview alone is worth
the price of FoxPro. (In the sample report in this chapter, Page Layout
was used to set page length to 19 lines, which enables you to see both
page headers and footers on one Page Preview screen.)
PgHead and PgFoot bands with nothing in them do not print on the
report output. If you use only one or two lines in the PgHead or PgFoot
bands, your report will look better if you remove the unused lines.
Chapter 5: Creating Reports in FoxPro J 41
Fig. 5.7.
ad The Layout
Detail
PgFoot
screen with
PgFoot excess Detail
PgFoot Bands removed.
PgFoot
QTY_-ONHND * COST
(see fig. 5.8). When you close the dialogs, you will see that the field has
been added. Using Page Preview shows the calculated field added to the
report (see fig. 5.9). You must scroll to the right using the horizontal
scroll bar or the arrow keys to see this field with page preview.
Fig. 5.8
Defining a Report <expr>:
Pee]
computed field i inuntry->qty_onhnd * inuntry->cost_
with the
Expression e
Builder. Field Names: Database: Variables:
To add a title to your report, place the cursor in the PgHead band and
select Text from the Report menu. This time, you don’t see a dialog, but
FoxPro waits for you to type the text on the Layout. Figure 5.10 shows
the screen after a title has been added.
Chapter 5: Creating Reports in FoxPro 1 434
There also is a Style check box in the Field dialog. If you place an X in
this box, you will see the Style dialog, shown in figure 5.11. On the Layout
window, if you select a text field by double-clicking or pressing Enter, you
also will see the Style dialog, in which you can change the style of the
characters in the field.
The style options available will vary depending on what your printer is
capable of doing. Basic printers have few options; laser printers have
many. If an option is available, it will be displayed in bold characters in
the Style dialog; those not available are in dimmed characters. Choose the
style option for the object selected and select OK to apply the style.
1 34 Part I: FoxPro Fundamentals
Normal
Bold
Italic «
Underline
Subscript « Cancel >
Superscript
Condensed
Double
Inventory Report
Fig. 5.12.
Part Number Keyword Description Qty Cost 2
The Layout
window with
column headings
added.
Chapter 5: Creating Reports in FoxPro 1 35
Inventory Report
« Done » <« More >» Column: @
You add a page footer by following the same process, placing the objects
in the PgFoot band. A good use for this feature is the addition of page
numbers. To add page numbers, enter
Page:
in the PgFoot band. Place the cursor one column to the right and select
Field. Choose Expr to open the Expression Builder. In the lower right cor-
ner is a scrollable list titled Variables; these are memory variables that
FoxPro keeps track of while it prints a report. To add a page number,
select the variable _pageno. Selecting that variable adds it to the expres-
sion field (see fig. 5.14).
When you close the Expression Builder and Field dialogs, your page num-
ber field will be displayed. Figure 5.15 shows the page header and footer
objects on the Layout, and figure 5.16 shows a page preview of your
report, with the page number in place. This format is often used for text
documents. Many reports have the page number in the page header area,
along with date and time stamps, and column headings.
Adding a Title
Although your report now provides the information you wanted about the
database, it would be nice to add some other things. For a long report, a
title page can provide information about the report, and summary fields at
the end of the page can total numeric fields generated during the report.
To add a title and summary, you need to add the bands in which they will
be printed.
1 36 Part I: FoxPro Fundamentals
Fig. 5.14.
Adding the Report ‘expr>:
_pageno variable ilj] |_pageno
in the Expression
Builder.
Field Names: Database: Variables:
Inventory Report
« Done» < oO
You can add a Title band and Summary band by selecting Title/Summary
from the Report menu. You see the Title/summary dialog, shown in figure
5.17. Mark the Title band or Summary band check boxes to place the
appropriate band on the Layout. Associated with each band is a New Page
check box. If you check this box for the title, it will appear on a separate
page at the beginning of the report. Similarly, checking New Page for the
summary places the Summary Band on a separate page at the end of the
report. If you also mark the New Page check box, FoxPro places either the
Title band or Summary band on a separate page.
Chapter 5: Creating Reports in FoxPro 1 47
Inventory Report
Fig. 5.16.
Part Number Keyword Description Qty Cost : Page Preview of
AC 4715349-9 BEARING BEARING (DEADLINE Zz Ss
4998799 PACKING | PACKING KIT (DEADLINE vA e report.
381999 BEARING BEARING (DEADLINE (é
185719 REGULATOR REGULATOR (DEADLINE 1
186668 KIT KIT (DEADLINE 1
187329 RESISTER RESISTER (DEADLINE 1
188228 TUBE TUBE (DEADLINE 1
113158 LOCK LOCK RING (DEADLINE Zz
Inventory Report
« Done » < More > Column: 7)
Once the Title and Summary bands are on the Layout, you can add or
move objects as necessary to provide more information and improve the
appearance of your report.
First, you need to tell FoxPro when to reset the totaled field to zero. In
this case, you can have it reset only once, at the beginning of the report,
or at the end of each page; these options are selected from a pop-up menu
in the Reset box. In cases where you are totaling the whole report, you
leave the default value, which tells FoxPro to reset only when the report
starts. In this dialog you also tell FoxPro how you want the field calcu-
lated. Select the type of calculation you want by clicking the appropriate
radio button. When you select OK, you move to the Expression Builder to
define what data to sum in the field.
Suppose that you want this field to total the number of items on hand in
the inventory—the sum of the QTY_ONHND fields. Choose Sum in the
Totaling dialog. In the Report Expression dialog, enter QTY_ONHND in
1 48 Part I: FoxPro Fundamentals
the Expr text box. You also can choose Expr to display the Expression
Builder dialog. In the Expression Builder dialog, you can enter gty_onhnd,
or use the Field Picker scrollable list to select the QTY_ONHND field.
Because you specified this field to be a summed field, FoxPro knows to
sum the QTY_ONHND fields in the report. Figure 5.19 shows the Expres-
sion Builder with the field to sum defined.
Chapter 5: Creating Reports in FoxPro J 49
Builder to define
what data will
Field Names: Database: Variables: Q
be summarized.
PART_NUM INUNTRY » ALIGNMENT
KEYWORD
DESCR
SUPPLIER « Verify
> QTY_ONHND
QTY_RORDER «
PRICE
COST a|
aL
Vil
ge
lh
oe
An
Far
Se
rr < Cancel sen
Page
oo}
oll
il
am
lar
oe
4
When you have closed the Expression Builder and Field dialogs by choos-
ing OK, you return to the Layout, and the field is in place. Place a text
object to label the summary field, and you’re ready to move on.
Add a second field to the Summary band and choose Totaling again. This
time, put into the Expression Builder the following computed expression:
QTY_ONHND * COST
This value will be calculated as FoxPro processes the report. Again, add a
text object, and your Summary band is done. Using Page Preview you can
see the Summary band at the end of the report. Figure 5.20 shows the end
of the INVNTRY database.
Fig. 5.20.
The end of the
Totals:
report, showing
the summed
fields.
Figure 5.22 shows the same dialog for the summed field of the
QTY_ONHND * COST summed field. The Format field 999,999.99 tells
FoxPro to put use two decimal places and a comma when formatting the
number.
Chapter 5: Creating Reports in FoxPro 141
You can alternate between Page Preview and formatting from the Layout
until the format and placement of the summed fields is right. Figure 5.23
shows the completed report in the Layout window, and figure 5.24 shows
the end of the report in a page preview.
Fig. 5.24.
The end of the
report, showing
the formatted Totals:
fields.
Now your report is completely designed. You have looked at the page
preview to make sure that it’s a masterpiece, and you’re ready to run it.
First, however, save the report using the File Save menu.
Fig. 5.25.
{XJ Environment J Scope... The Database
Iphone. f
] Uhile... Report dialog.
Plain
No Eject
Summary
Heading
To Print « OK »
To File
Console On (¢ ) Console Off <« Cancel >
If you choose the Scope option, you see a dialog asking you to define the
scope. Your options are as follows:
34423 instead.
Keyword Totals
Page:
To start, choose Open from the file menu and select the report already
created in this chapter. This way, you can modify an existing report lay-
out. Later you can save it with a new name, which preserves your original
report, or you can save it with the same name, which replaces the original
report with the newly modified one.
is. Grouping the data by keyword provides a break for the eye when scan-
ning the report, adding to the user’s understanding of the data.
To group data and’‘add subtotal fields, choose Data Grouping from the
Report menu. In the Group dialog, shown in figure 5.27, you see a scroll-
able list, which is empty because you have not defined any groups yet.
Fig. 5.27.
= The Group
PgHead & Oty Cost :
Detail
PgFoot
am etsu_o dialog.
PgFoot
PgFoot
PgFoot
Summary
Select Add to add the group you want. FoxPro displays the Group Info
dialog, in which you tell FoxPro how to group the report data (see
fig. 5.28).
« Group... >»
« OK »
Options:
Summary *** « Cancel >
{C J Swap Page Header
{C ] Swap Page Footer
{C J New Page
146 Part I: FoxPro Fundamentals
The expression you define in the Group Info dialog is the one on which
FoxPro will “break” the database into groups. Starting at the beginning of
the database (either actually or by an index order), FoxPro processes
records, looking at the value of the expression you have identified. When
that value changes from one record to another, FoxPro says, “Aha! Time
to change groups, which means printing out what’s in the Summary band
and starting a new group with a group header.” Figure 5.29 shows FoxPro
grouping where a change in the value of the keyword occurs.
You see, then, that for grouping to work, the database must be sorted or
indexed in an order that allows the grouping to be consistent. Consider,
for example, what would happen if you defined a group on the KEY-
WORD field, but had the database ordered on a PART_NUM index or sort.
Each time the value in the KEYWORD field changed, a new group would
be generated; if the database is indexed or sorted on PART_NUM, that
could happen every record or so, resulting in a bad report. When planning
a grouped report, make sure your database is indexed or sorted properly
and, if indexed, that the proper index is controlling the order of the
database.
KEYWORD + PART_NUM
This index will present records by keyword and, within each keyword
group, by part number.
Chapter 5: Creating Reports in FoxPro 147
If you don’t know the expression on which FoxPro will break the report
into groups, select the Group field in the Group dialog; FoxPro displays
the Expression Builder to assist you. The grouping expression can be any
valid FoxPro expression, including one or more database fields, calculated
values on the fields, logical values, or anything else you can construct.
Close the Expression dialog and you will see the Group dialog with your
expression in it (see fig. 5.30).
Fig. 5.30.
The Group
Qty Cost dialog.
ot) a
Add
Change
Summary *** End
Delete
Close the Group dialog to return to the Layout, which now displays
Group Header and Group Footer bands above and below the Detail Band.
This Group Band is identified by the title 1-keywo in the band title col-
umn, indicating that this is the first group and that it will break on the
expression KEYWORD. If you use Page Preview now, you will see no dif-
ference in the report because FoxPro ignores bands that have nothing in
them.
To identify the group, you can put fields in the group header giving infor-
mation about the group just starting. You have added a text object label-
ing the group and a field object with the value from the keyword field.
The Group Header line tells the report reader what is in the next group.
You also can add lines to a group for clarity. After you add the Group
header in the Layout window, shown in figure 5.31, run a page preview to
see how much better the report is with this grouping (see fig. 5.32).
148 Part I: FoxPro Fundamentals
3 WAY VALVE
When you select Totaling in the Report Expression dialog for the group
field, you will see the Totaling dialog. In the Reset scrollable list, choose
the data grouping expression as the reset point. This tells FoxPro to reset
the Totaling field that you have defined to zero at the start of each new
group. Figure 5.33 shows the INVNTRY—>KEYWORD selected as the
Reset point.
Figure 5.34 shows the Layout window with summary fields in the Group
Footer band; the resulting report is shown in page preview (see fig. 5.35).
Fig. 5.35.
Page preview of
the report with a
group summary
field Z WAY VALVE
: Keueord Totals
eyword: Z-FLUID
yi
ICO 862-468-238 2-FLUID Z-FLUID POQNER SRAKE VALUE
Keyword Totals
eyword: Z4U
aT-Z4U zu ZU HORN
C-123X zu zw COIL
CT-128C Zu ZV CONTACTOR
Keyword Totals
Done » < More > Column: 8
Adding Graphics
Now your report provides the information you want. One more thing can
improve its readability, though—some lines and a box. Lines and boxes
are nothing more than objects. You add them by choosing Box trom the
Report menu, then sizing them and moving them to where you want. A
line is a box, sized to have no height. To the example report, you will add
a line above and below the data records for each group, and put a box
around the title.
Once again, mouse users have the advantage. Choose Box from the Report
menu, place the mouse pointer where you want one corner of the box to
be and drag the mouse (holding down the button as you move the
mouse) to the opposite corner. The box is created as you move the
mouse.
From the keyboard, choose Box from the Report menu. Use the arrow
keys to place the cursor where you want the line or box to start. Press the
space bar to begin creating the line or box. Use the arrow keys to move to
where you want the line or box to end. As you move, the line or box
appears. When you are finished, press Enter
In the example, a box has been sized to no height to make a line, and
placed in a new Group Header line. A second line has been added to the
Page Footer, to put a line at the bottom of each page before the page
number. Figure 5.36 shows the Layout with lines and boxes added
Chapter 5: Creating Reports in FoxPro 1 51
Page Preview shows how this lends emphasis to the data groupings you
have created. Follow the same process to add a box around the page
header, separating it from the report data. Page Preview shows how effec-
tive this box and these lines are in improving the readability of the report
(see fig. 5.37). (Page length has been set to 19 lines in the Page Layout
dialog to allow this figure to show the PgHead and PgFoot bands on one
screen.)
Sorted 24
Ne
mire—connents | See SISAL
oa ane i NAa
Chapter 5: Creating Reports in FoxPro 1 53
Keyword Totals
Chapter Summary
In this chapter, you have learned how to create understandable reports.
You have added database fields, text objects, lines, and boxes. To make
the data more meaningful and readable, you have learned how to group
that data into logical units and how to summarize that data, both at the
group level and for the report as a whole. In short, you know enough
about FoxPro reporting to extract from your database information in any
number of ways.
As you have seen, report writing in FoxPro is quick and easy. FoxPro has
turned report writing from pure drudgery into an enjoyable, rewarding
process
1 54 Part I: FoxPro Fundamentals
Part II
Includes
Creating Multiple-File,
Relational Databases
As you use FoxPro, you will find situations that call for more than one
database to store all the information you need. When you need to store
and report on information about different types of data, you need a
database for each type. FoxPro enables you to create database systems
containing two or more databases. You can tie these multiple files
together, accessing data from one database while working in the other.
Creating multiple-file, related databases is not difficult, and it is in this
type of database that FoxPro’s power really shows.
This quick start builds on Quick Start 1 by creating another database, one
to track contacts a sales force may have with the company’s customers.
This database will be called the CONTACT database and will be related to
the CUSTOMER database, enabling reports and query screens to access
information from both databases at the same time. Like the CUSTOMER
157
1 58 Part II: Intermediate FoxPro
CD \FOXPRO\CUST
Set the path to the FOXPRO directory
PATH = \FOXPRO
and start FoxPro with the command
FOXPRO
First, you need to define the different databases your system needs. If you
have already created one of the databases, define what the second (or
third) will contain. If you need to tie the two databases together, include
in both a common field, which FoxPro will use to match records in the
two database files.
The CONTACT database is shown in figure QS2.2. Notice that the CON-
TACT database and the CUSTOMER database both have a field named
CUST_NAME. This is called the relational field; when FoxPro is processing
records in the CONTACT database, you will be able to access information
in CUSTOMER database records as a result of this tie between the two
databases (see fig. QS2.2).
Quick Start 2: Tapping the Power of FoxPro 1 59
Fig. QS2.3.
Structure: C:\FOXPRO\CUST\CONTACT.
DBF The SUTACUT, e
Name Type Width Dec dialog, with the
«Cancel >
2. Open the View window. In the first line of the work area box,
you see CONTACT, indicating that the CONTACT database is in work
area A. If you wanted to add more index files, you would do so
here by choosing the Add selection.
Now you have set up the second database for your system. You can work
with this database just as you did with the CUSTOMER database in Quick
Start 1, entering data into it and creating custom data-entry and query
screens with FoxView and reports from the Layout window. However, the
power of FoxPro comes from its capability to tie together two different
databases, drawing information from both at the same time. As you will
see later in this quick start, you can run a report on the CONTACT
database and print information from the CUSTOMER database at the same
time. FoxPro uses the common CUST_NAME field to tie the two databases
together. For now, though, you can use the CUSTOMER database to
ensure that you’re entering correct information in the CUST_NAME field.
To do this, follow these steps:
1. If it’s not open already, open the View window by choosing View
from the Window menu. The View window should appear as in
figure QS2.4.
Fig. QS2.4.
The View dialog,
showing the « View > Work Areas « Relations >
<Setup >
<Browse>
Fig. QS2.5.
The View
« View > Work Areas « Relations > window, with the
§ <Setup >
«Browse >
Fig. QS2.6.
The FoxPro
screen with a
Browse window
on the
CUSTOMER
database and a
CONTACT data-
entry window.
Fig. QS2.7.
Both the
CUSTOMER
Browse window
and the
CONTACT data- Ly CUSTOMER
entry window
visible at once. West Hill Florist 3Z981 Znd Ave So
Northwest Microsystems, In]18968 127th Pl
+ 4® >
6. You also can cut and paste the CUST_NAME fields. Move to the
CUSTOMER Browse window. Scroll to the record of a customer
which you want to enter into the CONTACT database, and then
select the text in the CUST_NAME field with either of the
following methods:
(J Using a mouse, put the mouse pointer at the first letter of the
name in the CUST_NAME field. Drag the mouse to the right
while holding down the mouse button. On a color monitor, the
characters selected will change color; on a monochrome
monitor, the selected characters change from black on white to
regular video and are underlined. When you have highlighted
the entire name, release the mouse button and select Copy
from the Edit menu or press Ctrl-C.
164 Part II: Intermediate FoxPro
1 From the keyboard, use the arrow keys to place the cursor at
the first character of the CUST_NAME field. Hold down the Shift
key while pressing the right-arrow key. Each press of the right-
arrow key highlights another character; continue doing this
until the entire name in the CUST_NAME field is highlighted.
Now choose Copy from the Edit menu or press Ctrl-C.
CONTACT
Cont_date 03/24/98
Salespers JWZ
Fig. QS2.9. Follow_dte 84/18/98
Pasting a Cont_rpt memo
Sale_made
CUST_ NAME
from CUSTOMER cst
|
had
l e
into CONTACT.
CUSTOMER
Paste the copied Cust_name
field here SSS
Cosars Continent 9923 Wilson Rd
Copy this field Northend Music SouthCenter Mall
from here
Fig. QS2.10.
A text-entry
window for
entering
information into
OMER the memo field,
[pct | | CONT. apr.
4923 Wilson Rd
Me) SouthCenter Mall
Notice that the information you have entered into the memo field
CONT_RPT cannot be seen. To see that information, tab to the
CONT_RPT field and press Ctrl-PgDn, just as you did to enter the informa-
tion. Press Ctrl-W or click the close symbol to exit the memo field. When
you have entered 10 to 15 records into CONTACT, press Esc or click the
data-entry window-close symbol.
1. Close any open windows you have on-screen. Open the View
window by choosing View from the Window menu. It should
appear as in figure QS2.12. If it doesn’t, select work area A, then
use the Open option to open the CONTACT database in this area.
Fig. QS2.12.
The View
« View > Work Areas « Relations >
window, with
CONTACT opened ‘On/Off > SOW | CONTACT
+CUSTOMER § j>t-+
in work area A.
«Files >
# Misc >
«Setup >
«Browse?
« Open >
“Setup >
«Browse?
Fig. QS2.14.
The relation « View > Work Areas « Relations >
between on/off CONTACT CONTACT
CONTACT and
«On. > : Ls
“CUSTOMER {| L-+CUSTOMER
CUSTOMER phe
established. « Misc >
«Setup >
«Browse?
These actions have tied together the databases CONTACT and CUS-
TOMER, a process known as “setting the relation.” Each database has a
“database pointer,” an imaginary arrow that points at the active record in
the database. With this relation set, when you move the pointer in the
CONTACT database, FoxPro automatically moves the CUSTOMER
database pointer so that it points to the CUSTOMER record with the same
CUST_NAME.
Next, you will want to make use of this relation:
2. To clean up the screen, select the View window and close it. (If
the Command window is open, select it and choose Hide from the
Window menu.) Move and size the two Browse windows until
you can see the CUST_NAME fields for both of them at the same
time; for this exercise, it is best if each is only two records high.
Figure QS2.15 shows the FoxPro screen with the two Browse
windows open.
Quick Start 2: Tapping the Power of FoxPro 169
Fig. QS2.15.
Browse windows
iiss Plumbing
Blane thank 82/81/98
ale ale on both
Comar 11/38/89 |CHZ 12/29/89 |Memo ,
bow CONTACT and
CUSTOMER
STI databases
fede | opened
Sgbeaee
Cosars Cont inGn Tale eae|
apap
4423 eon tnd
Rd enn
Hess Aviation ee 334Z Aviation R
addr
“CUSTOMER
- CUSTOMER
=
Moore & Associates ae
=
+4
Once you know your databases are set up correctly and the relationship
works, you can save this View with a name for later use. To do so, open
the View window and choose Save from the File menu. You will see the
Save View As dialog, shown in figure QS2.18.
Quick Start 2: Tapping the Power of FoxPro 171
Directory CUST
« Save »
UIEW_1_
Save the view as VIEW_1. FoxPro saves information about what databases
are open in which work areas, what index files are attached to the
databases, and what relations exist between them.
In the future, if you want to reestablish this View, you need only choose
Open from the File menu, select View from the Open dialog, and specify
VIEW-_1 as the view you want to establish. FoxPro will return itself to the
exact state it was in when you saved the view, including the sizes of
Browse windows.
You have seen how FoxPro relates two database files, keeping them in
sync as you move through the controlling database. Doing this enables
you to draw information from one database (CUSTOMER), based on the
record in another (CONTACT). To see how this can be extremely valu-
able in your database work, you next create a report that uses this
relationship.
1. Open the View window to ensure that the databases are open and
the relationship set. When your View window is correct, you can
create a report on the two databases. Make sure that the
CONTACT database has the “active database” symbol to its left. If
it does not, double-click CONTACT to select it, or highlight
CONTACT and press Enter to make it the active database.
2. Choose New from the File menu and select Report from the New
dialog. Select OK to open the Layout window. You will create your
report on this Layout window.
3. Choose Quick Report from the Report menu. Click Column Layout,
and then OK. You will return to the Layout view, which now looks
like figure QS2.19.
Fig. QS2.19.
The Layout
window,
sal follow_d cont_rpt
PgFoot
4, Edit the text labels to make them more meaningful. You also
should delete the CUST_NAME field, because you don’t want the
customer name to print on each line of the report. Add a line to
the bottom of the Detail Band by placing the cursor in the last
line of the Detail Band and choosing Add Line from the Report
menu.
5. Next, choose Group Data from the Report menu. In the Group
dialog, click Expr to display the Expression Builder dialog. In the
Expression Builder dialog, change the database to CUSTOMER by
pulling down in the Database box and selecting CUSTOMER from the
menu (see fig. QS2.20).
Quick Start 2: Tapping the Power of FoxPro 1 73
Break <expr?:
Peed |ee Fig. Q92.20.
Changing the
database to
CUSTOMER.
6. Select CUST_NAME from the scrollable list to tell FoxPro that you
want your report to group data by the value of CUST_NAME in
the CUSTOMER database. When printing the report, FoxPro will
move through the CONTACT database, updating the database
pointer in CUSTOMER as a result of the relation you have set
between the two files. When the value of CUST_NAME in
CUSTOMER changes, FoxPro will end one group and start another.
7. When you return to the Layout window, you can see that FoxPro
has created a Group Header Band and Group Footer Band. Place
the cursor into the Group Header Band and choose Field from the
Report menu. In the Field dialog, again change the database to
CUSTOMER, and pick CUST_NAME from the list. When you return
to the Layout view now, you will see a field labeled customer->
cust_name in the Group Header Band.
8. Choose Add Line from the Report menu three times to add three
additional lines to the Group Header. In the second line, add a
Field for ADDR_1 from the CUSTOMER database. In the third line,
add a field for ADDR_2 from the same database, and, in the fourth
line, add fields for CITY, STATE, and ZIP from the CUSTOMER
database. Your Layout view should look like the one in figure
QSs2.21.
174 Part II: Intermediate FoxPro
Fig. QS2.21.
The Layout view.
zip
Fig. QS2.22.
The output of Kirkland 98332
OU AIGENE “CHZ 82/15/98 Purchased restoration materials.
You can see that your report works, proving that your databases and the
relationships between them are correct. Still, your report is somewhat
stark, and with FoxReport’s capabilities, there is no reason for a plain-
vanilla report. The following steps present some ways to improve the
report’s appearance:
Quick Start 2: Tapping the Power of FoxPro 175
2. Open the Field dialog from the Report menu. You see the Report
Expression dialog (see fig. QS2.23). The Stretch Vertically
option applies specifically to memo fields and ensures that the
field will always be big enough to print the entire memo field.
The field will always be the width you specified on the Layout
view, but will take up as many lines as necessary. If you want the
field to be only one line, make sure that this option is not chosen;
the report field will be just as you defined it.
Fig. QS2.23.
The Report
Report Expression: Expression
contact->cont_rpt dialog.
« Cancel >
6. Return to the Layout view and choose Page Preview. Your report
should look like figure QS2.24, with the CONTACT—>SALESPERS
field floating below the comment field.
Kirkland
Sales- Follow-up
person Date Report
7. Add a line in the Group Footer to mark the end of the report by
choosing Box from the Report menu. If you’re using a
monochrome monitor, you will then choose what type of box you
want from the Box dialog.
Summary
In this quick start, you learned how to create and use multiple database
FoxPro systems. You saw how the databases must have a common field so
that FoxPro can relate them. Setting up Browse windows on the related
databases and moving back and forth between them showed how FoxPro
uses the relations you established, making sure that the records of the two
databases are in sync and always pointing to the correct record, based on
the common, relational field.
Quick Start 2: Tapping the Power of FoxPro ie/iz
Finally, you used the Layout view to create a report that draws informa-
tion from two different databases at the same time. You can see that this
technique is extremely valuable, enabling you to keep different types of
data in different databases while viewing and reporting on information
from those different types of data. Once you have mastered creating and
using two database files at the same time, you will be able to do the same
with three, four, or more files.
178 Part II: Intermediate FoxPro
Designing, Defining,
and Creating
Relational Databases
= Ithough you will find that some applications require only one
= database, most FoxPro applications require two, three, or more
databases to represent the different types of data in the application. This is
an area in which FoxPro really shines: in its capability to create sophisti-
cated database applications with multiple databases and to tie those
databases together in productive ways.
You will want to use more than one database file when the data you need
to store falls into more than one logical group. The example in this chap-
ter uses data about customers, the orders those customers place, and the
parts ordered. Information about customers is different than information
about orders and inventory, so each type of data—customer, order, and
inventory —go into separate databases.
The first part of this chapter discusses the theoretical side of relational
databases. The rest of the chapter focuses on defining a multiple-file
database system, including the files and the relationships you must tell
FoxPro about, and testing the database to make sure that the file struc-
tures and relations work as you want them to.
179
180 Part II: Intermediate FoxPro
A relationship exists between these data entities, and you want to have
your database represent those relationships. In the wholesaler example, a
relationship exists between the customer and the orders of the company
—each order is placed by a customer. Similarly, there is a relationship
between the order database and the inventory database—each order is for
some part in the inventory.
Fig. 6.1.
Database
relationships. which refers to
a part in the
. inventory
Chapter 6: Designing, Defining, and Creating Relational Databases 18]
Just as with a single-file system, when you design a relational database sys-
tem in FoxPro or FoxBase+, you must begin with a clear idea of what
you need as output from the system. In nearly all cases, you will be auto-
mating a manual system, or improving an existing computerized system,
so you have a head start on what the system must do.
Customer Report
Date:01/02/90
Times 6 si4ival
6 ODE ARATE AIOE CONE ELC TRS, BERETS CORI ILENE DPE RC IAT SI ei eae de ee
TBM MMAR ELD CER LA OTL EMAL OE OIE FE OT MAE ELE I OSI AEE LOT At
Number: 10
Name: OshKosh Cow Company
Address: 5534 E. Dairy Rd
Pasture 8
City: Oshkosh State: WI ZIP: 88332
Phone: (203) 882-1112
CP UG AD CTC RTE ONE EO EE TAI AT ELI O OMAP LOTS EAE OE Ee WL ei has Meade Saree,
RY ot MM 10gLi BR SG DY MT LS AS fac)2 BAY ak PAL ey Lootso A Fo hd Pa Lt Med Pet AT Bie Deeeee OY i Pt Pat el ed EMD Aa I EE LT Pee CRD ST PelSE day2
Inventory Report
Ulett PY aEaT Tat st oat MME a Ce A Eel LN BY AN Sl fol ERED at ad LAY sl Jp Sd el Sd Pd AS Pl eeAT A Dee a et LAT at BCE RE OME TATOS DM dd al LGM eC NALS
Qty Ext.
Fig. 6.3. Part Number Keyword Description On Hand Cost Cost
An Inventory Vet oye Pela ol Mala CO tee SN Ct es A Pea Me hoy | Meee
Obviously, a full system will have many different reports and inquiry
screens, but if the system can supply the basic reports, it also can support
just about any inquiries. The goal in designing this system is to make sure
that you can access all the data you need for these reports.
Looking at the outputs you need from your system, you can identify the
information you must have in the databases. In this example, you see that
the information for the Customer and Inventory reports can be taken from
the CUSTOMER and INVNTRY databases you created in Part I.
One new database is necessary: ORDER. This database must contain infor-
mation about the customer placing the order, the date of the order, the
salesperson who took it, and what was ordered. For simplicity, assume
that an order contains only one item from inventory and that the price is
not included.
Chapter 6: Designing, Defining, and Creating Relational Databases 183
Sales Report
Date: 01/02/90
Times! —Sisi4 13
CO, Ce at CORE ease, Coen 8) 0) eee Ok Ge Oak Oe. eee COE: PELE D CLIO OFC ID: FOE Bi TAOS OA Et ;
Sales Report
Date: 01/02/90
Time: 8:41:14
PU LID PEPRBODE PRETEND IES ELIE PILE TALI PRIN LEAD Pad APT ARE Dt LLP Pa A
Sold To: al
West Hill Florist
32901 2nd Ave So
Renton WA
LAUDE LTA. CAD OR PTAA LT fel IAD PI RE Ce BIR ADTANE A TET OST LM dlAYANTTS
Order Date: 01/02/90 Salesperson: DJZ
CO PTET LE IDLE IE DDH PBN Atdls POD LIND TIED Ae OME PD A EAP LM AdMLL AML ED IBED A TDed (LY aTPald
Part Number Qty Keyword Description Price
PDT OED RENEE, EDM TN PLETE DE PUT ALM DET et a OE Ln gadEMA PoRSESILTOLT
RAS,
CASCADE 6045 3 PLUG PLUG 0.00
Inventory Report
Part Ordered By Sort
De EEN SR rae PAD OSC EID LH CRM OR dS Coa bee 1 DAC anaes
You could design the ORDER database to contain the customer informa-
tion (name, address, city, and state) and information about what was
ordered (part number, description, and price), but doing that would not
be efficient. The customer information is already in the CUSTOMER
database, and the inventory information is already in the INVNTRY
database. If you duplicate all the customer and inventory information in
each ORDER record, you must enter it each time you take an order, and
you would have to make sure it was right each time. FoxPro, with its rela-
tional capabilities, can tie the ORDER database to the CUSTOMER and
INVNTRY databases so that you can access the data stored in them.
You know that a customer places an order; this is a good definition of the
relationship between the CUSTOMER and ORDER databases. Database
designers have long used graphical techniques (that is, scribblings on
paper) to define database systems, so you should do that here, creating
what is known in the database design world as an Entity-Relationship dia-
gram. The E-R diagram is a graphical representation of how your FoxPro
database must be set up.
An entity is a logical group of data that you need to store in your system;
in FoxPro, then, an entity becomes a database file. In the example system,
CUSTOMER is an entity, as are ORDER and INVNTRY. In the Entity-
Relationship diagram, an entity is represented by a box, with the name of
the entity inside it.
A relationship is what ties two (or more) databases together. In the exam-
ple, you can define a relationship called IS PLACED BY that ties the CUS-
TOMER and ORDER databases together; an order IS PLACED BY a
customer. If you put this relationship in your FoxPro database, FoxPro
will be able to process records in the ORDER database and use the rela-
tionship to access information about the customer who placed the order
Chapter 6: Designing, Defining, and Creating Relational Databases 185
Fig. 6.6.
ORDER < IS PLACED BY »——> CUSTOMER An Entity-
Relationship
diagram for
ORDER IS
PLACED BY.
Although you have given the relationship a name (IS PLACED BY) in the
diagram, you don’t use that name to define the relationship to FoxPro; it’s
used in the E-R diagram for clarity only. To define the relationship to Fox-
Pro, you must use indexes.
1. Reads the value of the field CUST. NAME in the active record of
the ORDER database.
Now, if you ask for information from the CUSTOMER database, such as the
value of the field ADDR_1, the information retrieved will be that for
the customer who placed the order. FoxPro has used the common fields
CUST_NAME to relate the ORDER and CUSTOMER databases.
In the Entity-Relationship diagram, you can show how the two databases
will be tied together. Under the diamond for the PLACES relationship, put
the relational expression for the controlling database toward that
database, and for the controlled database toward that database, as seen in
figure 6.7.
You also can draw an arrow pointing from the controlling to the con-
trolled entities to remind you which is which.
ee ee
Fig. 6.8.
ORDER < IS PLACED BY > »——> CUSTOMER The completed
Entity-
CUST_NUM CUST_NUM Relationship
diagram.
PART_NUM PART_NUM
When you have designed your databases and relationships on paper, you
must define the system to FoxPro.
188 Part II: Intermediate FoxPro
Table 6.1
Database File Structures
1 CUST_NUM Character 6
2 ORDR_DATE Date 8
3 SALESPERS Character 3
4 PART_NUM Character 15
5 QTY Numeric 5
** Total ** 38
1 CUST_NUM Character 6
2 CUST_NAME Character 25
3 ADDR_1 Character 25
4 ADDR_2 Character 25
5 CHANG Character Is
6 STATE Character 2
7 ZIP Character 9
8 PHONE Character 10
9 CONTACT Character 10
10 CREDIT Numeric 8 2
11 LAST_PUR Date 8
12 LAST_AMT Numeric 8 2
We, PREFERD Logical 1
** Total ** 153
Chapter 6: Designing, Defining, and Creating Relational Databases 189
Table 6.1—Continued
1 PART_NUM Character iS
2 KEYWORD Character 10
3 DESCR Character 25
4 SUPPLIER Character 25
5 QTY-ONHND Numeric 5
6 QTY_RORDER Numeric 5
V PRICE Numeric 8 2
8 COsi Numeric 8 2
se) AUTO_RORDR Logical 1
10 COMMENTS Memo 10
Ota lucas ii
You must define to FoxPro the databases and the relationships between
them. Start by opening all necessary database files, one per work area,
using the View window. If any file is open, select and close it to give you
a clean start. The View window, with no databases opened, is shown in
figure 6.9. You can see work areas A through J.
If you scroll down through the work area, you see that beyond work area
J, the areas are numbered rather than lettered. In fact, all work areas are
numbered; you can refer to areas A throughJ as 1 through 10.
190 Part II: Intermediate FoxPro
<Browse>
«Close >
Start by selecting work area A and choosing the Open option. Put your
first database file in this work area, then choose Setup to add the index
files you need. If you wanted to add a format file and field or filters state-
ments for this file, you would do so in the Setup dialog.
When you return to the View window, it should look like figure 6.10,
which has the ORDER database set up as work area A.
«Browse?
« Open >
«Browse?
If you design and create a system with many database files, you will find
that for specific jobs you only need some open at a time, with relation-
ships established between them. You should go through the Open and
Setup process for each job-specific setup you need, and then save that
“snapshot” of FoxPro for later recall. In this way, you can make FoxPro
more efficient and reduce the system’s complexity. Saving the view is
explained later in this chapter.
a
«Setup >
<Browse>
<Close > |
HINUNTRY
INUNTRY Records: 3Z87
3287,
FoxPro asks you to define the controlled database; select the database at
the other end of your relationship, in this example, CUSTOMER. You are
presented with the Expression Builder, in which you tell FoxPro what
expression, derived from the fields of the controlling database, will be
used to find the correct record in the controlled database. In this exam-
ple, FoxPro wants to know what field in the ORDER database will be used
to find the right record in CUSTOMER. Your design dictates that the field
will be CUST_NUM, so select that field from the scrollable list, and then
choose 0K. Now when you return to the View window, it looks like figure
6.14, showing the relationship.
Chapter 6: Designing, Defining, and Creating Relational Databases 193
«Browse?
« Open >
CUSTOMER
relationship
established.
«Browse?
« Open >
If you’re wondering why you didn’t have to specify the CUST_NUM field
in CUSTOMER, remember that the controlled database must be indexed
on the relational expression. FoxPro looks at a record in ORDER, then
uses the value of CUST_NUM, which you have specified as the relational
expression, and looks for that value in the index controlling CUSTOMER.
FoxPro doesn’t care what the field name in the controlled database is, as
long as it can find the relational expression in the index.
194 Part II: Intermediate FoxPro
Now you have to do the same thing to establish all the other relationships
you defined in your design. Next, the relationship between ORDER and
INVNTRY needs to be set. Here the relational expression is PART. NUM in
the ORDER database, and again, you must make sure that the index con-
trolling the INVNTRY database is on the field PART. NUM. When you have
completed that relationship, you see in the View window a representation
of both relationships (see fig. 6.15). Now you’re almost ready to see
whether your design works.
«Browse?
First, to set the database files and indexes in their correct work areas, you
select the work area, then tell FoxBase + what database to use. To set the
three example databases into their work areas, enter the following
sequence of commands (all text after the && is commentary and is
ignored by FoxBase+ and FoxPro):
Chapter 6: Designing, Defining, and Creating Relational Databases 195
SELECT C
USE INVNTRY
SET INDEX TO PART_NUM
Now the databases are in their correct areas, with the right index files
controlling them. The following sequence sets the relationships:
For greater clarity, the sequence just specified used the database names as
aliases. The following sequence also works:
SET RELATION TO CUST_NUM INTO A
SET RELATION TO PART_NUM INTO C
You can see why it is usually preferable to use the database name as an
Alias (or whatever Alias you may have assigned the database). Particularly
when you need to do some FoxPro programming, the database Name Alias
option makes clear which database is in work area A or C.
When this sequence is completed, FoxBase+ (or FoxPro) will look the
same as FoxPro set up with the View window. Using the Command win-
dow in FoxPro is covered in Chapter 8, but you can see that you often
can accomplish FoxPro processes faster through the Command window
than by using the windows and dialogs. Using the Command window
requires a better knowledge of FoxPro, though.
196 Part Il: Intermediate FoxPro
To save a View, open the View window and make sure that everything is
as you want it to be: databases in the correct work area with appropriate
index files attached, any filter condition defined, the fields set on or off as
necessary, and the right format file included, if you want. Then, select
Save from the File menu and give the view a name. Figure 6.16 shows the
current view being saved as ORDR-1.
Fig. 6.16.
Save View as:
The Save View
dialog.
Directory CUST
« Save »
ORDR_1_
When you want to reestablish that view, select Open from the File menu,
change the Type to View, and select the view you want from the File List.
When you return to FoxPro, its condition will reflect the saved View.
As before, FoxPro users can also use these commands in the Command
window to accomplish the same purpose.
First, of course, your databases need some data. CUSTOMER and INVN-
TRY already have data records in them, but ORDER is empty. Make sure
that ORDER is the active database (by selecting it in the View window).
Then, using the Append option from the Record menu, add a number of
records to the ORDER database. Take care that the CUST_.NUM you enter
exists in the CUSTOMER database and the PART_NUM you use is a valid
number in the INVNTRY database. Remember, you're just testing now; for
a real system, you would have FoxPro check these values as you enter
them to ensure that they’re valid.
Once you have entered enough test records in ORDER (at least 20), you
can test the relationships by creating a rudimentary report. You need only
include enough fields from each database to enable you to see that you
have set up the relationships correctly. If, later on, you find you’re missing
data fields, you can add them, but restructuring the database and relations
is more difficult. The following fields will fulfill this testing requirement:
You can see that, if the relationships are working correctly, each record in
the ORDER database will access and print out the right information in the
related databases.
a ee ee ee ee ee
Figure 6.17 shows the Layout View of the testing report. You can see that
this is a very basic report; you need only a Detail Band to check what
fields are accessed as the report progresses through the ORDER database.
Fig. 6.17.
The test report
Layout View. eust_n
After saving the report, you can run it by choosing Report from the
Database menu. Figure 6.18 shows the results of running this report. You
can see that, as FoxPro progressed through the ORDER database, it suc-
cessfully pulled in the appropriate data from the CUSTOMER and INVN-
TRY databases; the relationships worked as planned. You can save this
view, knowing that when you want to create the report with all the fancy
formatting, you can open this view and it will be correct.
When reviewing test reports, you should make sure not only that FoxPro
worked correctly when there was a match between the controlled and
controlling database, but that it also handled a no-match situation. In this
case, the data from the controlling database (ORDER) should be present,
but the controlled database’s fields should be blank. When FoxPro cannot
make a relational match, it points to a null record in the controlled
database. If you find data in a record where you know no match exists,
something is wrong with the relation.
This brings up a point of testing: always include test data that should fail.
It is too easy to include data you know will work and assume that all is
fine when it does work. Systems don’t die on common occurrences, but
on the once-a-year weird data. So try everything, including data you are
sure will never be entered in the system once it’s completed.
Chapter 6: Designing, Defining, and Creating Relational Databases 199
5 Comar
E-2398 ROLLER Fig. 6.18.
Cosars Continent The printed
1400-5509 1400-5509 SEAL output from the
Cosars Continent test report.
1425-3378 1425-3378 BEARING
Cosars Continent
CHAIN
2 Northwest Microsystems
BA 992518 BA 992518 RING
3 3 ScIL
CASCADE 662458 CASCADE 662458 SEAL
3 3) SCIL
F=869 F-869 POLY
Chapter Summary
This chapter has contained more theoretical background than any other
chapter in Using FoxPro. It’s essential that you understand the basic
theory of relational databases in FoxPro, because it is those relational
capabilities that give FoxPro the power for you to tap.
Now it’s time to learn how to put this relational database background to
work, entering data into FoxPro and creating inquiry screens that access
information from related databases at one time.
Data Entry and
Editing with
Multiple Files
= n Chapter 6 you learned when a multiple-file, relational database is
= best, how to define that system, and how to create it. This chapter
delves more deeply into entering, editing, and viewing data in such a
database.
In this chapter, you learn how to use FoxPro’s built-in capabilities to look
at more than one related file at a time. You learn how to create a user-
defined function to ensure the integrity of the relationship when data is
entered.
The power of a relational database is its capability to draw data from dif-
ferent files at the same time. In this chapter, you learn how to create a
form file that will enable you to access data in several related files. To do
this, you must learn a bit about text editing in FoxPro, about how Fox-
View screens are turned into FoxPro format files, and how to change that
process just a bit, to your advantage.
This chapter also teaches some “tricks” with FoxPro query and editing
screens, such as entering a key value to have FoxPro find the right record
and display the fields of that record and all related records. Because this
technique requires some FoxPro programming, you also learn the basics
of programming.
201
202 Part II: Intermediate FoxPro
Editing Text
Because you must do some text editing in this chapter, you need to learn
the basics of the FoxPro text editor. If you have worked with memo fields,
you already know how to use it; the FoxPro text editor is what you use to
enter and edit information in memo fields. To edit a program file in Fox-
Pro, choose New from the File menu, select Program, select OK twice, and
the Editor window appears (see fig. 7.1). Zoom the window to give you
the full screen to work with.
ET COLOR TO R/N
DR eAare “Customer Number: “
6,38 “Contact Date: "
Cal "Salesperson: "
8,25 “Date to Follow-up: "
9 9,34 “Comments: "
9 18,33 "Sale made? ”
Unlike the Memo window text editor, long lines do not wrap to the next
line in this mode; you must press Enter to end a line. When FoxPro is
executing a program file, it processes one line at a time. If you want to
continue a long line on the following line, place a semicolon (;) at the end
of the first line. Place some text in the text window. Because you’re just
experimenting, any text will do. Note that as you reach the right margin,
the screen scrolls to the right, causing text at the beginning of the line to
disappear off the left edge of the screen. Press Enter to end a line and
return the cursor to the left edge.
Using a mouse to work in the text editor is easy. To move the cursor
anywhere in the file, place the mouse pointer and click. You also can use
the scroll bars to get to the part of the file you want. To select a block of
text for deleting or moving, for example, drag the mouse from the start of
the text to the end. The next command you issue applies to the entire
selected block. Figure 7.2 shows a highlighted section of text, ready to be
copied or cut.
Chapter 7: Data Entry and Editing with Multiple Files 203
From the keyboard, you also can navigate in the text window. To move
the cursor, use the following keys:
Key Action
To move text, highlight the text you want to move and choose Cut from
the Edit menu. Move the cursor to where you want the text copied and
choose Paste from the Edit menu.
If you want to copy text, use the same procedure as Cut, except choose
Copy from the Edit menu. When you Paste, the text is copied and the
original text remains where it was.
or
@ row, col GET field_name
Row and col represent integers that indicate where FoxPro will place the
SAY or GET field on-screen. Each of these commands has several options
and clauses (some of which were presented in Chapter 2). These two
commands are essential for writing to and reading from the FoxPro
screen.
work areas. Load the database files just as you would from the command
line in FoxPro or FoxBase, using SELECT and USE. Figure 7.3 shows the
FoxView opening screen with the commands for loading three databases.
When you have loaded your databases, press F10 to move to FoxView’s
Form view.
FoxView C:>select 3
FoxView
As you can see in figure 7.4, FoxView’s Form view shows only the fields
for the first database file you used. FoxView places each database form on
a different page. Press PgDn to see subsequent database files, shown in
figures 7.5 and 7.6. Because this format will never do for multiple-file,
relational input screens, you must move all the fields onto one screen.
The second step is to move the fields on each page to their approximate
location on the finished screen. You don’t have to be exact, because you
can move the fields around later, but you want to avoid overlapping fields
when you combine the multiple screens.
206 Part II: Intermediate FoxPro
Cust_num
Ordr_date
Fig. Wee Salespers
, Part_num
The first aty
database used in
the FoxView shell
appears on Page
1 of FoxView.
Cust_name
Addr_ il
Fig. 7.5. Addr_Z
City
The second State
database is on Zip
Phone
Page 2. Contact
Credit
Last_pur
Last_amt
Preferd
The next step involves moving all the fields to Page 1 so that they all
appear on-screen at once. Use PgDn to move to Page 2, then press F6 and
use the Tab and right-arrow keys to select all the fields. Press F3 (Move)
and PgUp. All the fields on Page 2 will be moved to Page 1, where you
can position them as necessary. Repeat this process with the fields on
Page 3, moving them to Page 1 and positioning them there.
Chapter 7: Data Entry and Editing with Multiple Files 207
C: INUNTRY.DBF G Z,@
Part_num
Keyword
Descr Fig. 7.6.
Supplier
Qty_onhnd The third
Qty_rorder database is on
Price
Cost
Page 3.
Auto_rordr
Comments
You have combined the two or more screens that FoxView created onto
one screen, combining all fields. Press F10 to return to Form view where
you can see the results of your handiwork (see fig. 7.7).
Customer Name
Address
URS Hoth
City State [i Zip The three
database screens
Phone moved to Page 1.
Cust_num
Ordr_date
Salespers
Part_num
Oty
Part_num
Keyword
Descr
Supplier
Qty_onhnd
Price
be
Cost
Now you can move, size, and change the screen to your heart’s content.
FoxView enables you to emphasize data, separate it into logical groups,
and create boxes and labels to give the screen sense and shape. Chapter 3
a
contains complete instructions for adding titles, text, and boxes to a Fox-
View form. Figure 7.8 shows the completed screen for the example
database system.
Press Esc to activate the Menu bar, move to the Gen selection (if neces-
sary) and choose Select from the Template List. When the Template menu
appears, choose FORM1, Format File Generator, just as you would for a
single-database file system. Give the Format file a name and quit FoxView,
returning to FoxPro.
In FoxPro, set up your databases as you need them for this form, including
indexes and relations. Add the Format file to the controlling database
through the View Setup window, or by entering
You know that when you change a record in the controlling database, the
information from thé related files also appears on your screen. But if you
choose Change from the Record menu, all you see is a screen containing
fields from the first database you used in FoxView (see fig. 7.9). What
happened? Where did the rest of your form go?
Fig. 7.9.
Customer Number:
Using the format
file with Change
shows fields from
only one
database.
Order Date QUBEV) Salesperson
Part Number Qty
a
For some reason, the default form generator creates a form for only the
first database file you loaded into FoxView, the one that was on Page 1
originally. It is, fortunately, a fairly simple task to create a new form gener-
ator that builds a form file for all databases.
In the process of doing so, you will learn some important information
about how FoxView and FoxPro team up with a program called FoxCode
to generate form files and complete applications.
choose Open from the File menu, place an X in the All Files box and
choose the Format file name you specified in FoxView. The Format file
name will have an FMT extension (see fig. 7.10). Your Format file is a
series of SAY statements with any PICTURE and RANGE clauses you may
have specified. There also will be lines that determine the color of the
fields (SET COLOR TO BU/N) and commands to create the boxes.
If the Form has changed FoxPro’s screen colors, you can reset them by
entering the following commands in the Command window:
SEI EOLOR GO
CLEAR
Unfortunately, the FORM1 template file you used to create your Format
file is written in such a way that it processes only the first database it
encounters in the FoxView table. Fortunately, it is quite easy to create a
new FoxCode program that processes all the databases.
to
Move through the FORMALL.GEN file to row 18, which contains the line
<<#include 'GENFLD. INC'#>>
to
These lines should now look like those in figure 7.11. By changing these
lines, you have instructed FoxCode to look for different include (INC)
files when building the FORMALL template. Save the file and press Esc to
quit.
t>>
«<x-—-General modules-—-%>>
<<ttinclude °GENPRG.INC’ t>> <<xContains GetPrgName,
etc. *>>
<<tinclude ‘“GENSAY.INC’#>> <<xTo generate Grow,col SAY,etc. *>>
<<ttinclude ’GENBOX.INC’#>> <<*To generate boxes,etc. >>
<<ttinclude *GENHUE. INC’ #>> <«<xContains AtrCode,etc. *>>
<<tinclude “GENFLDAL.INC’#>> <«*Contains GenLabel,GenField, etc. *>>
<<ttinclude “GENFILE.INC’#>> <<«xContains GenHeader, GenFooter, etc, *>>
<<«x-—-Specific modules-——-*>>
<<#include °GENFMTAL.
INC’ #>>
Ct
Because you have instructed FoxCode to look for the GENFMTAL.INC and
GENFLDA.INC files, you must create them. First, open the GENFLD.INC
file from the same directory (TEMPLGEN) and immediately save it as
GENFLDAL.INC. Change the first line from
<<*GENFLD.INC*>>
to
<<*GENFLDAL. INC*>>
Move through the file until you see the function titled getFIELD. Continue
moving through the file until you see the lines shown in figure 7.12.
You need to make only one change. In the line that reads
Save the GENFLDAL.INC file and use the File Open menu to open
GENFMT.INC. Immediately save the file as GENFMTAL.INC. Again, change
the first line to reflect the new file name, from
<<GENFMT. INC*>>
Chapter 7: Data Entry and Editing with Multiple Files 21 4
System File
Edit Database Record’ Program Window.
. GENFLDAL.INC
if IsWithPrefix and (fldtyp <> ‘M’) and (fldals <> ’M’)
strg := strg + ljust( fldprefix + left fldnam,18-len(fldprefix) ),1@ )
else <<xall others*>> :
if fldals $ “AM’ <<x PRIMARY and MEMORY workareas *>> Fig. 7.12.
strg ‘= strg + l]just( fldnam,18 ) Change AM
else
strg := strg + fldals + ’->’ + ljust( fldnam,18 ) to M.
endif
endif
<< X-—-PICTURE-—-*>>
if fldpic
Strac=sstng e+ | PICTURE sc tt ldpicy+) 977
elsif fldtyp = °N’ <<«*force picture on numerics*>>
picstrg := replicate( ’S’,fldwid )
if flddec
picstrgl fldwid-flddec ] :=’
endif
strgs=esurg +) PICTURES + picstrg +
endif
RETURN strg
end <<xgetFIELDx>>
to
<<*GENFMTAL. INC*>>
Move through the file until you reach the function GenPlusFormat. Figure
7.13 shows this function.
procedure GenPlusFormat 5
beg Fig. 7.13.
forall pages The
WriteLabels
genln( ’*’ ) GenPlusFormat
UriteFields procedure to be
if pagcount <> pagtotal
genIn( ’READ’ ) changed.
endif
endfor
end <<*GenPlusFormatx>>
procedure GenOneFormat
begin
genln( ‘SET COLOR TO ’,ScreenColor )
genln( ‘CLEAR’ )
genln( ‘SET COLOR TO ’,StatusColor )
genln( ’@ @, @ SAY “Record: “ + SUBSTR( STR(RECNO( )+1@88808,7),2 )’
WriteLabels
genln( ’*’ )
Next, place
forall databases
214 Part II: Intermediate FoxPro
endfor
between the endfor and end lines. The modified function should look like
figure 7.14. Save the file using the Save option from the File menu.
procedure GenPlusFormat
begin
Fig. 7.14. forall databases
The changed forall pages
GenPlusFormat Peers
genln( *x’ )
procedure. WriteFields
if pagcount <> pagtotal
genln( ‘READ’ )
endif
endfor
endfor_
end <<*GenPlusFormat®> >
procedure GenOneFormat
begin
genln( ‘SET COLOR TO ’,ScreenColor )
genln( ‘CLEAR’ )
genln( ‘SET COLOR TO ’,StatusColor )
genln( ’@ @, @ SAY “Record: “ + SUBSTR( STR‘ RECNO( )+1888888,7),2 >’
CD \FOXPRO\TEMPLGEN
FOXCODE FORMALL
When FoxCode is finished, copy the output COD file to the directory
\FOXPRO\TEMPLCOD by typing
Return to FoxPro. First, move to the directory from which you originally
started FoxPro with the DOS CD command, and then start FoxPro as
follows:
CD\FOXPRO \ cust
FOXPRO
Chapter 7: Data Entry and Editing with Multiple Files 21 5
where table_name is the name of the table you saved in FoxView. Figure
7.15 shows the FoxView screen as it loads the designed table.
Now you can generate your new form. Press Esc to display the Gen menu.
Choose Select from, and you will see the Template screen. The FORMALL
template is listed with the title Multiple File Format Generator. Choose
FORMALL, give your format file a name (you can use the same name as
you did before and overwrite the existing file), and let FoxView invoke
your newly created template file. When it is finished, return to FoxPro, set
up your databases, and choose Edit from the Record menu. The first
record in the controlling database appears and, with it, all the information
from the related records in the related databases (see fig. 7.16).
This has been a complicated process to create just one form. Actually,
though, most of the work in this section created not one form, but a file
that you can use every time you need to display data from different
databases on the same screen. Now it’s time to learn how to use the form.
216 Part II: Intermediate FoxPro
You now can set your format file either with the Format check box in the
View Setup dialog, shown in figure 7.17, or by issuing the Command win-
dow command
where fmt_filename is the name of the Format file you generated in Fox-
View. Now, you can use the Record menu to access and view related
records.
that the user of your database, whether it’s you or others, cannot enter
data that is inaccurate or invalid. FoxPro provides an excellent way to do
this, allowing you to attach to a data-entry field a RANGE or VALID clause.
C: ORDER. DBF
t. Als Field Typ Wid Dec Picture Range Valid Init Calc
1 AeRBOXOBJEGT season one IC IL IC IC ]
Fig. 7.18. Z.
3.
A Cust_num
B Cust_name C
C 6
VA)
C
[i
IC
vE
IC
iC
alfa
IC
IC
IC
]
]
Adding RANGE 4. B Addr_i C VAs) C IC I IC ic J
5S. B Addr_Z (e (As) C IC IC IC iC J
limits to a field
Cy) (ebay Coeds C IL IL IL IC J
in FoxView. 7. B State C Z C I IL I IL J
8 “Ba Zip G } C IC allt iC IC J
3. B Phone C 10 C IC a}{e it IC J
18. A BOXOBJECT B (¢:! (je IC ats Il JC J
11. A Ordr_date D 8 iE IC IL IL IL ]
1Z. A Salespers G 3 [ it it IC iC ]
13. A Part_num C 15 C IC ie ili iC ]
14. A Qty N 5 c lac ,Savane 1 I ]
15. C Keyword (t: 10 C IC IC iC iC ]
16. C Descr Cc 25 [ IC IC alt IC J
17. C Qty_onhnd N 5 iE lk IC Alle IC J
18. C Supplier Bs 25 C IC JifE IC IC J
oolf= 1)
Think of a VALID clause as half of an equation, with whatever the user has
entered into the field as the other half, as follows:
If both sides of the equation are equal, FoxPro accepts the entered data; if
they are not equal, FoxPro will reject it. For example, if you have a char-
acter field named ZIP, and you only want the user to be able to enter the
values "98080", "98081", or "98082", your equation would look like
Figure 7.19 shows the Table View with this VALID clause entered in the
ZIP field.
When you generate the Format file for this screen, FoxView will automat-
ically add the necessary VALID statement and parentheses. When this for-
mat file is used in FoxPro, then, the user will only be able to enter these
three values; any others will cause FoxPro to place an Invalid Data Entry
message on-screen and reject the input.
Chapter 7: Data Entry and Editing with Multiple Files 2? 19
C: ORDER. DBF
You create a UDF as a FoxPro .PRG program file by choosing New from
the File menu and selecting ( ) Program from the radio buttons in the
New dialog. A text window opens and you enter your UDF. When you’re
done, save it using the Save option of the File menu, giving it a name.
Then you can add the UDF to the VALID column of the field in FoxView.
Sound complicated? It isn’t really; follow along as we create a simple UDF
that accomplishes the same ZIP test as above.
ZIP_TEST()
Generate the Format file as usual and return to FoxPro. The
format file created has a VALID clause in it for ZIP, so you must
create the UDF named ZIP_TEST.PRG.
220 Part II: Intermediate FoxPro
2. Choose New from the File menu, select Program and OK. A text
window opens. Enter the following program text into the window:
FUNCTION ZIP_TEST
PARAMETER ZIP
IF (ZIP ="98080") .OR. (ZIP ="98081”" .OR. (ZIP ="98082")
RETURN -F.
ELSE
RETURN .T.
ENDIF
The first line tells FoxPro this is a function named ZIP_TEST. The
second line accepts the value from the data-entry field, which will
be sent to the function by the VALID clause. That value is
assigned to the memory variable ZIP for testing.
3. Save this program using the Save option of the File menu, naming
it ZIP_TEST. You now have a valid user-defined function. When
you use a format file that has this UDF in a VALID clause, FoxPro
will take a value for the ZIP field, send it to this UDF and wait for
the UDF to “do its thing.” When the UDF tests the value and
returns a true or false to the VALID clause, FoxPro acts
accordingly —rejecting the data with an error message if the
VALID clause receives a false, and accepting it if it receives a true.
This UDF would ensure that the user couldn’t enter a CUST_NUM value in
the controlled database of two related databases unless the CUST._. NUM
value already existed in the controlling database.
Once you have selected the Change (or Edit from the Command window )
command, you can use the PgUp and PgDn keys to move forward and
backward through the database. Again, you move through the controlling
database; the related databases follow automatically. When you are fin-
ished looking at a data screen, pressing Escape returns control to FoxPro.
The FoxPro menu bar is now usable again.
222 Part II: Intermediate FoxPro
In a large database, you will find yourself using Seek frequently as you
look for specific records based on the index expression of that database.
With a little bit of FoxPro “twiddling,” you can create a file that eases the
task.
The process you want FoxPro to follow in this program file is as follows:
3. If the user doesn’t want to see more, exit from the loop.
The FMT format file already contains all the SAYs needed, with proper
location and PICTURE clauses for formatting. You can edit that file to
include the user input of key fields, the test to see if it’s time to exit the
loop, and the loop itself. By saving the file as a PRG program file, you can
execute it with the Do option, rather than using it as a FMT file, which
allows no control statements.
ET COLOR TO ORDER_Q.
PRG
5,19 SAY A rf
13,13 SAY A
13,34 SAY
g@qaquxa A->Salespers
15, 2 SAY A->Part_num
aga15,18 SAY A->Qty PICTURE "99999"
2. GET each memory variable at the same location as the SAY of the
form.
This procedure is not difficult. In the example, only one key field is in the
controlling index, order_num. The lines to insert to read this key field and
seek on it are as follows:
These lines should go before the SAYs of the data fields in the PRG file. If
your key field is made of a FoxPro expression, you must insert another
line after the READ and before the SEEK that creates that expression. If,
for example, your controlling database was indexed on FIELD1 + FIELD2,
the read routine would look like the following:
m=FIELD] =” ‘i
m= FIELD2.— ~ a
@ 1, 0 GET m_FIELD1 && GETs on screen
@ 2, 0 GET m_FIELD2
READ && read all three GETs
m_key = m_FIELD1 + m_FIELD2
IF m_key = ” fe && nothing entered
RETURN && back to FoxPro
SEEK m_key
Figure 7.21 shows the PRG file, with these lines inserted. The multiple
SAYs have been omitted to save room.
x--- end of lines added to input and seek on the key field
Remember that your view must be set up with the controlling database
indexed on the proper extension (in this example, the controlling index,
ORDER, is indexed on CUST_NUM). The seek will find the first record
that has the key field (CUST_NUM) equal to the value entered. If there is
none, all screen fields will be blank.
Your PRG program now has the capability to read from the screen the
fields you want to seek on, do that seek, and present the data. Save the
Chapter 7: Data Entry and Editing with Multiple Files 225
PRG file and try running it. Choose Do from the Program menu and select
the newly created file. Assuming that your database files are set up cor-
rectly, you are presented with a form that asks for input for the key field.
When you enter a value and press Enter, the program continues by seek-
ing on the value and placing the found record on-screen, along with infor-
mation from related databases. Figures 7.22 through 7.24 show a form
awaiting key field input, the entered input, and the results.
Customer Number: _
Fig. 7.22.
The form waiting
for entry of the
key field value.
Customer Number: 6_
Fig. 7.23.
Entering a
CUST_NUM
value to find.
226 Part II: Intermediate FoxPro
Customer Number:
Customer Name [Offxabel Belin etal =n
Address GLYARPOE mic
Fig. 7.24.
The multiple-file City Sir Wh) Zip GREY)
: Phone EEPECEy4)
form showing
information
from three Order Date (MEY) Salesperson
Part Number Qty Keyword Description Quantity Onhand
databases. Cee GE) Sos SEAL
Supplier Price Cost
Lal 8.94
Go to the line just above the lines you entered before, in which you ini-
tialize the memory variables. Add the command
DO WHILE .T.
Now go to the bottom of the file and, just above the EOF: ORDERQ.FMT
statement (which is actually superfluous and can be deleted), add the line
ENDDO
FoxPro will repeat every statement between the DO WHILE .T. and the
ENDDO endlessly. The only way to get out of this loop is through the test
after the READ statement; if nothing was entered in the GET key field
memory variable, your program returns from that test and you are
returned to FoxPro.
Chapter 7: Data Entry and Editing with Multiple Files DOF,
Changing the CONSOLE state kills the Press any key to continue message
that WAIT usually issues. If you want to see that message, leave out the
SET CONSOLE commands.
* Program.: ORDER_Q.
FMT
* Author..: John Zumsteg
* Date....: 03/04/90
* Notice..: Copyright (c) 1990, Northwest Microsystems
* Version.: FoxBASE+, revision 2.10
* Notes...: Format file for ORDER.DBF
DO WHILE .T.
mCUST_NUM = "" sc
@ 5, 19 GET mCUST_NUM
READ
IF mCUST_NUM = "' a
RETURN
ENDIF
SEEK mCUST_NUM
Se en a
ES NE TE
228 Part II: Intermediate FoxPro
@ 12,0 TO 18,79
@ 13, 2 SAY “Order Date "'
@ 13,22 SAY "Salesperson "'
@ 14, 2 SAY “Part Number "'
@ 14,18 SAY "Qty "
*
*-- end of lines added to input and seek on the key field
ENDDO
*
* EOF: ORDER_Q.PRG
Now, after FoxPro has gotten the key field value, performed a seek on it,
and displayed the data, the second READ activates the GETs you have just
created. You will be able to enter data into those fields you have desig-
nated as editable by the GET statements.
* EOF: ORDER_9.
PRG
4+
Chapter Summary
This chapter introduced programming, user-defined functions, and Temp-
late programs. The examples presented in this chapter will make your
FoxPro systems far more reliable and easier to use.
If you master these concepts and realize the potential that FoxPro pre-
sents through programming, user-defined functions, and Template pro-
grams, you can use these tools to create sophisticated and elegant FoxPro
systems that cannot be created in other database systems without huge
amounts of programming.
Data entry and inquiry into multiple-database FoxPro systems can be as
simple as single-database systems. But with a bit more work and the
knowledge of FoxPro that you learned in this chapter, you can make
multiple-database FoxPro systems do just what you want them to do,
quickly and elegantly.
FoxPro Tips, Tricks,
and Techniques
=§ o far, you have absorbed a great deal of information about using Fox-
= Pro, and you're probably getting a little weary of having new concepts
and techniques thrown at you. This chapter will be more enjoyable. This
is a potpourri chapter that presents tips and tricks that make FoxPro eas-
ier and more fun to use.
231
232 Pew tntemmaiiiate Rare
Using a Mouse
Fox Software maintains that using 2 mouse Matead of the Reyhboand & the
QUICKEN Way Of SPeeding up FoxPro. The mouse makes QPOAAAQ, VOW,
Nazing, and Moving Windows uadelievahly quick aad easy, Working 2 Ge
logs WR the keyboard requires many Key presses % get W the rem bax
and make 2 selection, With the mouse, B'S a Simple poimtandclick OES
tran. AS you learn more adout FoxPro, you will dad yournetf RAINE
MOUS MOVEMMATD and selections wath Keyboard Shormons bat ever Re
advanced FoxPro user. the mouse speeds all Qperations
With RoxPro comes an aftr to purchase am excelent mouse at [ow cat:
f you Gont have a mouse, | urge yor to take Rox Software ap aa their
offer.
ane
Holds General Ledger files
and programs
Holds files and
prograns conmon to
Fig. 8.1.
all accounting Holds Accounts Payable files An MS-DOS file
nodules and programs directory
Structure.
Holds Accounts Receivable files
and programs
eeee eee
The last concept to understand is paths. You may want DOS to run a pro-
gram that isn’t in the current directory. You can give DOS a path to follow
as it looks for a program. Again, using the accounting example, if you are
in the GL directory and want to run the ACCT program, which is in the
ACCTING directory, you can issue the DOS command
PATH = \ACCTING
Now when you ask DOS to run a program, it first looks in the current
directory (GL). If the program is not there, it starts down the path, look-
ing in each directory named in the path for the program you have asked
for. For example, if your path is set by
PATH = \ FOXPRO;\GL;\ACCTING
and you enter the command
FRAMMIS
which tells DOS you want to execute a program named FRAMMIS, DOS
will look for that program in the current directory first. Then if FRAMMIS
is not found there, DOS looks for it in \FOXPRO, \GL, and \ACCTING.
Only if FRAMMIS is not found in any of these directories will DOS issue
the bad command or filename error.
Directories, paths, and batch files can help you organize your FoxPro
applications.
234 Part II: Intermediate FoxPro
Fig. 8.2.
The FoxPro
directory
structure, created GOODIES
during FoxPro
installation. SAMPLE
TEMPLCOD
TEMPLGEN
TUTORIAL
J
If you have created a FoxPro application, the many database (DBF), index
(IDX), report (RPT), and form (FRM or FRX) files are in the same direc-
tory as the FoxPro program files. This method works for one application,
but if you add a second and a third, things begin to get difficult to manage
in that directory. Figuring out which files belong to the application you're
working with is difficult. To solve this problem, you can create a subdirec-
tory for each FoxPro application and keep each application’s files in its
own subdirectory.
~ Fig. 8.3.
FOXPRO A FoxPro application An example of
FoxPro
ADV_BOOK A FoxPro application applications in
Separate
A FoxPro application directories
CD \FOXPRO
Then enter
MD app/
where app/ is the name of the application directory you want to create.
MS-DOS directory names have the same rules as MS-DOS file names: you
can use up to eight characters or numbers, with no spaces. Directories do
not have an MS-DOS file extension.
You can change the current directory while in FoxPro. This enables you
to work with different applications without having to exit FoxPro and
change the current directory with the MS-DOS CD command. Changing
the path tells FoxPro where to look for files when listing scrollable file
lists, or when trying to open views that contain file names.
D4 36 Part II: Intermediate FoxPro
To change the Path in FoxPro, choose Files from the View window. The
View Files dialog is shown in figure 8.4. You can change the default drive
by selecting the Default Drive box, and you change the path by typing an
X in the Path check box or by pressing P. You will see the Enter Path
Name dialog, shown in figure 8.5. In this dialog, you select the path you
want FoxPro to use by highlighting the subdirectory you want and choos-
ing Select.
Help...
C: \FOXPRO\FOXHELP.
DBF
Resource...
C: \FOXPRO\FOXUSER.
DBF
FILE SELECTION
In the scrollable list, you see only subdirectories, which are delimited by
square brackets [directory]. The C..] entry, which is always the first entry
in the scrollable list, represents a subdirectory’s parent directory. If, for
example, you are in the directory C:\FOXPRO\AMMS and you want to
see the subdirectories in the C:\FOXPRO directory, you would choose
C..J, and FoxPro would show the list of subdirectories in C:\FOXPRO.
You can always tell where you are in the directory structure because Fox-
Pro lists the directory you have chosen just below the Enter path name
line at the top of the window.
You can put any number of directories in the path. If your path is
The first line of this batch file sets the path command, ensuring that Fox-
Pro can be run from any subdirectory. The second line changes to the
\FOXPRO\AMMS directory, which contains the database, index, report,
and form files for a specific application. The last line invokes FoxPro.
to display the FoxPro text editor and enable you to create the batch files.
Assuming that you’re working from a hard drive defined as the C: drive,
this command creates the batch file in the root directory, from which you
can execute the file as you start up your computer.
Utility Programs
Fig. 8.6.
A hard disk drive Batch Files
directory setup.
DOS Programs
ADU_BOOK
Because FoxPro searches the current directory first, you can have a differ-
ent CONFIG.FP file for each FoxPro system you create, as long as you
Chapter 8: FoxPro Tips, Tricks, and Techniques 239
keep each system in a separate subdirectory. You also can have a custom
CONFIG.FP in your FoxPro directory for times when you don’t need a
system-specific one.
Following is a list of commands you can put into a CONFIG.FP file, which
I think are most helpful. The FoxPro manual has a more detailed descrip-
tion of the many things you can do with this customizing tool. Most of
these commands are the equivalent of FoxPro SET commands; in the
COMNFIG.FP file the SET is omitted. In the following commands, the setting
that FoxPro uses as a default is shown in italic.
You also can assign character strings to the function keys (except F1). If,
for example, you want the F2 key to execute the command DO TEST, you
would place into the CONFIG.FP file the following line:
F2="DO TEST;”
If you have a favorite text editor, you can use that instead of the built-in
FoxPro editor. To tell FoxPro what editor to use, place the following line
in your CONFIG.FP file:
To define the word processor, which will be used in memo field editing,
enter the following line:
WP ="\BRIEF\B’
Note | If your text editor doesn’t load, it may be that it requires too
much memory. Anything over 384K is too large for FoxPro to
load and use on a 512K machine.
The CONFIG.FP file can help you customize FoxPro to your likes, or to
the preferences of those who will be using a system you create.
Creating a View
Creating a view seems simple, but has some complications. To create a
view, set up FoxPro the way you want, with database files opened,
indexes set, format and field statements as necessary, and the many SET
ON/OFF switches set the proper way. Then select Save from the File
menu. You will see the Save View As dialog, shown in figure 8.8, which
asks for the name you want to assign to this view. The files scrollable list
shows any views already defined in the current directory to aid you in
choosing a unique name. Once you have given the view a name, you can
save it.
« Save »
relation set up or the wrong controlling index (or the database and work
areas reversed, as I often seem to do), your report or inquiry will not
work as you expect it to. Using views requires care in setting them up.
Views ensure consistency. Without views, you would have to set up Fox-
Pro with databases, indexes, and so on, every time you wanted to change
things; with views, you can save the configuration and know that every
time you want it back, you will have it, with all the details.
Note | When you save a Report Form, you see a Save Environment
check box in the Save Report As dialog (see fig. 8.9). If you
selected that option, FoxPro created a pseudo-view file with
the report’s name. If you later run the report, FoxPro opens
that view file and sets up itself accordingly. If you have
another view in place, it disappears, and you must open it
again to reestablish it. Remember this when you run a report
and find that your view has changed.
Directory
« Save »
QX_RPT1. FRX
Browse menu
Edit menu
Ctrl-V Paste
Using Macros
A macro is a way of assigning a string of text to a specific key or combina-
tion of keys; when you press that particular key-combination, FoxPro
“plays back” the string of text as if you entered it from the keyboard. Mac-
ros Can save you much time and typing if you find yourself typing a partic-
ular sequence of keystrokes over and over.
Chapter 8: FoxPro Tips, Tricks, and Techniques 245
Creating a Macro
The first step in creating a macro is to choose Macros from the System
menu. You see the Keyboard Macros dialog shown in figure 8.10.
e \
Fig. 8.10.
Keyboard Macros The Keyboard
Macros dialog.
The scrollable list shows all the keys and key combinations for which a
macro has already been defined. Notice that the function keys are listed.
These macro assignments are as follows:
Fl Help
F2
F3
F4 Dir (lists the database files in the current directory)
F5 List Structure
FG Display Status
F7
F8
F9 Append
Function keys
Alt-any key (including function keys)
Ctrl-any key (including function keys)
Shift-Alt-any key
Shift-Ctrl-any key
Once you have entered your key combination, select OK, and FoxPro
returns to the Command window, with a message reminder that you’re
recording a macro. Enter the keystrokes you want; FoxPro executes them
as you enter them. When you have finished, press Shift-F10 to stop record-
ing. FoxPro displays the Stop Recording dialog, shown in figure 8.11.
Select OK to end the recording process.
Fig. 8.11.
The Stop
Recording dialog. Stop recording CTRL_X?
To use the macro, press the key combination you defined. FoxPro enters
the commands in the Command window just as if you had entered them
from the keyboard. You also could put into the macro text strings that
you want entered into a field in a database; pressing the key combination
during an Append operation inserts the text string into the fields.
Macros can be a great help when you have a string of commands or text
that you find yourself repeating over and over. Any time you find yourself
doing this, think about using a macro to save time and tedium, and
reducing the possibility of making typing errors.
Chapter 8: FoxPro Tips, Tricks, and Techniques 247
The command shown opens the file designated as CUSTOMER and assigns
to it two index files, CUSTNAME and CUST_NUM, making the first file the
controlling index. All commands in dBASE III, dBASE III PLUS, dBASE IV,
and FoxBase+ are entered this way. Contrasted with FoxPro’s window
and menu user interface, command-line-driven programs are less friend-
ly and require a more thorough knowledge of the program to do even
simple tasks.
Still, the command line has some advantages. As you become more famil-
iar with FoxPro and its commands, you will find that you can enter the
command
USE CUSTOMER INDEX CUSTNAME, CUST_NUM
248 Part II: Intermediate FoxPro
Fig. 8.13.
The FoxBase +
screen, with a
USE command
on the command
line.
much faster than you can navigate through the File Open window, and
then the View Setup window to get everything opened and in place. The
Command window can be a high-speed way to get things done in FoxPro,
but it does require more familiarity with the system.
USE is the verb, telling FoxPro what action to take. Here the command
tells FoxPro to set a database into the current work area. CUSTOMER is
the object, telling FoxPro what database to associate with the USE com-
mand. INDEX is a modifier, which tells FoxPro that the names following
are index files to associate with database. The case of the commands,
uppercase or lowercase, have no effect on the command. USE, Use, use, or
even uSe are all the same thing to FoxPro.
You also can hide the Command window, using the the Window menu
Hide option. This is discomfitting, at best, because you can still enter com-
mands from the keyboard and execute them, although you cannot see
them going into the Command window. If this happens—usually by acci-
dent—just choose Command from the Window menu to reopen the Com-
mand window.
You may find the Command window an annoying presence on the screen.
As you become more accomplished, you can watch how FoxPro translates
your menu commands into Command window strings before it executes
them. Soon, you will be using the Command window to speed up your
navigation through FoxPro.
250 Part II: Intermediate FoxPro
If you were using the mouse to execute these commands, quite a few
point-and-clicks would be required. If you were working in the Command
window, you would use the following commands to accomplish this:
SELECT 1
USE file INDEX file
EDIT
USE
You can create a simple FoxPro program that will execute this sequence
of commands when you enter
DO AMMS
Chapter 8: FoxPro Tips, Tricks, and Techniques 2 51
in the Command window. To create this program, open the File menu and
choose New. In the File Open dialog, choose Program. A program editing
window will open, and you can enter your first FoxPro program.
The editor has essentially the same functions available in memo fields.
Enter the four commands shown in figure 8.15, pressing Enter at the end
of each line. The && symbols tell FoxPro to ignore everything to the right
on a line—the && symbols indicate comments. When you have entered
your program, select File Save and give it a name. FoxPro appends the
PRG suffix, indicating a program file, and saves the program.
program in the
text-editing
window.
The Trace window enables you to “trace” the execution of the program
file a line at a time. To use the Trace window, select Step from the Pro-
gram menu, which tells FoxPro to go through any program file one line at
a time. Choose Do from the Program menu. FoxPro executes the first line,
and then stops. Now you can open the Trace window from the Window
menu. You will see the Trace window, shown in figure 8.16, with the cur-
rent program in it. Selecting Resume causes the next line to be executed
and highlighted. In this way, you can follow what is happening in your
program. Obviously, with a four-line command program, Trace is of little
help, but when you have a large command file, Trace can show you what
FoxPro is doing with your errant program.
<Cancel> <Resume>
Chapter Summary
For all its ease of use, FoxPro is a complex program. As you become more
expert with it, you will find an increasing need to take short-cuts to make
your time more productive. This chapter focused on ways to do that.
You have learned how to use views to simplify setting up a specific envi-
ronment, ensuring it to be consistent from session to session without hav-
ing to remember every detail and go through the tedious process of
setting them. You have seen how the CONFIG.FP file can customize Fox-
Pro to your liking. Macros enable you to store frequently used keystrokes
or mouse sequences and play them back, thus saving you time. And finally,
Chapter 8: FoxPro Tips, ‘Tricks, and Techniques 253
you have learned the basics of creating FoxPro program files to execute
long sequences of commands automatically. All these techniques make the
sophisticated capabilities of FoxPro easier and more productive to use.
Now it’s time to move to the next step in using FoxPro’s power: creating
and running reports on multiple-file, relational databases.
2 54 Part II: Intermediate FoxPro
Reporting on
Multiple Database
systems
=J n Chapter 6, you learned basic reporting techniques, working on a one-
= 4H database file system. FoxPro’s report writing capabilities are far more
sophisticated than that. This chapter introduces you to reporting on more
than one database at a time. You also see how to use some of the
sophisticated techniques of the FoxPro report writer.
255
256 Part Il: Intermediate FoxPro
1. Each page of a report should contain a title, the date, the time the
report was printed, a page number, and, if applicable, column
headings for the report. This presents the report reader with
essential information on each page.
2. Present the information in a logical order. You may choose to
print the records in alphabetical order, or you might want to
order the records according to the value in a numeric field or by
a date in each record. You control the order of a report with the
database indexes.
4. Use lines and boxes to break up the report and draw attention to
data you want to emphasize.
FoxPro takes much of the drudgery out of creating reports. With just a
little forethought, your reports can show off your database skills.
SciIL
P.O. Box 2231
Kent WA °
CPL fo TAR ANE PRE ON ESEPRT RSE TRS DR BS CTREEY RE PT BS LACT RT ELST AR TOT APY PORTA BY Ao ASTANEAE TE SCAN COSY NAY RC YD Da Ae PEL ee CF UF
Fig. 9.1.
Order Sales- Part Part Part | A report on a
Date erson Number Quantit Keyword Price ‘
7 y a relational
01/02/90 DJZ CASCADE 6045 3 0.00 database system.
01/22/89 DIZ IN E-2138 100 PULL 214.00
LE PED DP OL DEDY TIAL TIE DT AD PRPS O EDIE IAD DIP TILE TE BNA DETTE LETITUND, CAE PIO LEO RTE LEG ELE G
S & C Autos
3342 E. Elwood
Phoenix AZ
CRY BY BETETA BE RPSL AT PRELSP M OLES ET Pd PEP RET TNT REY REDE AM 2aTPY IETS AEEAOEdit dal(8 Aa AELPe ABE PRLLSTIATBEYAEEUE ANC SOLE PMR ee OEE Dek dak TT
Generally, you will want to group reports in some order, with appropriate
totals on the grouped data. Also, you can use the Group Header to print
fields about related databases. You can group on the value of a field in a
related database. In this example, you could group on the value of
Se EEE ee eS eee
CUST_NAME in the ORDER field, but for illustrative purposes, this report
will group on the CUST_NAME field in CUSTOMER.
Command
SELECT B
SELECT A
SELECT B
SELECT C
select a
display struc
«Setup >
«Browse?
« Open >
SCOPE, FOR, or WHILE test, FoxPro executes that test and prints the
Detail Band if the record passes the test. Figure 9.6 shows the Detail Band
in the Layout Window with fields from the controlling database.
Add fields to the Detail Band with the Fields option of the Report menu. If
you want to include all or nearly all the fields from the controlling
database in the report, use Quick Report to place all fields on the Layout
View. Choose Form Layout to make sure that all fields get on the report;
in Column Report only as many fields as will fit on the page are placed in
the Detail Band. Then move and delete fields as necessary to make the
Layout view match your report design.
Pou suena |
Pee] Gee]
Report ‘expr>:
Dae] Fig. 9.7.
The Report
Expression
inuntry->keyword _
dialog, adding
fields from a
Field Names: Database: Variables:
related database.
Once the controlling database fields and any necessary related fields are
added to the Detail Band, you should use the Page Preview feature to test
your layout. If necessary, save and run the report to ensure that all is well
so far. Figure 9.8 shows the page preview of the example report. From the
page preview, you can tell whether the relationships you have established
work as you planned.
If you run page preview and find the related database fields are blank or
contain incorrect values, you can be sure that your relationships are not
set correctly.
Fig. 9.9.
Grouping on the [eth J [string] Ltostea:
value of a Break ‘expr>:
related database customer->cust_name
field.
The report will now break whenever the CUST_NAME field in the CUS-
TOMER database changes. Remember, as it proceeds through the control-
ling database, FoxPro will maintain the relation to the controlled
databases.
Chapter 9: Reporting on Multiple Database Systems 26 4
Fig. 9.11.
33423 Airport Drive Page preview of
Cinncinnatti OH 43554 arelarional
Cosars Continent
4923 Wilson Rd
Smyrna TN 33423
AS you can see, it’s a simple task to place fields from related databases into
a report. By setting up these relations, you can ensure that the information
in related databases always refers to the current record in the controlling
database. You should often use page preview as you design your report on
the Layout view to make sure that the body of the report is right. Once
you have all the database fields in the report working correctly, you can
add the frills, such as a title, date and time stamps, boxes, and lines.
ne More Column: 8
Chapter 9: Reporting on Multiple Database Systems 265
What has happened? The data grouping still works, but now the report is
no longer in alphabetical order by customer name. The customer number,
in each of the CUST_NUM fields, does not reflect alphabetical order; cus-
tomer numbers may be assigned as new customers are obtained, and new
customers are not often obtained alphabetically. So as FoxPro proceeds
through the ORDER database, it groups the records for CUST_.NUM 00001
together, then the records for CUST.NUM 00002, and so on. But because
CUST_NUM 00001 is the Zzybob Company and 00002 the Aardvark Com-
pany, that’s the order in which the report is printed.
SELECT ORDER
Decide the name of the new file; here it will be ORD_CUST.
ORDER-—>CUST_NUM = CUSTOMER-—>CUST_NUM
In other words, you want FoxPro to add, in the new database ORD_CUST,
a record each time it finds a match between the CUST_NUM field in
ORDER and the CUST_NUM field in CUSTOMER.
266 Part II: Intermediate FoxPro
FoxPro will look at the first record in ORDER to find the value of
CUST_NUM; then, starting from the top of the CUSTOMER database, it
looks at each record in that database. If the value of CUST_NUM in the
CUSTOMER database matches the value of CUST_NUM in that first ORDER
record, a new record in ORD_CUST is created. When FoxPro has looked
at each record in CUSTOMER, it returns to the controlling database,
ORDER, moves to the second record, and starts again. This continues until
all records in ORDER have been matched against all records in
CUSTOMER.
Finally, decide which fields will be copied into the new ORD_CUST. This
report might require the following fields from ORDER:
Now put all this together into the JOIN command, issued in the Command
window as follows:
The result of the JOIN command is shown in a Browse window for the
new ORD_CUST database (see fig. 9.13).
The database now has all the information required for the example report.
By indexing ORD_CUST on CUST_NAME, you can create a report that
accomplishes your purpose. Note that you still need a relation set
between PART_NUM and PART_NUM in INVNTRY to obtain the KEY-
WORD from INVNTRY. Figure 9.14 shows the Layout view of such a
report, and figure 9.15 shows the final report.
Chapter 9: Reporting on Multiple Database Systems 267
; Fig. 9.13.
Comar 33423 Airport |Cinncinn E-2398 The Browse
Comar 33923 Airport |Cinncinn E-2398 window of a
Cosars Continent}44Z3 Wilson Rdj Smyrna 1486-558] :
Cosars Continent|4423 Wilson Rd] Smyrna 1425-337 Joined database.
Cosars Continent]44Z3 Wilson Rd] Smyrna 381293
Hess Aviation In|334Z Aviation |Portland E-2398
Hess AViation In|334Z Aviation |Portland E-2514B
f Hess AViation In|3342 Aviation |Portland
Northwest Micros|1896¥ 127th Pl]Kent
OshKosh Cow Comp|5534 E. Dairy |Oshkosh
Pickett’s House
OshKosh Cow Comp|}5534 E. Dairy |Oshkosh
Pickett’s House 12/15/98)CL 1754428
SCIL P.O. Box 223i |Kent 82/81/98] CASCADE 662
SCIL P.O. Box 2231 |Kent 83/24/98] F-869
T. Moore & Assoc] unknown Port Ang 16/16/83] BA 988619
T. Moore & Assoc} unknown Port Ang 62/82/98) LP 1425-332
PgFoot
268 Part II: Intermediate FoxPro
TN 33423
Caution When using JOIN, be careful how you use this command,
testing it carefully on a small subset of the database (use
SCOPE, FOR, or WHILE to limit the processing). JOIN
commands can create huge files if not used properly. The
JOIN command starts at the first record and creates a new
record for every record in the WITH database that meets
the logical expression. If, for instance, you had acciden-
tally used the logical expression
To do this, make sure that there is a valid relation between the controlling
database and the controlled database, in the example, between ORDER
and CUSTOMER. That link has been set to CUST_NUM, which means that
the controlled database, CUSTOMER, has to be indexed on its field
CUST_NUM. Now, indexing ORDER on
CUSTOMER-—>CUST_NAME
Chapter 9: Reporting on Multiple Database Systems 269
17 records indexed
Caution | You will be unable to use this newly created index for
anything but reporting. If you try to make this index con-
trol the database without the controlling database being
opened and related, you will get an error message. You
also will get some interesting error messages when you
try to do other standard FoxPro things. When using this
method, create the index just before you run the report
and discard it (by setting the index to some other index
file) as soon as the report is done.
270 Part II: Intermediate FoxPro
Because Character fields can be large (up to 255 characters), and Memo
fields huge (up to 64,000 characters), FoxPro reports require special
capabilities to handle them. When you define a field for a Character or
Memo field, the option Stretch Vertically is presented in the Report
Expression dialog (see fig. 9.17).
« Cancel >
17 records indexed
A field with this option will always have the same width (the width you
define on the Layout view), but will “stretch” vertically to as many lines
as necessary to print the entire field. If you do not select this option, the
field will be limited to the width you selected and one line. Figure 9.18
shows a report with a character field not stretched; figure 9.19 shows the
same report with the field stretched.
If you place fields below a field that will stretch vertically, you need to
tell FoxPro to adjust that field’s position, based on the size of the stretch-
ing field. When you define the lower field, choose the Float as Band
Stretches option; FoxPro will then place the field one line below the last
line of the stretched character field. If you don’t select this option, the
field will be placed on the report as defined on the Layout view; if the
character field stretches, it will overwrite the bottom field, making a mess.
Chapter 9: Reporting on Multiple Database Systems 271
Fig. 9.18.
Customer Contact Report A Memo field;
Date: 81/27/98 h
Time: 11:12:22 Stretc
Vertically is
West Hill Florist ee
32981 Znd Ave So not selected.
Renton WA
Contact Follow-up
Number Date Date Comments
1 12/29/89 CHZ 61/85/89 Purchased large year-end order. Needs
17 records indexed
Fig. 9.19.
Customer Contact Report The same report,
: 81/27/98
> 11:13:04 with Stretch
Vertically
West Hill Florist
32981 Znd Ave So selected.
Renton WA
Contact Follow-up
Number Date Date Comments
1 12/29/83 CHZ 61/85/89 Purchased large year-end order. Needs
follow-up service by mid-Jan.
Call next week to get information on
service needs
17 records indexed
Figure 9.20 shows the report with the lower fields floating; figure 9.21
shows what can result if the field is fixed. The “Salesperson” literal field
and the SALESPERS database field end up in the middle of the CONT_RPT
memo field output.
ee
er
Fig. 9.20.
Fields floating Customer Contact Report
below a stretched Ee
> 11:17:48
field.
West Hill Florist
32981 Znd Ave So
Renton WA
Contact Follow-up
Number Date Date Comments
12/29/89 81/85/89 Purchased large year-end order. Needs
1 follow-up s:rvice by mid-Jan.
Call next week to get information on
service needs
Salesperson CHZ
17 records indexed
Renton WA
Contact Follow-up
Number Date Date Comments
12/29/89 81/85/89 Purchased large year-end order. Needs
1 Salesperson: rvice by mid-Jan.
Call next week to get information on
service needs
17 records indexed
Fig. 9.22.
Report: The Report
ES to Print « OK »
{ J To File
(+) Console On (¢ ) Console Off « Cancel >
OI Plain—If marked, FoxPro will not print the page number and
date at the head of each report page.
“I No Eject —Tells FoxPro when to go to the top of a new page. A
dialog opens in which you can make your choices.
J Summary —No lines in the Detail Band are printed; only totals and
subtotals.
274 Part Il: Intermediate FoxPro
The options correlate to those listed in the Database menu Report option.
Options are simply listed after the report name. For instance, this com-
mand line
PRINTJOB
FOR EACH RECORD IN THE CUSTOMER DATABASE PRINT
customer information
MOVE TO ORDER DATABASE FOR EACH RECORD OF
CURRENT CUSTOMER
PRINT
order information
ENDFOR
ENDPRINTJOB
This program could not be done in the Layout view, because it requires
looping through the CUSTOMER database and, for each record in that
database, looping through the appropriate records in the ORDER database.
FoxReport allows looping through only one database. So for a report like
this, a program using PRINTJOB and ENDPRINTJOB is perfect. The
PRINTJOB and ENDPRINTJOB commands relieve the programmer of
keeping track of the number of lines printed, when to go to a new page,
what the margins are, and so forth.
Tal a et BY ad ad LST OL RE DPE LTT Po dE EOE AY RAT AIOE STE TAT SEABED TSS aE LT OT aoePe aT PR TCT ET
CT ACTION (DFE TROD COMPLICA ETD ALR EE EE CEI DT LTDA DMTaRet aE PEAT PY OY PI IR LE EAL 2
SELECT 2
USE CONTACT INDEX CUST_NUM
SELECT aI
SET RELATION TO CUST_NUM INTO CONTACT
* write a title
* set the text alignment to be centered between the margins
_ALIGNMENT = "CENTER"
? "Customer Contact Report"
2? “Date: ", DIOCCDATE())
Chapter 9: Reporting on Multiple Database Systems DY.
RETURN
*: EOF: PRINTTST.PRG
The output for the report is generated by the ? command, which prints
the variables listed on the same line. Variables can be database fields, lit-
eral texts, or FoxPro expressions. You can use the TRANSFORM clause as
you would a PICTURE clause in a FoxReport.
-PLENGTH = 48
278 Part Il: Intermediate FoxPro
which sets the page length to 48 lines. The following assignments can be
made from the command line, before running the report program, or as
command lines in the program itself:
Q) _ALIGNMENT= <exprC> Used to determine how to justify
output on the report. You can assign LEFT, RIGHT, or CENTER
to _ALIGNMENT.
1 INDENT= <exprN> Sets an indent value. FoxPro will indent
lines this number of columns from the left margin.
LY _PSPACING = <exprN> Sets the line spacing for the report. You
can set line spacing from 1 to 3 lines.
which tell FoxPro to route a copy of all screen output to the file
filename. Remember, though, to stop output to the ALTERNATE file with
the command
Chapter Summary
Report writing is never the high point of database design and develop-
ment. Yet this phase of your system can really show off your design skills
and FoxPro expertise. Using FoxReport and the Layout window gives you
a quick and easy way to create most of the reports you will ever need for
your databases.
For those times when more complexity is needed, FoxPro gives you its
programming capability, tied to the PRINTJOB and ENDPRINTJOB com-
mands, which relieve you of the task of programming for page breaks,
indents, right and left margins and the other details of report writing. You
will find both these approaches to FoxPro reports valuable and rewarding.
280 Part II: Intermediate FoxPro
‘Part Ill
Advanced
FoxPro
Includes
Building an
Application
aX s you become more proficient at using FoxPro, you will find that you
grow tired of going through the process of opening database files
with the File Open menu, attaching index files with the View Setup dialog,
choosing Format files and report files, and so on. Eventually, you will
think about using the power of FoxPro to create a_ ready-to-run
application.
You also may find that others want to use your FoxPro systems. For these
users who are unfamiliar with the intricacies of FoxPro, you need to pro-
vide a turn-key system—one that users can turn on and run without need-
ing to know the details of how FoxPro works. For these users you need to
develop a FoxPro application system.
283
284 Part III: Advanced FoxPro
Creating an Application
If you need to create an application that works with only one database
file, you can use FoxView and the FoxPro templates that function in Fox-
View. To create a single-file application, follow these steps:
a: Press F10 to move to FoxView’s Form view, where you can create
the screen form. Chapter 2 explains how to create and edit a
screen form. You can see a completed screen form for the
CUSTOMER database in figure QS3.2.
Quick Start 3: Building an Application 285
Fig. QS3.2.
The complete
FoxView screen
Customer Number form for the
Sa CUSTOMER
database.
Name
Address
City
Phone Contact
Disk Gen
Address
City
Phone Contact
(§:\FOXPRO\BOOK\CUSTOMER.FU
Enter FILENAME of FoxVieu Table to save
286 Part II]: Advanced FoxPro
If you want to save the table with the name shown, press Enter. If
you want to give this table a new name, enter the name here.
This allows you to save more than one form design for each
database. For now, press Enter to save the table.
Using the arrow keys, move to the Gen menu pad. The pull-down
menu should have highlighted the menu bar Select From Template
List. If the pull-down menu does not highlight the correct menu
bar, use the up- and down-arrow keys to highlight the Select From
Template List bar and press Enter.
aesemmmcmmmes !E'PLATES
ADVANCED. | FoxPro Advanced Application
APPS1 File-Maintenance Application
Fig. QS3 a: FORM1 Format File Generator
Selecting FoxPro FORN2 Driver with FORM/SAYS/GETS/STOR/REPL procedure file
Advanced FORMALL Multiple File Format Generator
5 FORMJZ Format File Generator
Application from REPO1 Report Format File Generator
the template list. SIMPLE Simple Database Application
at the bottom of the screen and await a file name from you. This
is the name of the PRG program file that the Advanced
Application Template will generate for you. Enter any valid MS-
DOS filename, but don’t add an extension; FoxView automatically
adds the PRG extension that identifies the generated file as a
program file. Figure QS3.5 shows this screen, with the file name
CUST entered.
Quick Start 3: Building an Application 287
Fig. QS3.5.
Entering a name
for FoxView to
use in generating
an application
program.
8. FoxView asks for another name. FoxView is asking for the name of
the FoxPro format file that the template will generate. You can
use the same name as the application for consistency, or you can
give any other valid MS-DOS filename. As with the PRG filename,
don’t add an extension; FoxView will automatically add the FMT
extension FoxPro needs to identify the file as a format file.
9. Now you can sit back and watch the Advanced Application
Template generate a host of FoxPro program lines on the screen.
When the Advanced Application Template is done, press Enter to
return to FoxView. You will also need, in this quick start, a
FoxPro FMT format file that has the same screen design. Choose
Select from the template list again, then choose FORM1, Format
File Generator, from the template list, and give this file the name
CUSTOMER. Again, FoxView appends the necessary FMT
extension.
10. Press Enter, and then move to the Disk menu pad. From there,
pressing Q for Quit will allow you to exit FoxView, after
answering the
question with a Yes. You may also be asked if you want to save
the screen design.
11. You can now return to FoxPro (which will happen automatically
if you invoked FoxView from FoxPro). In FoxPro, you can run
your application by choosing Do from the Program menu and
selecting CUST.PRG from the File Picker list of the Do dialog.
ee es eee ne Pe ee ee a ee ee ee
Fig. QS3.6. »% —-- Removes all non-alpha characters from a string replacing them
* --- with a space
The CUST.PRG E
lines with a bug sf
FUNCTION alphaonly
OM them; change PARAMETER msource
the mx to mx2. mlen = LENCmsource>
mtarget = ’’
FOR mx = 1 TO mlen
mtarget = mtarget + IIFCISALPHACSUBSTRCmsource,
mx, 1)», SUBSTRCmsource, mx,
ENDFOR
RETURN mtarget
Now change the mx on this line and the following line to mx2 (see fig.
QS3.7). Save the file with the File Save option and run this simple applica-
tion by choosing Do from the Program menu. When the Do dialog appears
on-screen, choose CUST.PRG and try your application.
The Advanced Application Template you called from FoxView has created
a mini-FoxPro system built around the screen you created. The system has
four menu pads that provide the basic database functions necessary for
you or a user to enter data into the database, inquire or search the
database, and create and use reports. Use these menus just as you would
use FoxPro menus.
Quick Start 3: Building an Application 89
As you can see, this method gives you a quick-and-easy way to create sim-
ple applications that you or others can use. The users need not be both-
ered with the many details of FoxPro. Note, though, that the Report and
Label options of the Utility menu call up the FoxPro Report and Label
dialogs. If you want to create a true FoxPro “shell” for nonexpert users,
you will need to create report and label programs for them. These would
then appear in the dialog when the user requests a report or label.
ae Menu Pads
Fig. QS3.8. Popup —~>
A menu and pop-
an Popup Bars
up menu, with
their elements
defined.
; CLEAR
Fig. QS3.11. HIDE WINDOWS ALL
MENU_1.PRG
With ihe ON DEFINE MENU main
SELECTION PAD DEFINE PAD file OF main PROMPT "'\<System" AT 88,
: DEFINE PAD Goto OF PROMPT "'\<GoTo" AT 28,
command lines DEFINE PAD Record OF main PROMPT "\<Record" AT @8,
added. DEFINE PAD Util OF PROMPT "\<Utility" AT 88,
DEFINE PAD quit OF PROMPT "'\<Quit" AT 88,
6. Enter a line that will cause the menu to be displayed and put into
action, this is the ACTIVATE menu_name command. At the end of
the program, enter the line
7. Enter the PROCEDURE msg subroutine. This will write out the
message sent to the menu, allowing you to see that the menu is
working as it should.
Quick Start 3: Building an Application 293
*: MENU_1.PRG
*: A test menu application for Quick Start 3
CLEAR
HIDE WINDOWS ALL
DEFINE MENU main
PROCEDURE msg
PARAMETER mchoice
@ 24, O CLEAR
@ 24, O SAY "Chose "* + mchoice
RETURN
Now you can test this menu skeleton. Save the file again with the File
Save option. Resize the MAIN_1.PRG window to a smaller part of the
screen (make sure that the window doesn’t cover up line 24, where the
PROCEDURE msg will write its message. Choose DO MENU_1.PRG
from the Program menu or DO from the Program menu and select
MENU_1.PRG from the File Picker list in the DO dialog.
FoxPro will replace the FoxPro menu with the one defined in the
MENU_1 program. You can select a pad as you would with FoxPro, using a
mouse or the keyboard; your choice will be shown on line 24 by the
PROCEDURE msg routine. Figure QS3.12 shows the screen, with the
MENU_1.PRG window on-screen, your menu at the top, and a message
that results from selecting the File pad. To stop the program, press Esc.
If you get an error message, or your program prints out the wrong mes-
sage for your choice, review the program carefully to find the error. This
part of the program must be correct before you continue with your appli-
cation development process. The next step is to add pop-up menus to
each of the pads.
294 Part II]: Advanced FoxPro
Fig. QS3.12
The MENU_1.PRG
application in
operation.
Chose Record
2. Define each bar of the pop-up menu, using the DEFINE BAR
command. Each bar has a number that defines it. The pop-up
menu will be constructed with bar number 1 on the first line, bar
number 2 on the second line, and so forth. For each bar, you also
must define the PROMPT, which is the character string that will
appear as the menu bar. Note the difference between the bar’s
number and PROMPT; the number will be used by your program
for various purposes and will never be known to the user. The
PROMPT is what the user sees on the pop-up menu. Figure
QS3.14 presents the program with the pop-up menu for the
Record pad included.
2
?. As with the menu, you must program a way to determine what
the user has chosen, process the user’s choice, and take some
action on the choice This is done with an ON SELECTION
POPLP command, which activates a PROCEDURE to take
appropriate action; the ON SELECTION POPUP uses the DO
command to invoke the PROCEDURE and passes the number of
the bar to the PROCEDURE, Figure QS3.15 displays the
MAIN_L.PRG with the ON SELECTION POPUP command added,
using a DO clause to invoke a procedure
oe To process the choice made by the user trom the pop-up menu,
you need a small procedure, which recognizes which pop-up
menu was selected and takes appropriate action, You will have to
have such a procedure for each pop-up menu detined, so they
must be named uniquely. Figure QS3.16 shows the PROCEDURE
goto_prc, which processes the choices if the user chooses a bar in
the Goto pop-up menu. At this point, the actions are only to
display the selected bar for testing purposes.
You should now follow the above steps for each of the menu
pads, defining the bars, specitving the action to take with an ON
SELECTION... command, and writing a simple procedure to
process the action.
Quick Start 3: Building an Application 297
PROCEDURE goto_proc
PARAMETER mb °
eg Fig. QS3.16.
DO CASE The PROCEDURE
CASE mbar = 1 , y
DO sg WITH “Next” goto-pre, which
CASE mbar = 2 processes choices
DO msg WITH "Previous"
made in the Goto
CASE mbar = 3
DO wsg WITH "Top" pop-up menu.
CASE mbar = 4
DO msg WITH "Bottom"
ENDCASE
=)
5. Because now you want the Main menu to show a pop-up menu
when a pad is selected instead of executing the msg procedure,
change the ON SELECTION PAD commands to activate the
appropriate pop-up menu when a pad is selected. The format for
this command is as follows:
Figure QS3.17 shows the ON PAD commands, which take the place of
the ON SELECTION PAD DO msg WITH commands in MENU_1.PRG.
Your new version of the application program, pop-up menus, and pro-
cesses to handle the selections should look like the following program:
*: MENU_1.PRG
*: A test menu application for Quick Start 3
CLEAR
HIDE WINDOWS ALL
CASE mbar = 2
DO msg WITH a ‘Open’ Ly
ENDCASE
RETURN
PROCEDURE goto_proc
PARAMETER mbar
DO CASE
CASE mbar = 1
DO msg WITH "Next"
CASE mbar = 2
DO msg WITH ‘'Previous"
CASE mbar = 3
DO msg WITH ‘ “Topas
CASE mbar = 4
DO msg WITH "Bottom"
ENDCASE
PROCEDURE rec_proc
PARAMETER mbar
DO CASE
CASE mbar = 1
"Append"
DO msg WITH
CASE mbar = 2
DO msg WITH "Browse"
CASE mbar = 3
DO msg WITH MEGiites
CASE mbar = 4
DO msg WITH ‘Delete”
een
CASE mbar = 5
DO msg WITH "Recall"
ENDCASE
RETURN
PROCEDURE utl_proc
PARAMETER mbar
DO CASE
CASE mbar = 1
DO msg WITH ‘’Report"
CASE mbar = 2
DO msg WITH "Label"
ENDCASE
RETURN
PROCEDURE msg
PARAMETER mchoice
@ 24, O CLEAR
@ 24, O SAY "'Chose "* + mchoice
RETURN
You now can save and test the menu again. Figure QS3.18 shows the
menu in action once more, now with the Record pop-up menu activated,
and it shows the on-screen results of choosing a bar from the Record pop-
up menu
Edit
Add
Fig. QS3.18. Brouse
MENU_1,.PRG in Delete
action with pop-
Customer Number
up menus. a
City oan
Phone iliyea:s eee Contact [eRe
Database: CUSTOMER.
DBF
Quick Start 34: Building an Application 401
fest the menu program to see that all menu pads and pop-up menu
choices work correctly. Once you know they do, it’s time to add the pro-
gram lines that will cause FoxPro to respond to the choices.
Add the routine to display the records as you work with them. To
do this, open another text editing window with the program
CUSTOMER.PRG that you created in FoxView. Copy that program
into the MENU_1.PRG just after the DO WHILE loop statement.
=) In the case of the Report and Label choices in the Utility pop-up
menu, you need to bring up the Report or Label dialog to allow
the user to choose which Report or Label format he wants to
print. To do this, for the Report choice, you should enter REPORT
and for the Label option, you should enter LABEL.
7. Last, you need a PROCEDURE that will put the form you created
in FoxView onto the screen. To do this, add the following line:
When you have finished this, your application is complete and ready to
test. The entire MENU_1.PRG file is as follows:
*: MENU_1.PRG
*: A test menu application for Quick Start 3
CLEAR
HIDE WINDOWS ALL
PROCEDURE rec_proc
PROCEDURE file_proc
PARAMETER mbar
DO CASE
CASE mbar = 1
DO msg WITH "'Help"
CASE mbar = 2
DO msg WITH "Open"
ENDCASE
RETURN
Quick Start 3: Building an Application 40 5
PROCEDURE goto_proc
PARAMETER mbar
DO CASE
CASE mbar = 1
DO msg WITH ''Next"®
CASE mbar = 2
DO msg WITH "Previous"
CASE mbar = 3
DO msg WITH "Top"
CASE mbar = 4
DO msg WITH "Bottom"
ENDCASE
PROCEDURE rec_proc
PARAMETER mbar
DO CASE
CASE mbar = 1
DO msg WITH 'Append''
CASE mbar = 2
DO msg WITH "Browse"
CASE mbar = 3
DO msg WITH “"Edit"
CASE mbar = 4
DO msg WITH "Delete"
CASE mbar = 5
DO msg WITH "“'Recall"
ENDCASE
RETURN
PROCEDURE utl_proc
PARAMETER mbar
DO CASE
CASE mbar = 1
DO msg WITH "'Report"
CASE mbar = 2
DO msg WITH "Label"
ENDCASE
RETURN
PROCEDURE msg
PARAMETER mchoice
@ 24, O CLEAR
@ 24, 0 SAY "Chose " + mchoice
RETURN
306 Part III: Advanced FoxPro
Now you can test your program. Open the Program menu. If your pro-
gram is in the active window, the last entry in the Program pop-up menu
will be DO MENU_1.PRG (see fig. QS3.21), and you can select the entry
to run your program.
Do MENU_1.PRG “O
If the program is not in the active window, you select Do. The Do dialog
opens, and you can select your program from the scrollable list (see fig.
QS3.22 ).
Fis, OS5.22.
The Do Program
File dialog, with Do Program File:
a scrollable list
of PRG program
MENU_1.
MENU_MST.
PRG
ORDER. PRG
PRG we Le_]
files ORD_ENTR. PRG
PRINTTST. PRG Directory BOOK
Q. PRG
REPORT1. FXP
SIM. PRG « Do
SMP. PRG
< Cancel >
C ] All Files
Quick Start 3: Building an Application 407
: MENU_1. PRG
*: A test menu application for Quick Start 3
CLEAR Fig. QS3.23.
HIDE WINDOWS ALL An error message.
x--- define the main menu
DEFINE MENU main
x--- define t
DEFINE POPUP
DEFINE BAR 1 Unrecognized phrase/”keyword in command.
ON SELECTION
x--- define t]} « Cancel » < Suspend > < Ignore >
DEFINE POPUP
You may find that a program compiles (which means that FoxPro found
nothing syntactically wrong) yet still does not run as you want the pro-
gram to run. This means that you have made an error of program logic.
The best way to find errors is to use the Trace and Debug windows.
FoxPro will start your program, but execute only the first line.
Open the Trace window from the Window pop-up menu and
move and resize the window so that it will not block your menus.
Figure QS3.24 shows the Trace window opened.
Fig. QS3.24.
The Trace
window, with *--- tie popups to main menu pads
ON PAD file OF main ACTIVATE POPUP file _pop
MENU_1.PRG ON PAD goto OF main ACTIVATE POPUP goto_pop
executing in it. ON PAD record OF main ACTIVATE POPUP rec_pop
ON PAD Util OF main ACTIVATE POPUP util_pop
ON PAD quit OF main RETURN
bh Click the Resume box of the Trace window to execute the next
line of your program. Continue to execute lines one at a time and
watch FoxPro place your menu on the screen. At times, you may
find that your program causes FoxPro to make a window active
on top of the Trace window; in this case, select Trace from the
Window menu or press Ctrl-F1 to cycle through windows until
the Trace window returns to the top.
You also will find times when you want to leap through large
hunks of the program rather than going line-by-line. You can set a
“breakpoint,” that is, a line at which execution will stop, in the
Trace window. Scroll to the point at which you want FoxPro to
suspend and click on the line with the mouse or press Enter from
the keyboard. A diamond will appear to the left of the line,
indicating a breakpoint (see fig. QS3.25).
Now, from the Program menu, select Step, which will SET STEP
OFF. Choose Resume, either from the Program window or the
Trace window. FoxPro will execute your program to the
breakpoint and stop. Select Step again to SET STEP ON and use
the Trace window to execute the rest of the program one line at
a time, or until you turn the Step off.
Quick Start 3: Building an Application 409
Fig. QS3.25.
The Trace
*--- tie popups to main menu pads window, with a
ON PAD file OF main ACTIVATE POPUP file pop breakpoint set to
ON PAD goto OF main ACTIVATE POPUP goto_pop
ON PAD record OF main ACTIVATE POPUP rec_pop stop program
ON PAD Util OF main ACTIVATE POPUP util_pop execution.
ON PAD quit OF main RETURN
CASE mbar = 3
DO msg WITH Top"
CASE mbar = 4 Fig. QS3.26.
DO msg WITH "Botton" The Debug
ENDCASE A
window, showing
PROCEDURE rec_proc variables and
PARAMETER
50 CASE mbar theirrp values as 5
<Cancel> <Resune> the program
executes.
310 Part II]: Advanced FoxPro
The application you have just created is quite simple. This application
contains no error-checking routines or ways to change the original Fox-
Pro environment (colors, window sizes, SET ON/OFF command settings)
and return to that environment when the application completes. If you
want to see some of these routines, print out the CUST.PRG created with
the Advanced Application Template in FoxView. This program (which is
actually created by another program!) contains many of these routines,
and can be a catalyst for your own creativity in implementing many new
ideas in your application.
Summary
This has been a fairly simple example of an application program. Yet the
example fully illustrates the basic processes of creating an application.
Menus drive the application, just as they do in FoxPro itself. From those
menus, you offer the user a series of options from which he selects the
one he wants.
In this quick start, you have learned the basics of creating an application
that you or others can use. You have created menus and the associated
pop-up menus, and seen how to tie FoxPro commands or additional pro-
grams to the menus. Complex application programs can have multiple
menus and many pop-up menus with hundreds of selections overall, but
they are created with the same processes you used in this quick start.
Creating
Applications
with FoxPro
=a t some point in your FoxPro education, you will need to go beyond
= FoxPro’s interface. You may find that other people need to use the
database system you have developed, with its input and inquiry screens,
and reports and labels, but they don’t want to learn the intricacies of Fox-
Pro. Or, you may find that you don’t want to use FoxPro’s interface all the
time. In these cases, you can build an application to run your system.
An application is like a shell that separates the user from FoxPro. An appli-
cation limits the actions of the user to just those things needed, thus
making the system easier to use and understand. FoxPro applications are
usually, like FoxPro itself, driven by menus and pop-up menus, from
which the user makes choices.
In this chapter, you learn about the tools used to create complete applica-
tion programs in FoxPro. These include the menu tools, which define, cre-
ate, and use FoxPro-type menus. Another set of tools implements pop-up
menus, which usually are associated with a menu. When the menu item is
selected by the user, the pop-up appears with choices about that menu
item. Pop-up menus also can be independent of a menu, appearing when-
ever an application needs to present a list of choices to the user. You
learn how to create a complete menu and pop-up system to run your
application.
You also learn how to create a help system specific to your application. A
help system is essential to those users not familiar with FoxPro or just
learning the application.
311
Ic NN st Be sn ta
412 Part II]: Advanced FoxPro
Finally, you learn how to use Windows and different color schemes to
give your application system pizzazz. Well-designed windows with colors
make an application system easier to use and understand.
Designing an Application
The first step in designing a new application is to identify the necessary
functions you want the application to perform. Once the functions have
been identified, group them into logical units. Just as FoxPro arranges
actions into groups (System, File, Edit, Database, Record, Program, and
Window) and then places the actions under menus with these group
names, you need to group the actions selected for your application and
arrange them under menu names.
As with system design, your first question should be, “What information
must come out of this system?” Once you have identified the application’s
outputs—reports and query screens—you can define the routines and
options that are necessary to get the required information into the system,
and then get the information out.
Main Menu
Pads: System Customer Contact
Fig. 10.2.
Sub_menu A more complex
application
Fore system, with
By Customr submenus.
By Date
By Salesp
Report
popup
popup Next By Number
Help Previous By Name
Database
Quit
Another way is the bottom-up method, in which the lowest level pro-
grams and functions are written and tested, then the next higher level
—which uses the low-level functions—and so on, until the highest level
menu can be written and all of the applications on the menu are ready to
run.
Yet another way is the inside-out approach. The developer writes and
tests the hardest parts of the application to make sure that they can be
accomplished. Then the simpler ones can be coded and tested along with
necessary menus, utilities, and pop-up menus.
You may find a combination of all three the best approach. If you know a
part of your application—say, a particular report or query—will be diffi-
cult, write that portion first to make sure that it can be accomplished with
your database design. If the report or query cannot be done, you should
rethink the design of your databases and application before the applica-
tion is 95 percent finished and you have to change much of it. Other than
that case, [ prefer creating the menus and pop-up menus first, because
then you can prototype the application.
First, though, you must create the menus and pop-up menus for your
application.
Fig. 10.3.
A FoxPro menu,
with its elements
labeled.
You must include the pad_name, the menu_name, and the PROMPT
when defining a menu pad. If you leave out the optional AT row and col-
umn location, FoxPro will put the first pad at the left edge of row zero
(the top row) of the screen. (The second pad will be to its right, and so
on). The following lines define pads for the menu named TOP_ MENU:
create the two pads Report and Record. Press R to activate the Report
pad, and press C to activate the Record pad. When this menu is displayed,
the hot characters will be in a different color than the rest of the menu
characters to indicate their special nature.
The first selection activates a pop-up menu defined for this pad, the sec-
ond invokes a FoxPro procedure or PRG program file, and the third issues
the FoxPro command RETURN.
FoxPro constructs the menu from the DEFINE MENU and DEFINE PADS
commands you have given it, places the menu on-screen, and processes
the menu. Until the menu is deactivated, the menu controls FoxPro pro-
cessing, branching out through pop-up menus and PRG program files or
procedures. Unless some part of the programs called by the menu issue a
FoxPro QUIT command, control eventually returns to this menu. Only
when the user presses Esc or takes an exit path provided by the program,
does the menu relinquish control.
418 Part Ill: Advanced FoxPro
DEACTIVATE MENU
Because only one menu can be active at a time, nO Menu name is needed
Note | Even though only one menu can be active at a time, more than
one menu can be on-screen at a time. One menu can activate
another menu, which can activate a third menu, all of which
are on-screen at the same time (assuming none overlap each
other). But only the most recently activated menu is active;
the other menus are “out of the action,” waiting until the
menus they activated are deactivated.
Your application programs can determine what choice a user makes from
the pop-up menu by using one of two functions. PROMPT() returns the
actual prompt string of the user’s choice; BAR() returns the number of the
pop-up bar assigned in the DEFINE BAR statement.
provide more options. The basic format of the DEFINE POPUP command
is as follows:
The pop-up menu_name is a name assigned to this pop-up menu, and the
row, column defines where the upper left corner will be on-screen. Also
like the DEFINE MENU command, the DEFINE POPUP command _ has
options to provide a message on the line 24 of the screen as follows:
You also can specify the color to assign the pop-up menu with the
optional COLOR clause, which can designate the standard and enhanced
colors, or select a predefined color scheme.
Once the pop-up menu is defined, you must define which choices will be
presented to the user via the pop-up menus. Pop-up menus can contain a
list of options, which you define with the DEFINE BAR command, or you
can use several other interesting options: PROMPT FIELD, PROMPT FILES,
and PROMPT STRUCTURE.
When you use this DEFINE POPUP command while the CUSTOMER
database is open and active, it displays the pop-up menu you see in figure
10.4. Each field in the pop-up menu is the value in the field CUST. NAME
in one database record. The user chooses a value, and this value is
returned by the function PROMPT().
ot ee Se ee eee
Fig. 10.4.
A pop-up menu Northwest Microsyst
created with the SCIL
S & C Autos
PROMPT FIELD Comar
command. Cosars Continent
Northend Music
Bill’s Plumbing
Studio 11 Art
OshKosh Cow. Company
Metropolitan Corp
Hess Aviation Inven
T. Moore & Associat
v.
The skeleton is an MS-DOS file name, with or without the * and ? wild
card characters. If you wanted to present a list of PRG program files in a
pop-up menu, you could use the following command:
DEFINE POPUP /file- pop PROMPT FILES LIKE *.PRG FROM 10,10
TO 30,20
This command would create the pop-up menu shown in figure 10.5. As
with all pop-up menus, the user’s choice will be returned as a string by
the PROMPT() function.
a : Fig. 10.5.
| C: FOXPRO\BOOK\ A pop-up menu
a created with the
ADD_EDIT. PRG. PROMPT FILES
ADU. PRG LIKE command.
CHAP1O.PRG
CHAP11-1. PRG
CHAP11. PRG
CHK_CUST. PRG
CUST. PRG
DRIVER. PRG
ERROR_MS. ne
Figure 10.6 shows an example of this type of pop-up menu. The example
was created with the following command:
Fig. 10.6.
A pop-up menu
CUST_NAME created with the
PROMPT
STRUCTURE
command.
LAST_PUR
LAST_AMT
PREFERD
422 Part III: Advanced FoxPro
As with menus, several special facilities are built into the PROMPT charac-
ter expression. You can define a character of the PROMPT expression as a
hot character. A hot character enables the user to press the key corre-
sponding to a bar’s hot character to select that bar. To define a hot char-
acter, place the two characters \< before the hot character.
If you want to divide the pop-up menu options into subsections with a
line between the sections, use the PROMPT option. For example, consider
the following DEFINE BAR commands:
These commands create the pop-up menu shown in figure 10.7. Note that
BAR 4 creates a line separating Quit from the other pop-up menu choices.
Once you have defined the pop-up menu and all its options, you must tell
FoxPro what action to take when a choice is made from this pop-up
menu.
>
Fig. 10.7.
A pop-up menu
created with
DEFINE BAR
commands.
Note that the action to be taken is actually any valid FoxPro command.
You could put a FoxPro command there, but then that command would
be executed no matter what choice was taken from the pop-up menu,
which defeats the idea of giving the user a choice. The best way to pro-
cess the choice is to use a PROCEDURE subroutine, passing to the sub-
routine the number of the bar that the user selected.
Several FoxPro functions return information that your application can use
to decide what action to take. These functions are as follows:
4 POPUP() returns the name of the pop-up menu from which the
user made a choice.
J BAR() returns the bar number, from the DEFINE BAR statement,
that the user chose.
Each pop-up menu should have a procedure file to process choices made
from that pop-up menu. You can pass the choice made as a parameter to
the procedure file, for example,
This statement tells your application that when a user makes a choice
from the pop-up menu named SYS_POP, FoxPro should call up the PRO-
CEDURE subroutine named SYS_PROC and pass to it, as a parameter, the
bar number that was chosen.
The PROCEDURE should then take action based on which bar was cho-
sen. In pseudo-English, the following is what such a procedure would look
like:
PROCEDURE SYS_PROC
PARAMETER BAR_ NUM
DO CASE
CASE BAR_NUM = 1
statements to execute for choice of bar 1
CASE BAR_NUM = 2
statements to execute for choice of bar 2
other case statements for other choices
ENDCASE
RETURN
You also could pass, as a parameter, the actual string prompt. In fact, if
you have used the PROMPT FIELDS, PROMPT FILES, or PROMPT STRUC-
TURE options of the DEFINE BAR command, you will have to pass the
prompt string, because no bar number is associated with choosing an
option from those lists. In that case, the PROCEDURE can look like the
following:
Whether you have specified pop-up menu options individually or used the
PROMPT FIELDS, FILES, or STRUCTURE options, you must create a PRO-
CEDURE subroutine to process the choice.
Define each pad of the menu, using the DEFINE PAD command.
cSFor each pad in the menu, define what action should be taken
when the pad is chosen, using the ON SELECTION PAD
command.
Chapter 10: Creating Applications with FoxPro 42 5
See? It’s not so hard. The result of working with menus and pop-up menus
is a polished, easy-to-use application program. Both you and your users
will appreciate your efforts to use menus and pop-up menus to run your
application program.
Help systems in FoxPro, even FoxPro’s own help system, are standard
FoxPro databases. A help database has two fields. One field is a character
field named TOPICS that has a length of 16. The other field is a memo
field named HELP. The TOPICS field has a string that describes a help
topic. The memo field holds the textual information that actually provides
the help. When the user presses the Fl key to get help, FoxPro searches
the database that is currently defined as the help database and places the
TOPICS into a window. From the window, the user can select a topic and
FoxPro will place the help information from the memo field for that topic
in the same window.
To use a custom help system, you only have to create a new help
database, with at least the two fields TOPICS and HELP, and tell FoxPro to
use that database for help in your application. Then, when the user
presses the F1 Help key, FoxPro will use the custom help database rather
than the standard FoxPro one.
326 Part II]; Advanced FoxPro
For each record, place the help text in the memo field. Help text can be
any length.
In this line, Help_file.name is the name of the help file you created.
Your application can have as many help files as you want, with the appli-
cation switching from one help file to another as necessary. This feature
can simplify the help system for anyone using your application, because
you can limit the help topics to the area of the application in which the
user is working. For instance, if your application has major subsections for
the customer, invoice, and inventory databases, you can create a help file
for each and use the SET HELP TO command to use the appropriate help
file in each database. Then, when a user asks for help in the inventory
section, he doesn’t have to wade through customer and invoice help
topics.
If you want to re-establish the regular FoxPro help system, put the com-
mand SET HELP TO FOXHELP in your application.
when the users request help with the Fl key, FoxPro will present a help
screen appropriate to what the user is doing at the time. For instance, if
the user is entering invoice information and asks for help, the application
can present the help screens with the topic of Invoice.
The steps for creating a context-sensitive help system are the same as they
are for creating a regular help system. You create the help database and
include topics and detail appropriate to specific parts of the application.
Then, in your application program, when you want to provide context-
sensitive help, you use the following command:
When the application program starts the process used to enter invoices,
you should include the following commands:
With these commands in place, when the user presses the F1 help key in
this part of the application, FoxPro will display help information associ-
ated with entering invoices. FoxPro uses the information from the record
you created in the help database (as shown in fig. 10.9) without requiring
the user to choose from the list of topics.
—- Entering Invoices —
When entering invoices, you must
fill in the fields which are seen
Fig. 10.9. in yellow, Other fields are
A context- optional.
oice Entry
sensitive help If you do not know the customer
screen. number, check with Accounts Payable @ Salesperson:
(ext. 443) to ensure that you enter
the correct number
Once the help screen is activated, the user can return to the Topics
screen and choose other help topics of interest.
Help systems are essential parts of your applications. Users have rightfully
come to expect help systems. Because FoxPro makes creating and imple-
menting a sophisticated help system easy, you have no excuse for failing
to provide one.
The advantage of using a window over writing to the screen is that a win-
dow can be placed on-screen, do its job, and then disappear, leaving all
information under the window exactly as it appeared before the window
was activated. This makes windows perfect for temporary jobs, such as
alerts and error messages, or asking questions of the user.
Defining a Window
Just as you did when you created menus and pop-up menus, you first
DEFINE a window to FoxPro. With the definition command, you tell Fox-
Pro to build the window in memory, with the various options you specify.
Only when you issue an ACTIVATE WINDOW command does FoxPro put
the window on-screen.
1 DOUBLE
) PANEL
“) NONE
QO) SYSTEM
(4) BORDER
_ STRING
This last option defines what type of border the window will have. FoxPro
defaults to a single line around the window. DOUBLE causes the border
line to be a double line. PANEL creates a wide border. NONE specifies no
border, and SYSTEM says to use whatever the default for the FoxPro sys-
tem is.
You also can define your own border string by placing the characters that
will be used for the vertical and horizontal lines and each of the corners
430 Part III: Advanced FoxPro
in a series. The order of this border string is top, bottom, left, right, and
then top left corner, top right corner, bottom left corner, and bottom
right corner. Each character must be enclosed in quotation marks or
expressed as a CHR().
“¥ COLOR. You can specify the color of the window. For a more
detailed explanation of how to set colors, see the following
section.
When you want to remove a window from the screen, use either the
DEACTIVATE WINDOW command or the HIDE WINDOW command.
Either one removes the named window from the screen. DEACTIVATE
WINDOW and HIDE WINDOW are different from each other. HIDE WIN-
DOW removes the window from the screen, but doesn’t change the win-
dow’s active status. If you have hidden the active window, output will still
go to the window even though you cannot see the output. If you want to
make the screen active again, you can use the SHOW WINDOW command
to bring the screen back to the screen. The window will appear with all of
the output that went to the window while the window was hidden.
The following program opens a window and writes to it, opens a second
window and writes to the second window, hides the second window
while continuing to write to the second window, shows the second win-
dow with the output taken while the window was hidden, and then
returns to the first window to output some more. Although this is not
exactly a program you will want to use in your application line-for-line,
the program does give a good demonstration of FoxPro’s windowing capa-
bilities, and provides a base for your own experimentation.
CLEAR
DEFINE WINDOW one FROM 1,0 TO 5, 60 TITLE ‘Window One!
DEFINE WINDOW two FROM 7,5 TO 12, 65 TITLE 'Window Two!
4342 Part Ill: Advanced FoxPro
Using Colors
Just as windows provide your application with a polished look, colors can
provide oomph and emphasis to a system. Prudent use of colors in a Fox-
Pro application can make the difference between a good system and a
great system.
Remember that your application can be used on computers without a
color monitor. Therefore, your application should determine what kind of
monitor is present, and adjust the colors accordingly. This is, as you have
come to expect with FoxPro, not difficult to do. Before explaining this
procedure, this section will include a discussion of how to define different
colors to FoxPro for use in your application.
A quick summary of FoxPro’s color capabilities may be: You can specify a
color; 2 colors make a Color Pair; 1 to 10 Color Pairs make a Color Pair
List; 10 Color Pairs make a color scheme; and 24 color schemes make a
Color Set. Clear as mud, right? Before discussing how to set and change
colors, here are definitions of the terms.
Chapter 10: Creating Applications with FoxPro 4343
Using a Color
FoxPro can put eight different colors on-screen. These eight are repre-
sented in FoxPro by codes. The colors and their codes are as follows:
Color Code
Black N
Green G
Blank xX
Magenta RB
Blue B
Red R
Brown GR
White Ww
Cyan BG
Yellow GR+
On monochrome monitors, you can specify only four colors: white (W),
black (N), underlined (U), and inverse video (1).
All objects have both a standard mode and an enhanced mode—with col-
ors for each mode. Standard mode is when the object is not selected. For
example, a GET field when the cursor is not in the field will appear in
standard mode. When the cursor moves into a GET field, the field assumes
the colors set for its enhanced mode.
Color pairs are used to change the colors of one object on the screen. The
format of the SET COLOR command is as follows:
SET COLOR OF object TO <standard_color_pair>,
<enhanced_color_pair>
You also use color paits with the SET COLOR TO command. With this
command you alter only the colors of user-defined menus and windows.
Following is the format for this command:
If you are working with a COMPAQ monochrome monitor, you may find
certain standard FoxPro color schemes to be difficult to use, particularly
in inverse video fields. I suggest that you try the standard FoxPro color
sets COMPQ_COLO and COMPQ_MONO. If you still have problems,
experimenting with color sets in the Color option of the Window menu
may help.
Controls are the items that you can select in a window. An example is the
Topic Preceding Next items at the bottom of the Help window. If the con-
trol can be chosen the control is enabled; if the control cannot be chosen
(for example, Previous when you’re at the top of the help list and there is
no previous record), the control is disabled.
how to color the screen when your application is creating and using win-
dows. Another color scheme tells FoxPro how to color objects in the
menu (this one refers to only four objects) and another for dialogs.
If you have come up with a complete set of color schemes, or made mod-
ifications to only one or two, you can save all those schemes as a color
set. Do this by choosing Save. You will see the Color Set dialog, waiting
for a name for this color set. Give the new color set a name and select
Save /.
Now, when your application starts, you can load the customized color set
by issuing the SET COLOR SET TO command. The following is the format
for the command:
Color_set_name is the name you assigned your custom color. That set
will be loaded and your application will look just as you planned.
? SYS(2006)
returns the string MGA/MONOCHROME; if the application is running on a VGA
color system, the command will return VGA/COLOR.
Using this in a program, you can detect the type of monitor and load an
appropriate color set using the following routine:
MON_TYPE = SYS(2006)
IF “color” $ MON_TYPE
SET COLOR SET TO "COLOR’
ELSE
SET COLOR SET TO "MONOCHROME”
ENDIF
By including this small routine, you can ensure that the correct color set
will be loaded. The other alternative is to maintain two (or more!) sepa-
rate versions of your application, one for each type of monitor that the
application can run on.
Chapter Summary
Application programming in FoxPro is tremendously rewarding, though at
times difficult. Your application can be quite simple, merely allowing
others to use your database system without learning FoxPro commands
and all of the FoxPro options. Or your application can become quite
complex.
a
yeH
338 Part Il]: Advanced FoxPro
The day will come when you realize that FoxPro “out of the box” has
some limitations. Compared to its competitors, FoxPro’s limitations are
less limiting: you can do more with FoxPro than other database programs
without resorting to programming, but as you build more advanced appli-
cations, you will bump against those limitations more and more.
Eventually you will think of something you want FoxPro to do that you
cannot accomplish without programming. It may be adding a custom
menu to make your database system easier for others to use, or an input
or output screen that just cannot be done in FoxView. When you find
yourself frustrated because FoxPro cannot do what you want it to do, it’s
time to turn to programming.
FoxPro programs are made up of three basic building blocks: FoxPro com-
mands; memory variables, which hold data of some sort for later action;
and programming constructs, which tell FoxPro to loop through a series
of commands or jump to a different area of the program or make a deci-
sion based on the value of a variable or database field. With these three
building blocks, you can create complex database systems.
To create a FoxPro program, you can use the File Open menu, choosing
Program from the Radio Button choices of the File Open menu. A Text
Editing window, with the title Untitled.prg will open. In this window
you create your program. In the Command window, enter the command
where filename is the name of your program file. In either case, the Text
Editing window will open, ready to take your program. If you have a
favorite text editor you would rather use, you can have FoxPro open the
text editing window with that editor by adding a
TP = editor_name
SELECT 1
USE CUSTOMER INDEX CUST_NAME
SELECT Z
USE ORDER INDEX ORD_NAME
SET RELATION TO CUST_NAME INTO CUSTOMER
BROWSE NOMODIFY
RETURN
FoxPro starts at the first line of a program and moves through the com-
mands one line at a time. Later you will see ways to modify this flow of
control.
Adding Comments to
a FoxPro Program
Comments are an indispensable part of all FoxPro programs. No matter
how good your program is, the day will come when you need to change
it; then you will be glad you included comments.
READ
340 Part II]: Advanced FoxPro
This fragment shows the two ways to add comments to a FoxPro program.
When a line begins with an asterisk (*), FoxPro ignores everything on the
line. Note that the asterisk does not have to be in the first column, but it
does have to be the first character on the line. The second way to com-
ment in FoxPro is with &&, which tells FoxPro to ignore everything on
the line to the right of the &&. This is used to put a comment on a line
that also has FoxPro code.
Make sure that your comments tell you something valuable. It does no
good to comment something that is clear simply by reading the code. A
well-commented program is easier to debug and easier to change.
CURR_REC = 100
.. program statements
GOTO CURR_REC
assigns the value 100 to a memory variable named CURR_REC. At a later
point in the program, the memory variable CURR_REC is used in a GOTO
statement. FoxPro will read this statement, know that CURR_REC has the
value 100, and execute a GOTO 100 command.
Chapter 11: Programming with FoxPro 341
Memory variables can take the same characteristics as database fields, but
there is no MEMO memory variable type. Thus, memory variables
can be of the types character, numeric, float, date, and logical. A mem-
ory variable’s type is defined by what is assigned to it. The expression,
CURR_REC = 100
You can assign to a memory variable the value from any valid FoxPro
expression. For example, the expression
sets the variable BIG_NUM to a logical type and assigns to it FoxPro’s rep-
resentation of true, .T., if the AMOUNT field of the current record in the
ORDER database is equal to or greater than 100,000.
CURR_REC = 100
SKIP
CURR_REC = CURR_REC + 1
Here, CURR_REC has been assigned the value of 100 and a SKIP statement
is executed. Afterward, CURR_REC is set to the value of itself plus 1
(CURR_REC + 1). In the assignment statement, the CURR-REC on the
right side of the equation has substituted for the value 100.
(The ? in the example is a FoxPro command that prints to the screen the
expressions following it. The ? and ?? commands are explained later in this
chapter. )
However, if you execute an expression with the wrong type, such as the
following:
NUM1 = 100
STRING1 = "Here is string one”
STRING2 = STRING1 + NUMI1
you see the output and the error message in figure 11.1.
Fig. 11.1.
Actions on the
wrong types of
memory
variables. clear
numl = 108
stringl = “Here is string one”
stringZ = stringl + numi
There are limits on the number of memory variables you can have active
at one time in FoxPro, but they are so great that you will probably never
bump against them. If you do, you can consult the FoxPro manual to learn
how to fine-tune FoxPro to allow more memory variables.
The logical expression can be any valid FoxPro expression that FoxPro
can evaluate to true or false. As such, the expression must compare two
values, one on each side of a logical test. The format for logical expres-
sions is
You can combine one or more logical expressions using AND and OR.
The format for this is
This is less confusing than it sounds. With a bit of practice, you will
understand these logical expressions and compound logical expressions.
Using IF..ELSE..ENDIF
As you saw, the IF..ELSE..ENDIF construct gives you a way to execute one
set of statements if a condition is true and to skip those statements,
optionally executing another set, if the condition is false. The format of
the IF..ELSE..ENDIF construct is as follows:
IF logical_expression = TRUE
execute these statements
ENDIF
Chapter 11: Programming with FoxPro 345
IF logical_expression = TRUE
execute these statements
ELSE
execute these statements
ENDIF
You don’t have to include the ELSE; if you don’t and the logical expres-
sion evaluates to false, FoxPro skips to the statement immediately follow-
ing the ENDIF. In any case, you must end with the ENDIF; otherwise,
FoxPro will not know when to start executing statements again.
Using DO WHILE..ENDDO
Many times you will want FoxPro to execute the same block of statements
more than once. You use the DO WHILE..ENDDO construct in this case.
The format of this is
After initializing the COUNT and TOT_AMT memory variables (if you
don’t, you will get a error message the first time you try to use them in
the COUNT = COUNT + 1 statement), FoxPro evaluates the logical
expression COUNT < 1000. Because the first time through, COUNT
equals zero, FoxPro executes the statements between the DO WHILE and
ENDDO commands. Then it jumps back to the DO WHILE and evaluates
the logical expression again. This continues for 1,000 records, until
COUNT, which is incremented by one each time the program loops, is no
longer less than 1,000. FoxPro evaluates the logical expression, which
returns false, and jumps to the statement after the ENDDO.
COUNT = COUNT + 1
If that statement were omitted, COUNT would never change, and the DO
WHILE logical expression would never evaluate to false. This is the end-
less loop that programmers know and hate. Only an interrupt (pressing
the Esc key) will break the loop, and that stops the whole program.
Remember: inside the body of the DO WHILE..ENDDO, there must be a
statement that changes the logical expression.
TOT_AMT = 0
DO WHILE TOT_AMT < 10000
TOT_AMT = TOT_AMT + AMOUNT
SKIP
ENDDO
TOVIAME =" 7TOToAMT
Chapter 11: Programming with FoxPro 347
Using FOR..ENDFOR
In the first DO WHILE..ENDDO example, the loop ended when the vari-
able count reached 1,000. Another way to set up a loop for a specific
number of iterations is with the FOR..ENDFOR programming construct, in
which a memory variable is used as part of the FOR statement:
The memory variable MEM_VAR is set to 1 at the start of the FOR loop.
FoxPro executes the statements between the FOR and the ENDFOR.
When it reaches the ENDFOR, FoxPro increments MEM_VAR by one (or, if
STEP is specified, by the amount specified after STEP) and tests whether
MEM_VAR has exceeded the limit (in the example, 100). If it has, FoxPro
jumps to the statement following the ENDFOR and continues.
FOR..ENDFOR loops are useful when you have a set number of iterations.
Note that you also can use memory variables for the FOR limits:
START = 1
END = 100
FOR
MEM_VAR = START TO END
statements to execute
ENDFOR
348 Part Ill: Advanced FoxPro
Using SCAN..ENDSCAN
When your loop involves looking through a database, SCAN..ENDSCAN
may be the programming construct you need. When FoxPro encounters a
SCAN statement, it starts at the beginning of the current database file and
executes each statement between the SCAN and the ENDSCAN for each
record in the file. You can use SCOPE, FOR, and WHILE clauses to limit
the scan process.
Using DO CASE..ENDCASE
The IF..ELSE..ENDIF construct enables you to define the direction your
FoxPro program takes on an either/or basis. Depending on the value of the
logical expression, the program either does one thing or another. Often
times you will want to give your program more than one alternative
route; the DO CASE..ENDCASE construct is designed for these cases. DO
CASE..ENDCASE enables you to specify any number of routes, depending
on the value of variables.
DO CASE
CASE /logical_expression_1
statements to execute if logical_expression_1 = TRUE
CASE logical_expression_2
statements to execute if logical-expression_2 = TRUE
CASE logical_expression_3
statements to execute if logical_expression_3 = TRUE
OTHERWISE && optional OTHERWISE clause
statements to execute if none of the CASE logical expressions
are true
ENDCASE
Chapter 11: Programming with FoxPro 349
If the first CASE logical expression is false, FoxPro moves to the second
and evaluates that CASE statement’s logical expression. This continues
until one of the expressions is true, or until FoxPro encounters the
optional OTHERWISE statement. If an OTHERWISE statement is included,
the commands in that block will be executed. If there is no OTHERWISE,
and none of the logical expressions evaluated to true, FoxPro jumps to the
statement following the ENDCASE and continues.
You can see that the DO CASE..ENDCASE construct can take any number
of alternative routes through your program. An excellent example of DO
CASE..ENDCASE statement usage is to process a menu choice:
Note that it is not required that the logical expressions have anything in
common. It is entirely possible to have a DO CASE..ENDCASE fragment
that looks like the following, in which all the logical expressions are com-
pletely different:
DO CASE
CASE AMT > 100
? "The total amount is greater than $100”
350 Part II]: Advanced FoxPro
CASE EOF()
? "You’re at the end of the file”
CASE MONTH(DATE()) <> "JAN”
? "This isn’t January!”
CASE RECNO() > 100
? "Record number = ”", RECNO()
ENDCASE
The difference between INPUT and WAIT is that INPUT will always put
the user’s input into a memory variable; you must specify the memory
variable in the INPUT statement as follows:
causes FoxPro to stop, issue the Error encountered string and wait until
the user enters something. Pressing Enter causes FoxPro to discard the
input and continue processing the program.
Chapter 11: Programming with FoxPro 351
The two statements also differ in the character string that can be used as a
prompt. If you omit this prompt string with INPUT, nothing appears on-
screen. With WAIT, omitting the character string prompt causes FoxPro
to issue the message Press any key to continue, and then wait for the
user’s input.
? ‘This is line 1’
?? ‘This is line 2’
results in
You can list a series of expressions with the ? and ?? statements as follows:
ORDER-—>AMOUNT = 100.00
? "Amount: ” , ORDER—>AMOUNT, ” plus or minus a few bucks.”
results in
Each expression in a ? or ?? list can have several optional clauses for for-
matting and positioning on the line. A PICTURE or FUNCTION clause,
described in the Chapter 3 discussion of FoxView and the Chapter 5 sec-
tion on Report Writing (and more thoroughly in the @ SAY..GET section
later in this chapter) can be included, as can an AT clause, which places
the expression at a specific column on the output line:
AMT = 123.45
TOT_AMT = 12,990.34
? AMT FUNCTION "$9" AT 5, TOT_AMT PICTURE "99,999.99" AT 20
352 Part III]: Advanced FoxPro
results in
$123.44 12,990.34
The ? and ?? statements also are useful for writing reports, when used in
conjunction with the PRINTJOB..ENDPRINTJOB commands. For screen
output, they are limited in that they write only to the current line on-
screen. For full-screen data entry and output, FoxPro provides the amaz-
ing capabilities of the @ SAY..GET statements.
Using @ SAY..GET
Full-screen data entry and display screens are an essential part of a full
FoxPro database system. You have seen how with FoxView you can create
input and inquiry screens that ensure the accuracy of input data and
enhance the presentation of the output. When programming in FoxPro,
knowledge of the FoxPro commands @ SAY and @ GET will give you
great flexibility in this area.
@ SAY and @ GET are shorthand for the FoxPro commands that place
information at specific places on-screen. The actual format of the com-
mands is as follows:
FNAME = "John"
LNAME = "Pickett"
@ 0, 0 CLEAR && clear the screen
@ 1, 10 SAY "Last Name :” + LNAME
@ 2, 10 SAY "First Name: " + FNAME
Chapter 11: Programming with FoxPro 353
The CLEAR command clears only the bottom FoxPro screen. Windows
that are on top of the FoxPro window remain on-screen. For these exam-
ples, the window remains on-screen so that you can see the program and
the result of the program at the same time.
There are many formatting options available for the SAY statement, but
because they also are valid for the GET statement, the next section looks
at that statement first.
Issuing the GET statement in a program does not actually cause FoxPro to
read data from the screen. To activate GET, you must issue a READ state-
ment. When you do that, FoxPro steps through all the active GETs on-
screen, in the order you placed them there, until each has been read, or
the user has pressed a key indicating to end data entry (Esc, PgUp, or
PgDn). The following is an example of using GET statements to read from
the screen in a program:
FNAME = "John"
LNAME = "Pickett”
@ 0, 0 CLEAR && clears the entire screen
@ 1, 10 GET LNAME && place a field on-screen
@ 1, 10 GET FNAME && and another
READ
Only when the READ is executed in the program does FoxPro take infor-
mation from the GET fields. When the GETs are placed on-screen, the cur-
rent value of the memory variable or database field is placed in the GET
field. Figure 11.3 shows the screen when the code fragment is executed.
FoxPro has reached the READ statement and is awaiting input from the
user. The values assigned to the memory variables are displayed and may
be accepted by simply returning through the fields.
CHAP11. PRG
Pickett fname = "John"
Fig. 11.3. John lname = “Pickett”
FoxPro waiting 6, @ CLEAR &&clear the screen
@ 2, 18 GET lname
at a READ 3, 18 GET fname
statement for READ
input.
Chapter 11: Programming with FoxPro 4 55
The GET field will be placed with one space between the end of the SAY
expression and the start of the GET field. Again, an example shows this
best. Combining the code samples for the SAY and GET statements, you
can write the program as follows:
CHAP11. PRG
Last Name + Pickett fname = “John”
First Name : John Iname = “Pickett” Fig. 11.4.
@ @, @ CLEAR &&clear the screen
@ Z, 1@ SAY “Last Name :" GET lname
The screen using
@ 3, 18 SAY "First Name :" GET fname SAY..GET
READ
combination
statements.
You can get quite sophisticated with data-entry and display screens using
SAY and GET statements. You can see many examples of these in action
by creating screens with FoxView and using the MODIFY COMMAND file
to look at the FMT files generated. But you will find as you program more
that FoxView has some limits that you can overcome by programming
things yourself.
356 Part II]: Advanced FoxPro
which would then allow the user to choose from only these
three choices when inputting to the field.
R Tells FoxPro that the format string contains characters other than
standard PICTURE codes and that these characters are to be
placed in the field as edit masks. For instance, @R (999)999-999
causes a field to appear as( )_- and accepts only the
characters 1 through 9. This is useful for creating edit masks for
your data.
T Trims the leading and trailing edge blanks from the data in the
field.
Chapter 11: Programming with FoxPro 357
WHEN <exprL> The field will be READ only when the value of the
logical expression is TRUE. This allows you to skip fields under
some conditions and READ them under others.
When designing a FoxPro program, think about how you will actually pro-
gram the beast. You will find that your program does some things many
times, such as issue error messages, or read data from one database file, or
ask for information from the user. When you find sections of code that
Chapter 11: Programming with FoxPro 359
will be repeated often in your program, break them out into separate pro-
grams. You could, for example, have a program that looks like the
following:
Although this all may work just fine, consider what happens if you decide
that you want your error message to appear in a different place on-screen.
You must go through your program, find each place the error message is
written and change the program to reflect the new location. In a large
program, I can guarantee you will miss at least one.
The solution is to place the error message in a separate program file and
execute that file from the main program:
DO error_msg
put a series of GET statements on-screen
READ the GET statements
process the information in the GET statements; if some information
was not right,
DO error_msg
put the GET statements back on-screen
READ the GET statements
process the information again
Now, if you want to change the error message location, you do so in only
one place, the error message program. Likewise, you can place any rou-
tine that you call more than once in a separate file.
The key to structured programming is to have each subprogram do one
programming process. Then, when something goes wrong with that pro-
cess or you want to change it, you have to change only that one program.
Large FoxPro systems may contain hundreds of program files, each of
which follows this rule.
360 Part IJ: Advanced FoxPro
Using Subprograms
When one program calls another, you will often want the calling program
to pass some data to the subprogram and receive some data back. FoxPro
gives you the ability to do this with the DO..WITH option.
* ERROR_MSG procedure
PARAMETER E_MSG
Now, when you execute ERROR_MSG, you must pass the error message
string as follows:
or
You can see the advantage of the PARAMETER statement. It lets you use
one routine in many different places, with different data going to it at
each of those different places. Your alternative—not a very good one at
all—is to write the routine each place you need it, with the correct data
for that specific place. Subprograms are an absolutely essential capability
of all programming languages, and FoxPro is no exception.
Chapter 11: Programming with FoxPro 361
Now, when your program calls another with the DO command, FoxPro
does not go looking on the disk for the program; it already has it in mem-
ory. You will not believe how fast executing a program in a procedure file
can be.
To place PRG program files into a procedure file, use your favorite text
editor to merge the individual programs into one file. The only change
you must make is to add, as the first line of each procedure, the line
PROCEDURE procname
where proc_name is the name of the program to be called. If, for example.
you have created a file called ERROR_MS.PRG and want to put it into a
procedure file called UTILS.PRG, you would place the line
PROCEDURE ERROR_MS
as the first line of this procedure in the program file. When you have
more than one procedure in UTILS.PRG, it will look like the following:
PROCEDURE add_line
PROCEDURE edit_line
PROCEDURE error_Ms
You can create a procedure file with the FoxPro text editor. First, open a
new program file from the File New menu option. Secondly, use the File
Open option to create a second text editing window with the file you
want to include in the procedure file. Figure 11.5 shows two windows
open, one for the UTILS.PRG procedure file and a second for the program
ERROR_MS.PRG.
IF LEN(msg_str) > 75
msg_str = LEFT(msg_str,7
ENDIF
Move to the ERROR_MS.PRG window and delete the * that marks the first
line as a comment. Then highlight all the lines in the program and choose
Copy from the Edit menu. Now make the UTILS.PRG window active, make
sure that the cursor is where you want to insert the program, and choose
Paste. The ERROR_MS.PRG program is inserted into the procedure file.
You can continue this process until all the program files you want in the
procedure file are included.
Chapter 11: Programming with FoxPro 36 4
PROCEDURE get_char
PARAMETER msg_str, chk_str, ret_char
Fig. 11.6. : Activates a window, “places the msg_str in it and waits for a
: character input. Tests the character entered against the
The GET_CHAR : chk_str and will not return until a valid character has been
; entered.
procedure.
: do a little housekeeping
: Can’t have a string longer than 75 characters, because it
: won’t fit in the box. If the string is longer, truncate it so
: the routine still works
IF LEN(msg_str) > 75
msg_str = LEFT(msg_str,75)
ENDIF
valid_char = .F.
DO WHILE .NOT. valid_char && loop until users enters a
&& character that’s in the chk_str
oa UPPER(ret_char) $ UPPER(chk_str)
; user entered a valid character, exit the do while...enddo loop
valid_char = .T.
ELSE
*: center the error message on the next line
@ 1, (80-LEN(err_msg))/2 SAY err_msg
ENDIF
ENDDO
RETURN
This creates a window from row 21, column O to row 24, column 79
(across the bottom of the screen). A great advantage of using a window is
that, should you decide to put the GET_CHAR input somewhere else on-
screen, you only must change the row and column parameters in the
DEFINE WINDOW command. The line,
IF UPPER(RET_CHAR) $ UPPER(CHK_STR)
centers the MSG_STR on a line. The program adds two to the length of the
MSG_STR,
to account for the space after the message and the space in which the
GET will take place. By doing this, the entire line, message, and GET field
will be centered on the line.
The program shown in figure 11.7 is a routine that uses memory variables
and two DO WHILE..ENDDO loops to give the user the opportunity to
change the entered data before it enters the database file.
Chapter Summary
In this chapter, you have learned quite a bit about FoxPro programming.
You learned about the different programming constructs of DO
WHILE..ENDDO, FOR..ENDFOR, DO CASE..ENDCASE, and SCAN..END-
SCAN, and how these constructs tell FoxPro to react differently to differ-
ent conditions. You learned the basics of FoxPro screen input and output
with SAY and GET statements. And you have seen several sample pro-
grams that illustrate basic FoxPro programming.
add_edit.prg
an append routine that enables the user to edit the record
Fi IML Gf on-screen until it is acceptable. At the end of entering data,
S: OWhG the user is asked if he wants to file, edit or quit without
The : filing. This routine enables you to take data from the screen
but not enter it into the database until it’s correct.
ADD_EDIT.PRG
SET TALK OFF
program. esc_pressed = 12 && READKEY() returns a 12 if escape key is pressed
SELECT 1
USE customer IN DEX cust_num
SAY UJ City
SAY J State
SAY " Zip
USE
RETURN
Installing FoxPro
he installation procedures for FoxPro could hardly be easier than
= MM they are. You enter a command, give the installation routine your
version’s serial) number and activation key. and then swap disks as you’re
asked. Once the base system is installed, you can add nonessential parts of
the system as you want.
This appendix leads you through the installation procedure. When you're
finished, you will have FoxPro and the necessary optional systems
installed properly.
System Requirements
FoxPro is one of a growing number of PC programs that almost require a
hard disk drive. You could run FoxPro on a system with two high-capacity
floppy disk drives (at least 1.2 megabytes per drive) but it would be very
cumbersome and slow.
FoxPro did not follow the trend toward memory-hungry systems, though.
Although more and more PC-based systems require the full 640K of sys-
tem memory (some barely work with that), FoxPro continues to run “lean
and mean.” FoxPro will work well with 512K computer. This doesn’t
mean that FoxPro will not benefit from more memory, however. With
640K, you can add some memory-resident programs, and if your com-
puter does have extended memory or expanded memory, FoxPro can use
it wel) when accompanied by the appropriate memory drivers.
Installing FoxPro
FoxPro’s installation procedure is two part: in the first part, you install the
base system, which is FoxPro itself, FoxView (the screen developer), Fox-
Code (for advanced users), and FoxDoc (a program documentor), Once
you have done that, you're given the chance to install additional programs
you may want.
To install the base system, follow these procedures:
1. Copy the five original FoxPro disks to blank disks. If you have a
one-drive PC, do this with the following command:
DISKCOPY A: A:
If you have a two-drive system, use this command;
DISKCOPY A: B:
In the first case, place the original disk in drive A: and enter the
command. DOS will read the disk (the “source disk”) and prompt
you to enter the disk onto which vou want to copy (the “desti-
nation disk”). In the second case, place the original disk in drive
A: and the new disk in drive B: and issue the command,
Do this with each of the disks, then put the originals away, | know many
readers will totally ignore this step, thinking that because they're putting
FoxPro on the hard drive and never using the original disks, there’s no
need to copy the originals. | have never had an original disk go bad, so |
understand that sentiment; but I have lost original disks and then had my
hard drives crash. This is cheap insurance.
In your FoxPro package is a form showing the serial number and two acti-
vation keys. One activation key, called the Demonstration Activation Key,
unlocks FoxPro so that you can test it, but severely limits the number of
records FoxPro will allow. The second activation key, which you can read
only by opening the sealed envelope, unlocks the full FoxPro system.
2. Next, write down your serial number and the regular activation
key. I suggest you write both down on the original disks, the copy
disks, in at least one of the manuals, in your address book, the
family Bible, and three or four other sate places. I suggest that
because it is easy to lose that sheet of paper with the serial
number and activation keys, and when you accidentally erase your
hard drive (ves, I have done that), you will need the serial
number and activation key to reinstall FoxPro.
Now, finally, you’re ready to install FoxPro. To install the FoxPro system,
you need about 1 megabyte of space on your hard disk. The base system
Appendix A: Installing FoxPro 369
provides all FoxPro functions, but doesn’t include FoxView, the tool used
to develop sophisticated data-entry screens. Adding FoxView and the nec-
essary programs will add 500K to your disk requirements. If you want to
install everything included on the distribution disks (which includes dem-
onstration and tutorial files along with several FoxPro programming
tools), you will need 2.5 megabytes of space.
3. Create a FoxPro directory. If you are installing on a hard drive
designated as the C: drive, type the following command at the C:
prompt:
If you want to install FoxPro on a drive other than C:, replace the
C: in this command with the appropriate drive letter designation.
INSTALL C:
Fig. A.1.
Entering the
Enter your FoxPro Serial Number: FMD@31122 Activation key.
FoxPro will now lead you through the installation procedure, asking you
to insert disks as necessary. When the base system is in place, you will see
the screen shown in figure A.2.
You now have the opportunity to install FoxPro optional products. Some
of these optional products are sample files and tutorial programs; others
are near-essentials, such as FoxView (see fig. A.3).
Fig. A.3.
a CONTENTS : The FORETO
|Product —_[ Space| Install] FoxPro compiled templates. Optional
A Install templates to generate Products
Goodies 98] NO FoxPro code based on the screens i ms
Demo Application you create in FoxView. installation
Color Sets screen.
& FoxDoc
FoxVieu
>
: Disk Statistics
Available disk space: 4,918 Kbytes Disk space needed: @ Kbytes
4 Color Sets. These are color sets for monitor types other than
the one you already specified. No need to install these now.
(if, however, you find your screen difficult to read,
experiment with other color sets through the Window Color
menu option. Choosing another color set may improve your
screen readability.)
FoxPro has created the necessary directories for you. The directory struc-
ture is shown in figure A.4.
FOXPRO SAMPLE
Fig. A.4.
The Directory TEMPLEGEN
structure FoxPro
creates. TEMPLCOD
TUTORIAL
FoxPro is now ready to run. I suggest you create another directory for
your FoxPro database files and other files you will create during the pro-
cess of learning and using FoxPro. To create another file, enter the
command
where dirname is the name of the directory you want to create. Then,
move to this directory by typing
CD \FOXPRO \dirname
Next, set 2 path so that DOS knows where to find FoxPro by typing
PATH = C: \FOXPRO
FOXPRO
You should see the FoxPro opening screen (see fig A‘5). Now turn to
Ouick Start 1 and have fun!
7a San ees
375
376 Using FoxPro
CDOW(), 110
CHR(), 330 I
CTODQ(), 110
date, 109-110 IF..ELSE..ENDIF flow of control construct, 344-345
DOW(), 109 _INDENT system print variable, 278
DTOCQ(), 110 indexes, 63, 119-123
EOF(), 109 attaching to database files, 74-75
LEN(), 109 controlling index, 75-76
logical, 109 creating, 21-23, 64-67
math, 108-109 defining, 71-74
MAX(), 109 expressions, 64-67
MIN(), 109 relational databases, 268-269
eect
- ee
Sm CADE On
Bad Hat Feet
Free Catalog!
Mail us this registration form today, nN . How many computer books do you 6. How would you rate the overall
and we'll send you a free catalog buy a year? content of the book?
featuring Que’s complete line of CL) 1 or less Very good
best-selling books.
(] 2-5 Good
L] 6-10 Satisfactory
Name of Book [] More than 10 ee
1
Poor
Name
. How many Que books do you own?
! 7. What do you like best about this
Que book?
Title 2-5
6-10
Phone ( )
More than 10
Company ow long have you been using
QO000
52 is software? 8. What do you like /east about this
Address
Less than 6 months Que book?
City
() 6 months to | year
[ 1-3 years
Stitte ZIP More than 3 years
hat influenced your purchase 9. Did you buy this book with your
2= this Que book? personal funds?
Please check the appropriate answers: Personal recommendation imiyes L] No
Advertisement 10. Please feel free to list any other
1. Where did you buy your Que book? In-store display comments you may have about
(_] Bookstore (name: ________) Price this Que book.
(-] Computer store (name: _____) Que catalog
(im) Catalog, (names =) Que mailing
(_] Direct from Que |
| Que’s reputation
fail Other: —= {_] Other: 2 =e
OuCcC
You can FAX your order to 1-317-573-2583. Or call 1-800-428-5331, ext. ORDR to order direct. Subtotal (eee
Please add $2.50 per title for shipping and handling. Shipping & Handling eae
Total
Quc
NO POSTAGE
NECESSARY
IF MAILED
IN THE
UNITED STATES
OU
11711 N. College
Carmel, IN 46032
NO POSTAGE
NECESSARY
IF MAILED
IN THE
UNITED STATES
OuUC
11711 N. College
Carmel, IN 46032
HOUCHEN
BINDERY LTD
UTICA/ OMAHA
NE.
SINGH
FOXPRO
Speed up your database operations with Using. FoxPro™ Learn how to...
from Que! Complete with coverage of FoxBase+, this M@ Record data easily with
book teaches you how to create databases, as well as FoxPro’s windowing
timesaving techniques for efficient database operation. _ interface
Using FoxPro is divided into three easy-to-understand
Mi Summarize and sort data
sections. These sections logically advance you from
beginning FoxPro concepts to sophisticated functions. ll Create basic and custom
You learn the fundamentals of entering, editing, and reports
viewing data; managing multiple-file databases; and
li Define, design, and generate
generating FoxPro applications of.your own. Plus, three
~ a relational database _
Quick Start tutorials help you master FoxPro in the
shortest time possible. HI Manage multiple file
databases
Reach ultimate database productivity with Que’s Using
FoxPro! . Mi Program in FoxPro
niBiddk ||USING
3rd Edition Tlie’ ‘Cullen
ISBN O-880ee-S14-9§
ips ~ | | 900009
$26.95 USA | :
$34.95 CAN
£24.95 U.K.
IBM/DATABASE ep | | Bae 9°780880'225 144