0% found this document useful (0 votes)
31 views410 pages

Using Foxpro - John W. Zumsteg

The document is a book titled 'Using FoxPro' by John W. Zumsteg, published by Que Corporation in 1990. It covers various aspects of FoxPro, including fundamentals, intermediate techniques, and advanced programming, with a focus on database management. The book is intended for users looking to enhance their skills in using FoxPro for database applications.

Uploaded by

Parpalabogdan
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
31 views410 pages

Using Foxpro - John W. Zumsteg

The document is a book titled 'Using FoxPro' by John W. Zumsteg, published by Que Corporation in 1990. It covers various aspects of FoxPro, including fundamentals, intermediate techniques, and advanced programming, with a focus on database management. The book is intended for users looking to enhance their skills in using FoxPro for database applications.

Uploaded by

Parpalabogdan
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 410

; ; : ™

¢
‘3

Quick Start tutorials

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.

A ll rights reserved. Printed in the United States of America. No part


of this book may be used or reproduced in any form or by any
means, or stored in a database or retrieval system, without prior written
permission of the publisher except in the case of brief quotations
embodied in critical articles and reviews. Making copies of any part of
this book for any purpose other than your own personal use is a viola-
tion of United States copyright laws. For information, address Que Cor-
poration, 11711 N. College Ave., Carmel, IN 46032.

Library of Congress Catalog No.: 90-60380


ISBN 0-88022-514-9

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

Interpretation of the printing code: the rightmost double-digit number


is the year of the book’s printing; the rightmost single-digit number, the
number of the book’s printing. For example, a printing code of 90-1
shows that the first printing of the book occurred in 1990.

Using FoxPro is based on FoxPro Version 1.0


DEDICATION®™

“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

Acquisitions Editor Editors


Karen A. Bluestein SBC ee

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

Composed in Garamond and OCRB Bold by Que


Corporation.
ABOUT THE AUTHOR.

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

Part I FoxPro Fundamentals


Quick Start 1 Getting Started witht FOXPtOe aor ee eee 9
Chapter 1 AncOverview OR BOXPLrO mci eke oe:
Chapter 2 Designing and Creating a Database............ BD)
Chapter 3 Entering, Editing, and Viewing Information .... 79
Chapter 4 Sorting’ and Summarizing Data. 7s. 6a. eae 101
Chapter 5 Creating Reports: in! FOXPLO 2 a7 ee ee 2D

Part II Intermediate FoxPro


Quick Start 2 lapping thesPowes Of FOXPLo. ©... 5 ae eee Vyas
Chapter 6 Designing, Defining, and Creating Relational
Datla DaS€S Sipacece teres he onl one ra eee ate L179
Chapter 7 Data Entry and Editing with Multiple Files..... 201
Chapter 8 FoxPro Tips, Tricks, and Techniques.......... 251
Chapter 9 Reporting on Multiple Database Systems....... 255)

Part III Advanced FoxPro


Quick Start 3 BuildingsansApplication’s, s4 tape ee 283
Chapter 10 Creating Applications with FoxPro............ 311
Chapter 11 Programming, with (FOXPrO.. <r noeseee 537
Appendix A Install ohOx Proce co.cce ns eae ee eee ee 367
Index sot maser foheHanis ato:worry HR apIeieate SS:5 ae Cite Ca eee een eae a7)

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

Quick Start 1: Getting Started with FoxPro ..... 9


Creating a ‘Database: ncinass 10 niet crete ee een ce os 9
Exploring the Window .2.)50c a an ae ne een ate oe 15
Using the Windows 5.c cho. 5 rec oon es Oe eee em eee oe 19
GeneratingesRepotts from) the: Databases... oc. se ar 23
SUMIIMALY 3 oe oork.n ou he ores carn cas aainie-- cag aye ere Reine tees ee a2

ArvOverview, Of FoxPro... 42... ae eee 33


What. 1S a dataD ase sa tr chk en ale utc teee ae mere rei 33
PAE BCS mgt eae ee Pes ei Sats oes Oe ee ny ee a 34
Relational Piles etch eats oi 7. cutee ey ee ae ona teeTe 34
The Backgrounds of FoxBase+ ,FoxBase
+ /Mac,
ANG FOXPIO2 Gore sae ek ob cs ha scot eng ere ee oe 36
FoxBase+: A Look-Alike of dBASE III PLUS.....\..<...... 36
FoxBase + /Mac: FoxBase+ in the Macintosh Interface .... 37
FoxPro: Bringing the Macintosh Interface to the PC...... By
The FoxPro Environments. ...<c.a0 oan eee eae ee oy
WINDOWS terion ied crsentt eo cuun Aeron tad ene Sete ene eeeere 38
FETE IMOUSE . "aca cinc a opis cease onieemnane ioete talonne a ee een eae 39
UNE ENEYDOALG secon aeticnn Scr te Nod Sek Ue ere ee eee 39
ite: Command: Line Bos tian conto Latent eee heen ae 40
POxPrecGanapilitics rita teh tick: <kaen serum’ kes beaten 41
Entering and Editing Data in FoxPro and FoxBase+...... 41
Reporting in FoxPro and FoxBase 0.0... 6 een ee 41
Programming in’FoxPro and FoxBase+................. 43
Using Advanced Features of FoxPro and FoxBase+....... 43
The FoxPro: Intertace meme veers eae trian tiaras isole ee 44
Choosing from tMentisin....- 7 eee As oa 44

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

Designing and Creating a Database ............. 53


Deciding What Information You Need To Store............ 54
Determining c¥our Objectives 70.7 )-mer an. ene 54
Determining Database Output 23.23 we 54
Building a Database: Structure ese ee i ee 58
Understanding FoxPro’s: Data Types’. p.m. 5 ee De
Character Datais oun. sorsntiae ce etae ner ee eae 60
Numeric: Datae tc 28)..acat in Gee oe ere 61
Float! Data stirs oc eccus acta ea en a eR ee 61
Logical Datasi ns vo < A SR es ae ee 61
Date Data si een.crod no ve i ths es ee eee eee 61
Memo. Data senate nite aim onion ee Gees 62
Picture: Data tne te teae e aaee ore eee ae 62
Creating a Data Dictionary for All Output Elements ...... 62
Defining: Database Struchite: ova, ewe aie ein es es 68
Defining IndexeSig cn decent ye sat ieee or eh rege, Ceci ores za!
Setting Bilters and Fields qr. poet wcrc hee ee ee ar US)
Creating Indexes... cca wae pie ede he we eens eee ie
Attaching Index Files to’ Database) Files... @.6 y.6- en - 74
Modifying tne: Controlling: Index ti. .6 ari eae ve
Deleting oraModilying Indexes 4)... 1 ana eee 76
SAVE LINC VICW tec ta hintns osctiacy Crdtee setae ee a 76
Ghapleresuminary errs ia yayacks Ao ae lot et ee ae dal.

Entering, Editing, and Viewing Information ..._ 79


Entering Records into a Database. cman bar eee eee IO
Using the Default, Data-Entry, Window 0a see 80
Building a,Custom Data-Entty Screen)... 5242-45 2 81
Using FoxView To: Create a Quick View ene ne: 82
Changing Data-Entty Labels: a) .ce ee ana 84

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

Sorting and Summarizing Data.................. 101


Calculating and Summarizing Information in a Database ..... 101
Refining Database Searches! 7.7.2 a eine eer 105
Using the Expression, Builder]. 40": Gm nea eae hme ke 105
Examinin ei EX Dressionsme eer noe oor eee ener 106
Building and Beginning Expressions.................. 106
Using FoxPro Pun Cuons say. j ido gas,Ak Go eae a en ene 108
Math FUN CU OMS hs hiy.4s aetna eons de a ee 108
Stine PUNCHONS! 6b os yas oe conan r ere Rata eae 109
LOgiCal FUNCTIONS: 4) cet. athe eine © de. een kOe LO
Date: Functions 5.75.5 «088 ie URE cone eee 109
Using the For and While Clauses To Limit Searches ...... 110
Using Memory Variables To Store and Display Information... 114
Reattranging:- the: Databases 3. foie aa. « cicero 116
SOLUS Ra's 3-12, Babette eae lay Ae Pe ie ea se 116
EACESING F245. 2 Gumint Rac Mee Gye Aig tea I Aen aN nts 1 ten
Indexing versus Sorting: Which Is Better?............... 120
Creating an NAR Mie isis«sting 66)ong od Rares olloe aluntiseane. ees 120
ChaptersSumimany ee rime haeet teil: ea ale. Gilt one eet alee 1235

Creating Reports in FoxPro...................... 125


Using ther Lay out Windows sien oho Ss am elon sh ashton ea oe 125
Creating aSimplesReporteres see ete dons eer nse oa ouch 127
Adding: Database Pieldstatnds anu «oo a ecumi ne sae bhsa0c 128
Using Objects’on thes Layout, View 3... cen ea ee 128
Using Page Previews oe ocoecren ca tante e tkeeretn ee ees 129
Adding-and Deleting Linés ina Report... =." 2. 4c...
4. - 130
Adding’ a’ Computed Field © .-5. ta, wae oe eae aetna 11
Adding a°Page Header Of FOOUCE |. a. a er ea iL3ol
Formatting Fields on the Report (1 05% 4. ane a 133
Adding, Page-Headers and FOOUers, 3.1; ae eee 134
Adding alittle re rita (Fisica ary 5 a aaecrs meme ene eae ye coer: 155
Adding Summary Fields in the Summary Band........... 137
Running the Report: a: oct ee eae eee eee 142
CreatingsMore Advanced Reports 2.24...4 10 2 eee 144
Adding Groups and Suptotals qa ee eee 144
Adding a Grouprolumimaty, Helden. a poe. ce a ek 148
AGIA GTADUICS 5 ois sacle hase ako here ee en nce Selavne 150
Adding /MEMO FiCldSinr sae aa cd oe ee eee er ae EZ
Chapter-Sumimary ce ee oie hes eek Ca ad Saas se See ae 5%)

Il Intermediate FoxPro

Quick Start 2: Tapping the Power of FoxPro... 157


Creating Multiple-File, Relational Databases ................ eye
Tying, Together ] wo. Databases seta) cae cach were nae ee 166
Creatine Reports on Related Databases..cn2 span 171
SUULIVIIE:@GER ee ER EMT Ty rere ty a teens PT te a ng 176

Designing, Defining, and Creating Relational


Databases ce eater aka koe ee 179
Understanding; a Relational, Database 7 Wi tn shee se 180
Destening a Relational. Database mn... 4. 5 aaeettien Saran Soe 181
Defining Databases and’ Relationships) sm. 9.4 tina « ou: 184
Creating Relational: Database Systemsiy ms. aa - 6h acre ates a0 188
USIN@ AWOL ALCAS «ccstine a2 rsactieyatta SPARE a Stee Ue wate ea: 189
identifying W otk Areas with Aliases” (.. 2... .0 so seeeee ss 190
specifying Relationships in, FOXPL0 22.005 ko eee 192
Setting Relationships in FoxBasesii.0. 24.628 see ees 194
Saving the Setupey i... 5 © atte ae RON hw oe 196
Saving and Using Views in FoxBase+... 06.08 See 196
Vesting a Relational Database, Syctemacwar ss Ae ee 197
Chapter, SUmMIMary. 5. ye dou bis out tee eR ee ee 1S
Data Entry and Editing with Multiple Files.....
Ric eehex te) Meme raha a etn Ah ater ent ny ee An
Understanding How FoxPro Writes and Reads
SCRECMPRICLES arate pty he eae cha etnies, Tee eet oroue ee oe eee
Using FoxView To Create a Multiple-File Form.............
Loadings the: Database: Biles 7. 3i. vs.) do hee ee
Moving -Pields:and:Pagesiag% 3 ie. % tas sey
Changing \GETSUO SAY Sig kai 9 ee & wht orl con eee
Creating a Form Generator for Multiple Files...............
Understanding How FoxView and FoxCode Work
(OSCRER wisn, arte mrcyidane digit dene GRnero Rn eee ee ee
Modifying the Form ‘File Generator, 72... gee ee
Compiling’ the New. Form File: Generator. 00...ose:
Using the Multiple File Form for Data Inquiries ............
Using RANGE andiVALID Clausesiin 22 ames sa: tes ene
Using RANGE \ClauseStyscc2 ois slic 28 Sheeiaee: in ae ee
Using a VALID Clause To; Check) Data Enttve 2... oe
Creating More Sophisticated VALID Clauses .............
Testing Relational Values with a User-Defined Function ...
Using the Record Menu To Find Records -..7...-....<..;
Creatingva Keyed Entry Viewing Program... .. nies ere
Changing ‘the FMT: File; to 2a.PRG: ile. cores eo
Adding Memory: Vatiable GEIS. 072... ee te
Adding 2, DO WHILE ENDDO LOOD tent i
Adding aw ATTMStatement site o.g oon ae eigen
Using the Keyed Form: Prooram: 7. 45.0 se es
Usingathe Form: Progcam for Data Entty. 4.4.3 ee
CHAPEL. SUIMIMALV cgi oon Ai ks ae ee
FoxPro Tips, Tricks, and Techniques ...........
Sita MOUS Cre rrg saath voreece eet rage ease tea en ee
Using Subdirectories and Batch Files-i252 eee see
Using Different-Subdirectories “2.2. ne a a ee
Eliminating Subdirectory Errots.- 5 00: yee ee
Customizing FoxPro with CONEIGEP © io.) samen
Using. Views: 10 Sct\Up POXPLO .2.43.4 5 ae one
ChEACE AUN ICW he sae lags ort aa tn ee ata ae ee
Openitig and, USING VIEWS viii s cote «chk ciate atte a Gee eee
Wein Kev bOat G:SHOr CU tswergei tir coum io) es Ooh ieee
Usitig MACtOSaner aint Merete rl sacteneonuiire) ewsie am Sor eae ee
Creating ae MAClO meet eer Ore pei als ine oN aan a aes
Storing and! Playing BaciaeMaAClO cna ciaahis ne ae on na
Using the Commands Window 2. ees satus acta ss ne
Understanding a Command String 2. rere. 5

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

9 Reporting on Multiple Database Systems....... 255


Designingey OUL REDOL acme acca nee et ae 256
Creating Multiple-Bile- Reports 295.0. ee ee 256
Setting Up the Databases for Reporting ................. 257,
Placing Fields invine: Detail Band se. 3 ates ae eee ee jas)
Adding shtelds tosthe JOCla hin Cran ee ee eee 260
Grouping on asRelated Database. ate ees 262
Placing Related Database Fields in the Group Header..... 263
Generating Controlling Database Ordered Reports.......... 264
Using JOIN Sor REDOStin Ge nt tiene eae aie eee 265
Indexing on-asRelated databases eas ey oe ee 268
WsingvAdvanced Reporting Techniques manana guise ee ace 270
Using Relational ReEPOtisas. cen eons ee eee ee a ae 272
Usineythe, Database Report Menus. 2 spe uae oteane i ote 273
sing the -Commandaw indow «purer Cierra
7 enemas 274
Generating PRINTJOB and ENDPRINTJOB Reports.......... 27)
WeLitings the REPOrt: PlOSlaIn ane. wea yc tee ore: eee ee 273
SCLUING SV SCEM_ELIIE, VAIADIES Gere meeeearners ens eee 277
Using (nesProgt alas. a ere ee ee le ee? a Gee ay, aan 278
@hapteceSumimaty ovcg rye. eee Oe tre eae 2/9

Iti Advanced FoxPro


Quick Start 3: Building an Application.......... 283
Creating an-Application %, vei.e as ee eis mee tans 284
Creatingsvicnustoeian Application: .o)..0 yl aun eee oe 289
Detinine MENU R AGS os, aricks ae hat ata FE ee Oe ee 290
Cleaning: a MenueProerain tereccns tanger «trata een an eee 290
Defining the Pop-up Menus for Each Pad................ 294
Detining FoxPro ACtiOnS «2,5 gucsc5. <4. cre Gy ce ee 301
Debucging. Your Application ae wie deck Rene ee 307
Wsing ‘the: Trace Window: © jcorcs. Pete eater nea 307
DSUTTMITVA
LY ci 6 taecclbicy reco mice ae Se Ge 310

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

11 Programming with FoxPro....................... 337


Creating a-POxPro: Procrany 3 0 este os its See Hace ne Cone 338
Using FoxPro Commands in Programs: 2.0323. s.. et 539
Adding Comments to a FoxPro Program................... 339
Wsine sMemotya Valid les ane ys5e) om fis ee eee eee 340
Assigning Values! to. Memory Variables. ..5..2..2 seusd oes 340
Combing Memo@nvay amalies. ns sha s.5 ss 3c aehear eee 341
Controlling the Flows OPE xccunOil..« ose .sae scone o. nde es 343,
Usiiie Logical EXpressions © aq maar: oe cone en ain was essa 343
Using IP: ELSE END IB aia cs ren can etd Wier ren ie cus 344

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

InstallingsKOxPro4) Fie ee 367


SYSCEm REGUIFEMENTS ect ee hee «oan en IEE) nae eee 367
Installing FOXPLO™ ti... sas) cree aaa bese tisk ate oe ees 368

INGOX a 5B aor ca ren ty es Ree Siete, Ser 375

XiV
ACKNOWLEDGMENTS

A ny book, and Using FoxPro is no exception, is a lot of work by


many people. I wish to thank those who helped me put this
book together.

First, thanks to my friends and family who encouraged me to write


Using FoxPro, and then endured my near-terminal grumps as it was
being written.

Many fine people at Que Corporation encouraged, prodded, assisted,


and cajoled me into writing the best book I could. These include
David Maguiness, Karen Bluestein, Renee Ackerman, Jo Anna Arnott
(what patience!), and the many editors who often knew, better than
me, how to write what I was thinking. Also, thanks to Larry Peters
for editing the technical aspects of Using FoxPro.

Thanks to Dean Myers and Computerland of Portland, Oregon, for


providing several state-of-the-art PCs to research and write this book.
With the difficulty they have had getting these PCs back (one does
get used to powerful computers), they may be regretting their deci-
sion, but thanks anyway.

Mostly, a special thanks to Terrie Lynn Solomon of Que Corporation,


whose faith in me resulted in this book. Without Terrie’s encourage-
ment, I would never have written Using FoxPro. Thanks, Terrie.

XV
TRADEMARK
ACKNOWLEDGMENTS

ue Corporation has made every effort to supply trademark information


about company names, products, and services mentioned in this book.
Trademarks indicated below were derived from various sources. Que Corpo-
ration cannot attest to the accuracy of this information.

Apple, Mac, and Macintosh are registered trademarks of Apple Computer, Inc.

COMPAQ is a registered trademark of COMPAQ Computer Corporation.

dBASE III PLUS and dBASE IV are trademarks of Ashton-Tate Corporation.


FoxBase+, FoxBase
+ /386, FoxBase/Mac, and FoxPro are trademarks of Fox Software,
Inc.

MS-DOS is a registered trademark of Microsoft Corporation.

OS/2 is a registered trademark of International Business Machines Corporation.


UNIX is a trademark of AT&T.

XVi
Introduction

=9) oxPro brings to the PC world of database programs a unique combina-


— tion of power and ease of use. With FoxPro, you can develop database
applications to perform simple and complex jobs, and you can do it with-
out learning an esoteric “language.” FoxPro’s windowing environment,
brought from the Macintosh, makes complex database applications far eas-
ier than with any other database manager.

Just what is a database or a database manager? If you have information that


can be defined in some organized way, you have a database. If the volume
of that information makes it impossible for you to make sense of it, you
need a database manager. A database manager is a program that stores the
data in your computer and enables you to look at that data in various
ways—sorted, viewed in whole or part, and reported any way you need.
FoxPro gives you the power to do all this.

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.

How To Use FoxPro and This Book


Learning a new computer program can be an exercise in frustration. You
know that the new program is going to pay great dividends in produc-
tivity and skill, but initially you may encounter obstacle after obstacle. I
call the first stage of learning a new program “fritter time”; you just seem
to fritter time away trying to get to those gains in productivity. Using Fox-
Pro is designed to reduce fritter time to a minimum.
2? Using FoxPro

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.

Users with some familiarity of FoxBase + or another database management


program also should go through Quick Start 1 because it is the easiest way
to learn how FoxPro is different from other programs. This quick start will
help you become comfortable with FoxPro’s user interface.
Introduction
3
When you’re comfortable with your basic knowledge of FoxPro’s capa-
bilities and user ifterface, proceed to Quick Start 2, where you will learn
to tap FoxPro’s real power: its capacity to work with many related files.
The chapters in Part II cover data entry, editing, viewing, and reporting on
more sophisticated and complex database structures. This area is where
FoxPro and FoxBase+ really stand out, providing power capabilities with
unmatched ease of use.

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.

Some Database History


Computers originally were used for number-crunching, but it was not
long before databases made their appearance. Nearly every computer
application in the commercial world requires data storage; accounting sys-
tems store information about customers, orders, accounts payable and
receivable, inventory, and myriad other sources of data. Microcomputers
applications are no different; the storage and retrieval of data quickly
became a primary purpose of microcomputers.

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.

Differences in computing power and database management capabilities


between FoxPro and other database programs are minor, but the ease-of-
use of FoxPro makes it a superior product.

Who Should Read This Book?


Anyone using FoxPro will benefit from Using FoxPro. Novices will be able
to start from square one, learning the necessary concepts and techniques
to get FoxPro up and running productively. The quick start chapters pro-
vide tutorials to give new users immediate successes with FoxPro. Follow-
ing chapters build on that foundation, providing more detailed and in-
depth knowledge to allow more sophisticated use.

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.

How To Use This Book


Because FoxPro uses a novel user interface, the first topic for any new
user of FoxPro is navigating in that interface. For this, you should start at
Quick Start 1. In fact, all users should go through this section, because it
provides essential information about navigating in FoxPro, which is unlike
any previous version of FoxBase or any other database PC system. If you
have any experience with Macintosh software (particularly if you have
used FoxBase/Mac), you will find this familiar ground.

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

More experienced users, after learning how to navigate in windows, can


jump to sections of particular interest. Note, though, that FoxPro does a
lot of things differently and better that FoxBase+ and its competitors;
there is much to learn here for even an experienced user.

Most of all, have fun! FoxPro brings an incredible amount of database


power to you and your PC, but it is an enjoyable program to learn and
to use.
a
ee Eee
6 Using FoxPro
ee eee
Part I

FoxPro
Fundamentals

Includes

Quick Start 1: Getting started with FoxPro

An Overview of FoxPro

Designing and Creating a Database

Entering, Editing, and Viewing Data

Summarizing and Sorting Data

Creating Basic Reports


8 Part I: FoxPro Fundamentals
UICK

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:

1. Assuming that you have FoxPro installed on your computer in a


directory named FOXPRO, enter the following commands:

CD \FOXPRO
MD CUST
CD7CuUsT,
PATH = \FOXPRO
FOXPRO
10 Part I: FoxPro Fundamentals

This series of commands moves you to the FOXPRO directory,


creates a subdirectory named CUST, moves to that directory, sets
a path so that MS-DOS can find FoxPro, and invokes the FoxPro
program. You should see the FoxPro opening screen (see fig.
QS1.1).

System File Edit Database Record Program Window

Fig. QS1.1.
The opening
FoxPro screen.

FoxPro 1.88 (c) Fox Software 1984,1989, U.S./Canadian Edition # XPD@43234

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

SEER File CRUE ESCM are rr

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.

System, File Edit Database Record Program Window

Fig. QS1.3.
The New dialog.

Database
Program
File « OK »
Index
Report <« Cancel >
Label
Form
12 Part I: FoxPro Fundamentals

System GE ees ait

Fig. QS1.4.
Structure: Untitled
The Structure Name Type Width Dec
dialog. Field

«Insert?

<Delete>

« OK »

<Cancel>

Fields: @ Length: 1 Available: 3999

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.

5. In the Field Name column, enter cust_name, telling FoxPro that


you want to create a field in the database with that name. Press
the tab key to move to the next column, the Type column. FoxPro
has several different type fields, which you can see by pressing
Enter or by pulling down the mouse pointer from the Type box.
Leave this field as a Character field, the default.

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:

Field Name Type Width Decimal

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.

System File Edit Structure

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 >

Fields: 12 Length: 147 Available: 3853

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:

1. In the data-entry window (see fig. QS1.6), the cursor is in the


field labeled Cust_name. Enter a customer name in this field. You
can enter any characters or numbers, either upper- or lowercase.

System File Edit Database Record Program Window Browse


CUSTOMER
Cust_name
Addr_1
Fig. QS1.6. Addr_2
Cit
The data-entry Sie
window. Zip
Phone
Contact
Credit
Last_pur
Last_amt
Preferd

»>Cust_name
»Addr_1 j
mAddr_Z td

2. When you're finished entering a name in the CUST_NAME field,


press Enter to move the cursor to the next field, ADDR_1. Enter
an address and continue, entering a second address line if you
want, and the city, state, and ZIP code.

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.

co Close the data-entry window by pressing Esc, or by moving the


mouse pointer to the Close box in the upper left corner of the
window and clicking. You’re now ready to look through your
database with the Browse command.
Quick Start 1: Getting Started with FoxPro 1 5

5. To view the information in your database, select Browse from the


Database window. FoxPro displays the Browse window, shown in
figure QS1.7.

System File Edit Database -Record Program Window Browse


By CUSTOMER =
[eustnun|Custinane
[ati ¢|
1 West Hill Florist 32981 Znd Ave So Fig. QS1.7.
zZ Northwest Microsystems, In}18968 127th Pl
3 SCIL P.0. Box 2231 The Browse
4 S & C Autos 3342 E. Elwood window.
5 Comar 334Z3 Airport Drive
6 Cosars Continent 9423 Wilson Rd
i Northend Music SouthCenter Mall
8 Bill’s Plumbing Z3Z3 N. Z3rd
3 Studio 11 Art 2231 Fourth
OshKosh Cow Company 5534 E. Dairy Rd
Metropolitan Corp 8823 E. Military Rd
Hess Aviation Inventory |3342Z2 Aviation R
T. Moore & Associates unknown
Oriental Cuisine 4432 International Ave

Although the word “browsing” carries connotations of afternoons spent at


the mall, it is an apt description of how you look at the information in a
database. You can stroll through the database, looking at this record and
that field, going back and forth to look at different things. FoxPro’s Browse
command enables you to do just that, and throws in the capability to add,
edit, and delete data from the same window quickly.

Exploring the Window


Browse through the database by scrolling lines upward and downward.
Move the mouse pointer to the right margin of the window, which is
called the Vertical Scroll Bar. Move the pointer to the scroll-down symbol
near the bottom of the scroll bar and click. You will see the database lines
in the window move up one line. This is called scrolling down. The
Browse window is a window on your database and, by clicking the scroll-
down symbol, you move that window down one line in the database. You
can move it back up by moving the mouse pointer to the scroll-up symbol
at the top of the scroll bar and clicking.
If you are working from the keyboard, use the up- and down-arrow keys
to scroll. As you press the up- or down-arrow keys, the highlight will
16 Part I: FoxPro Fundamentals

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

System File Edit Database Record Program Window Browse


S : CUSTOMER =|

32981 Znd Ave So Fig. QS1.8.


18968 127th Pl
P.O. Box 2231 The Browse
3342 E. Elwood Suite #Z3 window after
33423 Airport Drive i i ;
44Z3 Wilson Rd scrolling to the
SouthCenter Mall 4281 Southcente right.
2323 N. 23rd ‘
2231 Fourth
5534 E. Dairy Rd Pasture 8
8823 E. Military Rd
334Z Aviation R Hangar 18
unknown
4432 International Ave

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.

System File Edit Database, Record Program Window Browse

Fig. QS1.9.
The Browse
window, dragged
partly off the
LJ CUSTOMER screen.

West Hill Florist 32981 2nd Ave


Northwest Microsystems, In}18968 127th Pl
SCIL P.O. Box 2231
S & C Autos 334Z E. Elwood
Comar 33423 Airport
Cosars Continent 4423 Wilson Rd
Northend Music SouthCenter Ma
Bill’s Plumbing 2323 N. Z3rd
Im Studio 11 Art
DNOAUNDBWNe 2231 Fourth
OshKosh Cow Company 5534 E. Dairy
Metropolitan Corp 8823 E. Milita
Hess Aviation Inventory |334Z Aviation

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.

System File Edit Database Record Program Window Browse


is CUSTOMER
naar
A West Hill Florist 32981 Znd Ave So
Fig. QS1.10. Northuest Microsystems, In|18960 127th Pl
Zooming a SCIL P.O. Box 2231
5 i S & C Autos 334Z E. Elwood Suite #23
window to fill Comar 33423 Airport Drive
the screen. Cosars Continent 4423 Wilson Rd
Northend Music SouthCenter Mall 4281 Southcente
Bill’s Plumbing 2323 N. Z3rd
Studio 11 Art 2231 Fourth
OshKosh Cow Company, 5534 E. Dairy Rd Pasture 8
Metropolitan Corp 8823 E. Military Rd
Hess Aviation Inventory |334Z Aviation R Hangar 18
T. Moore & Associates unknown
Oriental Cuisine 4432 International Ave
Pickett’s House of Music

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

Using the Window


Besides giving you a way to look at your database, the Browse window
enables you to edit and delete information in the database. To do some
basic editing and deleting in your CUSTOMER database, follow these
steps:

ik Move the mouse pointer to the CUST_NAME field in the first


record and click. The entire record is highlighted and the field is
selected. On a color monitor, the characters in the field change to
yellow, showing the selected field. You can now edit the field.
When you're finished, click somewhere in the window and the
new information is accepted.

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, move to the ADDRI field in the first record


and select the field. Place the cursor over the first character of
the field and drag the mouse to the end of the field (holding the
mouse button down while moving the mouse). On a color
monitor, the entire field is now on a red background, indicating
that all the characters have been selected. Press Del to remove all
the information in the field (see fig. QS1.11).

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.

System File “Edit Database Record Program Window Brovse

a
Lt CUSTOMER =

West Hill Florist &


Northwest Microsystems, In]18968 127th Pl Fig. QS1.11.
SCIL P.O. Box 2231 Deleting all the
S & C Autos 334Z E. Elwood Suite #Z3
Comar 33423 Airport Drive information in a
Cosars Continent 94423 Wilson Rd field.
Northend Music SouthCenter Mall 4281 Southcente
Bill’s Plumbing
Studio 11 Art
OshKosh Cou Company 5534 E. Dairy Rd Pasture 8
Metropolitan Corp 8823 E. Military Rd
Hess Aviation Inventory |334Z Aviation R Hangar 18
T. Moore & Associates unknown
Oriental Cuisine 4432 International Ave
Pickett’s House of Music
2? Part I: FoxPro Fundamentals

3. To restore the information you just removed, select Undo from


the Edit menu. Undo enables you to reverse many actions you
have just taken. Any time you make a mistake, check to see
whether Undo is available. Some actions cannot be undone; if this
is so, the Undo option will be dimmed in the menu, indicating
that FoxPro cannot undo your last action.

4. You delete a record from the database by pointing to the space


between the left-most field in the window and the left margin and
clicking. A Deleted Record symbol appears (see fig. QS1.12).
From the keyboard, you can delete the record by selecting it and
choosing Delete from the Record menu. In the Delete dialog,
choose Delete. The Deleted Record symbol appears in the Browse
window.

System File Edit Database Record Program Window Browse


a CUSTOMER
part
Fig. QS1.12. West Hill Florist 32981 Znd Ave So
Northwest Microsystems, In]18962 127th Pl
The Deleted Deleted——> [-SCIL P.0. Box 2231
Record symbol Record S & C Autos “ 3342 E. Elwood
na record Symbol Comar 33423 Airport Drive
Fe ae Taco Cosars Continent 4423 Wilson Rd
marked for Northend Music SouthCenter Mall
deletion. Bill’s Plumbing 2323 N. Z3rd
Studio 11 Art 2231 Fourth
OshKosh Cow Company 5534 E. Dairy
Rd
Metropolitan Corp 8823 E. Military Rd
Hess Aviation Inventory |334Z Aviation R
T. Moore & Associates unknown
Oriental Cuisine 9932 International Ave

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

6. To remove all marked records permanently, choose Pack from the


Database menu. FoxPro displays a dialog asking you to confirm
that you really want to Pack the database. Choose Yes. Packing the
database permanently removes the records marked for deletion.

7. Finally, choose Append from the Record window. FoxPro will


open the data-entry window, enabling you to enter more records
into the database. Add a record or two for practice, then close the
data-entry window by pressing Esc or clicking the Close Window
symbol in the upper left corner.

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

System File Edit Database’ Record Program Window

Fig. QS1.13.
« View > Work Areas « Relations > & Q 3
The View
«On/Off > >» CUSTOMER window.
A
—B- ¢
<Files > ae
= R=
« Misc > =e
—F-

<Setup > -G-


—H-

«Browse? Sh
-J-

« Open >

<Close > {CUSTOMER Records: 15


22 Part I: FoxPro Fundamentals

2. Select Setup and the Setup dialog appears, as shown in figure


QS1.14. In this dialog, you specify information that will be
attached to the CUSTOMER database. Choose Add to tell FoxPro
you want to add an index to the database.

System File Edit Database Record Program Window

Fig. QS1.14. Database: CUSTOMER


The Setup dialog. Structure: <Modify> Indexes:

CUST_NAME «Add... >?


ADDR_1 <Modify...>
ADDR_Z < Remove >
CITY <Set Order>

Fields: 13 Length: 153 Index expr:


Index filter:
C 1 Set Fields...
( ) On (+) OFF
ISR iditers.
C J Format...

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.

System File Edit Database Record Program Windou

Fig. QS1.15. Open Index File:


The Open Index
File dialog.

Directory CUST

« Open

< Cancel
{C J All Files
Quick Start 1: Getting Started with FoxPro 23

4. The Index On dialog appears (see fig. QS1.16). To create an index


on the CUST_NAME field, select CUST_.NAME in the scrollable list
and press Enter or double-click CUST.NAME. CUST_NAME appears
on the Expr line. Select OK and the window closes.

System File Edit Database Record Program Window

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.

6. FoxPro now indexes the database. Choose Browse from the


Record window and you will see that the database is presented in
alphabetical order by the CUST_NAME field (see fig. QS1.17).
4

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.

Generating Reports from the Database


FoxPro provides a sophisticated Report Writer, capable of reporting on
multiple databases in an almost unlimited number of ways. Fortunately,
24 Part I: FoxPro Fundamentals

System File Edit Database Record Program Window Browse


5 CUSTOMER

Fig. QS1.17. Bill’s Plumbing 2323 N. 23rd


a Comar 334Z3 Airport Drive
The CUSTOMER Cosars Continent 4423 Wilson Rd
database, Hess Aviation Inventory |334Z Aviation R
i Metropolitan Corp 8823 E. Military Rd
presented Northend Music SouthCenter Nall
alphabetically by Northwest Microsystems, In]18968 127th Pl
1 Fyre Oriental Cuisine 443Z International Ave
the CUST_NAME OshKosh Cow Company 5534 E, Dairy Rd
field. Pickett’s House of Music
S & C Autos 3342 E. Elwood
SCIL PO. Boxnzzal
Studio 11 Art 2231 Fourth
T. Moore & Associates unknown

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.

“System File Edit Database Record Program Window Report


C UNTITLED.
FRX
R: Page Header
PgHead
Fig.
ry
QS1.18. teint
PgHead

The Layout PgHead


* Detail
window. Detail
Detail
Detail
PgFoot
PgFoot
PgFoot
PgFoot
Quick Start 1: Getting Started with FoxPro ? 5

2. Choose Quick Report from the Window menu. In the Quick


Report dialog that appears, choose Form Layout (see fig. QS1.19).

System File Edit Database Record. Program Window Report


UNTITLED. FRX
Page Header Fig. QS1.19.
The Quick Report
dialog.

Report:

Column Layout
Form Layout Fieldi Fieldz2
XXXXXX_XXXXXX
Titles XXXXXX XXXXXX
] Fields...

« « Cancel >

3. FoxPro creates a default report by placing the database fields and


labels on the Layout window, as shown in figure QS1.20.

System File Edit Database Record Program Window Report


UNTITLED.FRX
Page Header

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

System File Edit Database Record Program Window Report


; Preview

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.

2. Next, place the cursor on the label CUST.NAME and, while


holding down the Ctrl key, click the mouse button or press the
space bar. You now can change the text in the label with the
standard FoxPro editing functions. Change this label to Customer
Name. Press Enter to end the editing function. Move this field next
to the CUST_NAME database field.
Quick Start 1: Getting Started with FoxPro PAGE

System File Edit |Database Record Program Window Report


2 : UNTITLED.FRX
R: 16 C:. 25 Detail

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.

System File Edit. Database ‘Record Program Window «Report


2 UNTITLED.
FRX
Detail

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

28 Part I: FoxPro Fundamentals

System File Edit Database Record Program Window Report


, Preview

Fig. QS1.24. Customer Name Bill’s Plumbing


Page Preview of Address 2323 N. 23rd

an improved City Kirkland State WA Zip 98332


4 t Phone 2868829932
repor 1. Contact Oscar
Credit Limit 8.08
Last Purchase Date /
Last Purchase Amount 8.88
Preferred Customer? .

Customer Name Comar


Address 334Z3 Airport Drive

City Cinncinnatti State OH Zip 43554


Phone 6065321181
« Done » < More >» Column: a

Much better, but the addition of a title and some lines will improve it
even more:

1. Return to the Layout by choosing Done.

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.

With a mouse, the process is different. Choose Box from the


Report menu. Then place the cursor where you want to start the
box or line and drag the mouse pointer to where the line or box
should end. As you move the mouse around the Layout you can
see how the box changes shape.
Quick Start 1: Getting Started with FoxPro 29

System File Edit Database. Record. Program Window Report

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

Horizontal and vertical lines are created by making a box and


sizing it so that it has only one dimension. Figure QS1.26 shows
the Layout for a more polished report of the CUSTOMER database.

System File Edit Database Record Program Window Report


O UNTITLED.FRX
Ri 2 Ci 42 - Page Header

Customer Database Report


Fig. QS1.26.
Layout of a
Detail “4
Detail Customer Name
CUST NAME polished report.
Detail Address ADDR_1
Detail ADDR_Z
* Detail City CITY State ST Zip ZIP
Detail * Phone PHONE
Detail # Contact CONTACT
Detail +4 Credit Limit CREDIT
Detail #4 Last Purchase Date LAST_PUR
Detail #4 Last Purchase Amount LAST_AMT
Detail # Preferred Customer? P
Detail #
Detail #4
PgFoot
PgFoot
PgFoot
«

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

System File. Edit Database Record Program Window Report


kk Preview

Fig. QS1.27. Customer Database Report

The polished
report in Page Customer Name Bill’s Plumbing
Preview. Address 23Z3 N. 23rd

City Kirkland State WA Zip 98332


Phone 2868829932
Contact Oscar
Credit Limit 8.80
Last Purchase Date 7 7/7
Last Purchase Amount 8.88
Preferred Customer? .

Customer Name Comar


« Done » < More > Column: a

This new version is a much more readable report, certainly proof that
your computer is good for more than playing F-15 pilot.

Finally, you will want to save and run your report:

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

System File Edit Database. Record. Program:: Window Report

Save Report As:


Fig. QS1.28
Saving the report Be Drive
as REPORT 1, —

Directory CUST #

« Save »

{ ] All Files <« Cancel >

REPORT1_

CX] Save Environment


Quick Start 1: Getting Started with FoxPro 41

2. Close the Layout window by pressing Esc or clicking the Close


Window symbol. You are returned to the FoxPro screen.

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.

System File Edit Database Record Program Windou

Report: Fig. QS1.29.


<Form... > CX] Environment BAe The Report
eis dialog.

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.

System File Edit Database Record Program Window

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

5. If you want to print this report on your printer, select To Print;


otherwise the report will go only to the screen. Select OK, and
FoxPro prints the report. Unless you choose Console Off, FoxPro
will print the report to the screen as it prints it to the printer.

The purpose of all database programs is output—it doesn’t do much good


to store valuable and necessary information without a way to print it or
view it on-screen. FoxPro provides a quick and easy way to create elegant
reports.

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

SF ovo is the latest in a line of database management programs from


= Fox Software. FoxPro’s user interface—the way the program interacts
with the user—breaks completely from other past and current database
programs. Other database management programs require you to learn and
enter commands from a prompt, but FoxPro uses a visually oriented
graphical user interface. Whether you’re a new or experienced database
user, you will find that FoxPro’s windows, menus, and fill-in-the-blanks
approach is easy to use and enables you to be more productive.

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.

+——_ Flat File’s "width" ———>

Employee Employee Phone


Fig. Lal: Number Nane Number

A flat file. geee1 |JONES, ULL. 443-3342


g8882 WILSON, R.B. 334-2231
ge003 ZABY, M.M. 331-2283
90004 ROCKETT, R.W. 335-4423
Flat 88085 KENNEDY, B.W. 449-3312
File’s 60006 COLE, D.W. 442-3382
"length" 068887 PICKETT, W.L. 334-9923
98088 LENNON, H.W. 224-9983
98883 FLEMING, R R.H.
90018 STEWART, U.B. WwWWWoS wowois]wW
60011 STEWART, L.L. 334-9983
86812 SOLOMON, R.R.aro443-5534
96013 SIPPI, L.W. 449-6801
90014 KEHOE, J.C. 558-3342

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

Dept Empl Num| Title Fig. 1.2.


Two related files.
PROGRAMMING MANAGER
OPERATIONS SR UP Emp] Num] Name
SALES SALES REP
CORPORATE DIRECTOR > 86081 JONES, W.L.
ACCOUNTING GEN ACCT 60882 WILSON, R.B.
OPERATIONS OPS MNGR 80063 ZABY, M.M.
PROGRAMMING ANALYST g0084 ROCKETT, R.W.
OPERATIONS DIRECTOR 68885 KENNEDY, B.U.
SHIPPING WAREHOUSE 98086 COLE, D.W.
CORPORATE LEGAL COUN 68687 PICKETT, W.L.
PROGRAMMING DIRECTIR 60888 LENNON, H.W.
9889 FLEMING, R.H.
60618 STEWART, U.B.
00011 STEWART, L.L.

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

System File’ Edit. Database Record Program Window Brouse

13.
Fig 13

[Dept Sept nun]Tey !


DEPTMENT

PROGRAMMING Two related


MMIN EMPLOYEE - :
OPERATIONS FoxPro files.
SALES
CORPORATE
ACCOUNTING
coool |pones,WL. |
WILSON, R.B.
OPERATIONS ZABY, M.M.
PROGRAMMING ROCKETT, R.W.
OPERATIONS KENNEDY, B.W.
SHIPPING
CORPORATE
PROGRAMMING
FLEMING, R.H.
STEWART, U.B.
STEWART, L.L.
36 Part I: FoxPro Fundamentals

The great advantage of a relational database manager over its predecessors


(which require such connections between files to be defined when the
database is created) is that you can set up the relationships as you need
them. You can add another flat file and tell FoxPro about a relationship
between that file and others. Or you can tell FoxPro that two files are
related in one way for one purpose and then change that relationship
when you need to. Relational database managers give you flexibility.

The Backgrounds of FoxBase + ,


FoxBase
+ /Mac, and FoxPro
In this section, you briefly examine the history of Fox Software’s database
products: FoxBase+, the company’s first database program; FoxBase + /
Mac, the result of the company’s move into the Macintosh world; and Fox-
Pro, the company’s current database program, which brings the Mac inter-
face to the PC.

FoxBase+: A Look-Alike of dBASE III PLUS


In 1986, Fox Software introduced its first database product—FoxBase
+.
This product was one of several dBASE III PLUS look-alikes. FoxBase+
had the same user interface and functionality as the industry leader, with
one major improvement: FoxBase+ was about five times faster than
dBASE III PLUS when running programs written in the database language
and doing important database functions such as sorting and indexing. Fox-
Base+ accomplished this supercharging by converting the program’s
source code into an intermediate type of code that ran much faster.

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.

FoxPro: Bringing the Macintosh Interface


to the PC
Although Fox Software originally planned to convert FoxBase+ to the
Macintosh, the company ended up going the other way—converting Fox-
Base +/Mac back to the PC world. The program then took the name Fox-
Pro. The user interface of FoxPro is a direct translation of the Macintosh
interface. Windows, dialog boxes, radio buttons, and pull-down and pop-
up menus abound. Additionally, Fox Software added a number of capa-
bilities to FoxPro, and the company plans to add more capabilities in
future versions to make FoxPro the equal of its competitors in func-
tionality. This power, combined with the almost unbelievable ease of use
brought from the Macintosh version, makes FoxPro the database program
of choice for nearly all PC database needs.

The FoxPro Environment


If this theoretical discussion seems too complicated, don’t worry; you will
see that FoxPro makes seeing and setting up relations between files a sim-
ple matter. As you work through this book, you will learn the basics of
working with related files. When you have learned the basics, you will
think of more and more ways that FoxPro can save you time and effort by
tying files together. More than that, as you use FoxPro, you will find that
its unique environment makes it easy to try new things and learn the art
of relational databases.
3 8 Part I: FoxPro Fundamentals

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.

System File Edit Database Record Program Window . Browse


fe CUSTOMER

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

System File Edit Database Record Program Window

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.

Fox Software’s first recommendation for speeding up FoxPro is to use a


mouse if you’re not already doing so. If you’re new to using a mouse, you
will find that it becomes second nature to you quickly, and you will move
without hesitation around FoxPro. If, however, you don’t have a mouse or
prefer not to use one, all of FoxPro’s power is available from the
keyboard.

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.

Here is an example of a quick keyboard action equivalent to a mouse


selection. The following keystrokes are necessary for you to open the
Browse window:
4 Part I: FoxPro Fundamentals

PeSSmaLO

Alt-D Open the File pull-down menu


B Open the Browse window

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.

The Command Line


FoxBase + users must rely on the command line, which you use to enter
commands to tell FoxBase + what to do. The command line environment
exists in FoxPro, too, in the Command window. Any action FoxPro exe-
cutes from the menus and windows also can be executed from the Com-
mand window. In fact, each action you take in FoxPro is translated to a
command line command and appears in the Command window. Figure
1.6 shows the Command window with several lines built by FoxPro from
menu actions. As you become more experienced, you will find that you
can do some things faster by issuing commands in the Command window.

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.

Entering and Editing Data in FoxPro


and FoxBase +
At the simplest level, FoxPro and FoxBase+ give you a data-entry screen
that allows you to put data into your database quickly and easily. You will
find, though, that a custom data-entry screen speeds your data entry and
makes it much more accurate. FoxPro and FoxBase+ give you tools to
create sophisticated input screens. You can get data for several different
databases from the same screen. You can put edit masks in data-entry
fields to make sure that the data fits a mold. Numeric fields can have
upper and lower limits; FoxPro tells you if you enter a number outside
that limit. Text fields can have character “masks,” such as dashes or paren-
theses to make the data fit a mold.

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?

Reporting in FoxPro and FoxBase +


The fanciest database in the world is useless if you cannot get information
out of it. FoxPro provides an amazingly sophisticated report generator.
With it, you can create highly customized reports, with information com-
ing from different databases, with subtotals and totals, and with boxes and
lines to make the report easily readable. Figure 1.9 shows a report created
with the FoxPro report generator.
4 Part I: FoxPro Fundamentals

System File Edit Database Record Program Window Browse


CUSTOMER
Cust_name West Hill Florist
Fig. 1.7. Addr_1 32981 2nd Ave So
Addr_2
A default data- City Renton
entry screen. State WA
Zip
Phone 2862289932
Contact Wilson
Credit 180.88
Last_pur 11/01/89
Last_amt 23.88
Preferd F

Customer Database Entry

Customer Name

Fig. 1.8. ieee


A custom data- City ] State [
ntry scr } Phone > = ] Contact ]
entry screen nite :
Pref Customer Last Purch Date [ 7 7 J Last Purch Amount [

In the area of reporting, FoxBase+ takes a back seat to FoxPro. The


FoxBase+ report generator is not as sophisticated as FoxPro’s. You will
find it capable for basic reports, but more complex reports require some
programming ability or an add-on program such as R&R, a report writing
program for use with dBASE III, dBASE IV, and FoxBase+.
Chapter 1: An Overview of FoxPro 43

System File Edit Database Record Program Window

Fig. 1.9.
Customer List
A FoxPro report.

Customer West Hill Florist


Address 32981 2nd Ave So

City
State
Zip
Phone 2862289932
Contact Wilson
Credit Limit 100.88
Last Purchase Date 11/81/89
Last Purchase Amt 23.68
Preferred Customer .

Programming in FoxPro and FoxBase+


Even if you’re not a programmer, you may find uses for the FoxPro and
FoxBase+ programming language. When you find yourself doing a
sequence of actions over and over again, you may want to automate that
sequence so that all you have to do is give FoxPro or FoxBase+ a DO
command. At its most basic level, a FoxPro or FoxBase + program is just a
series of commands you enter from the keyboard or with a mouse. Figure
1.10 shows a simple FoxPro program that opens and reindexes a database
and then displays it in the Browse window.

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.

Using Advanced Features of FoxPro


and FoxBase +
For those of you who develop an in-depth knowledge of FoxPro and Fox-
Base+, these programs provide the tools you need to develop complete
turn-key systems, with custom menus, pull-down and pop-up menus, data-
entry screens, and reports.

Future versions of FoxPro also will support network operations, in which


one database can be used by several people at once. FoxPro Version 1.0
does not have this capability.
44 Part I: FoxPro Fundamentals

System File Edit Database Record Program Window


. SAMPLE. PRG =
SET TALK OFF
: SET ECHO OFF
Fig. 1.10. SET CONFIRM OFF
A simple FoxPro
program. SELECT 1
USE customer INDEX custname
REINDEX

SELECT 2
USE deptment INDEX enplnane
REINDEX

SELECT 1
USE
SELECT 2
USE
RETURN

The FoxPro Interface


If you’re familiar with the Apple Macintosh, you will be familiar with Fox-
Pro. FoxPro’s interface came directly from the Macintosh world. To use
FoxPro, you need to know how to do three things (whether you’re using
a mouse or the keyboard): make selections from menus, work with win-
dows, and “talk” to FoxPro through dialog boxes.

Choosing from Menus


At all times, FoxPro presents a main menu across the top of the screen
(see fig. 1.11). Each word on the menu is called a pad and represents a
group of actions that FoxPro can perform.

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

System File Edit Database Record Program Window

caeBar
ses eerl on|| Fig. 1.11.
Menu Pads The FoxPro main
menu.

| System BeeGe Edit Database Record Progran Window — q

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.

Windows and the Mouse


Windows and the mouse go together easily. Each window contains a num-
ber of markers that the mouse uses to move, resize, or close the window.
Figure 1.13 shows a window with these mouse markers.

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

System File _Edit Database Record Program Window Browse

Title Bar

Close—> CUSTOMER = <—Zoom Box Fig. 1.13.


feasting Beret te | 4 FoxPro
West Hill Florist 32981 2nd Ave So window with
Northwest Microsystems, In}18968 127th Pl +Vertical mouse markers.
Thumb

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¥ <«—Scroll Doun
<+—Re-size Box

Scroll Left Horizontal Scroll Right


Thumb

You can scroll in a window by pointing to the arrows in the Vertical


Scroll Bar (the right margin) or the Horizontal Scroll Bar (the bottom
margin). Clicking an arrow once scrolls up or down one line, or right or
left one field. You also can move in the window by dragging the thumb,
which is the diamond shape between the scroll arrows in the scroll bar.
Your position in the list being presented will change to reflect where the
thumb is located in the scroll bar. If you move the thumb three-quarters
of the way along the scroll bar, the window will start listing at three-quar-
ters of the way through the list being shown.

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.

Windows and the Keyboard


Moving, resizing, and closing windows is easily done from the keyboard.
To move a window on-screen, choose Move from the Window menu or
press Ctrl-M. The borders of the active window flash, indicating that Fox-
Pro needs to know where you want the window moved to. Use the four
arrow keys to move the window to the desired location and press Enter
to complete the move.
48 Part I: FoxPro Fundamentals

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.

The elements present in a dialog are examined in the following sections.

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.

System File Edit. Database Record Program Window

Fig. 1.14.
The Save Current
Save Current Document As:
Document As
rC..] dialog.
SAMPLE. PRG

« Save

{ ] All Files < Cancel

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.

Moving Around in a Dialog


A dialog may have many check boxes, radio buttons, scrollable lists, text
boxes, and text buttons. Mouse users can select any option by pointing
the mouse and clicking. Keyboard users can navigate around the dialog by
using the keys listed in table 1.1.

Table 1.1
Keys Used To Move Around in a Dialog
Key Function

Esc Exit the dialog without taking any action.

Ctrl-Enter Choose the default text button and exit.


Tab Move to the next dialog item.

Shift-Tab Move to the previous dialog item.

Arrows Move up and down in a scrollable list.

Home, End Move to the top and bottom of a scrollable list.

PgUp, PgDn Move to the previous or next display page in a


scrollable list.
Chapter 1: An Overview of FoxPro 51

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,

Create a database with names, addresses, and phone numbers

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

Deciding What Information You


Need to Store
FoxPro, like all database managers, is sensitive to its diet; if you stuff it full
of useless information, FoxPro will get fat and slow. So it’s important that
you feed FoxPro only the information it needs to do its job. Your inquiries
will run faster, your reports more quickly. The first step in designing your
database is deciding what information you need to have in the database
files.

Determining Your Objectives


What do you want your database to do? Think through all the things that
you want it to do, even far into the future. If you’re building a customer
file, you eventually may want to track all customer contacts; you may
want to store invoices and billings of each customer; you may want to do
historical reporting of which customers have bought what products. Now
is the time to look at the long term so that, as you build the pieces of the
database, you will know you’re going in the right direction.

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

Determining Database Output


In a world where the amount of information seems to grow exponentially,
it’s easy to start designing your database by surveying all the available data
applicable to your objective. If you are building a customer database, you
may want to include the customer name, address, phone number, contact,
president, vice-president, buyer, warehouse address, shipping address, bill-
ing address, subsidiaries, parent companies, and so on. But the key to
building a clear, concise database design is to start at the other end: what
data has to come out of the database?
Chapter 2: Designing and Creating a Database 55

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 Inquiry

Part Number Keyword Description Fig. 2.1.


An inquiry
Supplier screen.
List Price a Comments:
Cost

Date Last Ordered


Quantity-on-hand
Qty to order at
Automatic Reorder

Inventory Database
Stock Status Report

Date: 61/81/89 Beginning Part Number: #8888888008


Time: 11:32 Ending Part Number + 9999999999
Fig, 2.2.
Quantity Re-order Automatic
An example
Keyword Description on hand Quantity Reorder
report.
aaaaaaaaaa aaaaaaaaaa aaadadaaaaaaaa Cheb ebek)
adaadaaaadaa aaaaaaaaaa aaadaaaaaaaaa SIigI9.99
aaaaaaaaaa aaaaaaaaaa aaaadaaaaaaaaa $9,999.99
aaaaaaaaaa aaaaaaaaaa adaaaaaaaaaadaa $3,999.99

Total Items Processed: nnnn


Items below reorder * nnnn

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

Inquiry Screen Elements

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

Element Name Source

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

58 Part I: FoxPro Fundamentals

Table 2.2— Continued

Inquiry Screen Elements

Element Name Source

part _ number inventory_ record


keyword inventory_ record
description inventory_ record
supplier inventory_ record
quantity_on _ hand inventory_ record
reorder_ point inventory_ record
automatic_ reorder inventory_ record
cost inventory_ record
price inventory_ record
comments inventory_ record

Building a Database Structure


Once you know what information you want FoxPro to store in its
database, you can see what the structure of the database must be. In a
simple one-file database, such as the inventory example, all the informa-
tion can be stored in one database file.

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.

In any system, computerized or not, information tends to fall into logical


clumps. For instance, in a customer database, a clump of data exists for
the customer—name, address, phone number, and so on. In each case,
there will be one piece of each type of data for each customer—one
address, one phone number, and one city. You gather this data into one
file and call it the CUSTOMER file. Another clump of data might be for an
order of merchandise—one customer number, one order number, one
order date, one total amount. You could then gather this order data into a
file called ORDER.

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.

FoxPro stores its information in database files. A database corresponds to


a stack of paper, with each sheet of paper containing information about
one clump of data. If you wrote down on a piece of paper all the informa-
tion you wanted to store about one company, each piece of information
would be the same as a database field and the whole sheet of paper would
be the same as a record. If you did this for many companies and stacked
all the sheets in a pile, that pile would correspond to a database file. To
define a database to FoxPro, you must tell FoxPro about each of the fields
in that database.

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

Understanding FoxPro’s Data Types


Having defined the different fields of the database, now you need to
decide what types of information these fields are. FoxPro stores seven dif-
ferent types of data (character, numeric, float, logical, date, memo, and
60 Part I: FoxPro Fundamentals

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.

Creating a Data Dictionary for All Output


Elements
Once you have decided what forms your information will take in FoxPro,
it’s time to add some information to your database dictionary. Write down
in your notebook the database structure, with all the field types and sizes.
Add as many comments as you can; you cannot have too many comments
in a database dictionary. Table 2.4 shows the database dictionary for the
example inventory database. You may recognize that this information is in
a form almost identical to what FoxPro will need when you're setting up
the database.
Chapter 2: Designing and Creating a Database 6 m)

Table 2.4
Database Dictionary
Database Definitions

Decimal
Element Name Type Length Places

part _num CHARACTER IS)


keyword CHARACTER 15
descr CHARACTER Zs)
supplier CHARACTER Pa)
qty-onhnd NUMERIC 5)
qty_ rorder NUMERIC 5
auto_rordr LOGICAL 1
cost NUMERIC 8 2
price NUMERIC 8 2
comments MEMO 10

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.

Often, though, you want the database to be presented in an order based


on several fields. To accomplish this, you must build an expression; an
expression that combines several fields. When you define the index, Fox-
Pro presents an Expression Builder dialog to ease your job.

To create an index on an expression, open the View window from the


Window menu. If the database for which you want to add an index is not
opened, open it by clicking one of the work areas in the Work Area box
and then choosing Open. Pick the database file from the scrollable list and
choose OK. In the View window, choose Setup; in the Setup dialog, choose
Add. You will see the Open Index File dialog. Choose New. Then choose
Expr from the Index On dialog. FoxPro will open the Expression Builder
dialog (see fig. 2.3).

System File Edit Expression

The Expression INDEX ON: <expr>


Builder dialog. =

Field Names: Database: Variables:

> PART_NUM C > ALIGNMENT


KEYWORD C
DESCR C
SUPPLIER C
QTY_ONHND N
QTY_RORDER N
PRICE N
COST N

A FoxPro expression is a combination of database field names, memory


variable names, FoxPro functions, and text strings. The combination, when
processed by FoxPro, creates a value that FoxPro can use for a specific
purpose, such as searching or indexing a database. The Expression Builder
helps you create an expression by placing database fields and FoxPro
functions in a format from which you can pick and choose.
Chapter 2: Designing and Creating a Database 65

Suppose that you wanted to create an expression to index the CUSTOMER


database on the field CUST_NAME. As with all database programs, FoxPro
sorts the uppercase letters before the lowercase ones, so the name
“HOWARD” will appear before the name “Hobart.” To get a true alphabet-
ical sort, you need to build an expression that changes all the characters
of the CUST_NAME field to uppercase; FoxPro will then index on the
expression, rather than on the actual value in the field. To create this
expression, do the following:

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.

System File Edit Expression

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

FoxPro returns the string "FOXPRO”.


6 Part I: FoxPro Fundamentals

If the cursor is not on the closing parenthesis, move it there with


the arrow keys, and insert the character string you want
converted to uppercase.
3. From the Field Picker scrollable list, choose the field you want
indexed, CUST_ NAME, in the example. FoxPro places this field in
the Expression Builder box.

Your expression is now finished (see fig. 2.5). The expression

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.

System File Edit Expression

Fig. 25.
The completed INDEX ON: ‘expr?
Es) |Es
expression in the UPPER( invntry->part_num)_

Expression
Builder. Field Names: Database: Variables:

> PART_NUM > _ALIGNMENT


KEYWORD
DESCR
SUPPLIER
QTY_ONHND
QTY_RORDER
PRICE
COST TR)
LAS
Iie
ser
al
Si
di
Auer
>

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

In the Browse window, or in reports using this index, the inventory


records would be listed alphabetically by the supplier name. If a supplier
provided more than one part number, those part numbers would be listed
in order. Figures 2.6 through 2.8 show the results of different index
expressions on the example inventory database.
Chapter 2: Designing and Creating a Database 67

eae File Edit Database Record: Program Window Browse


INUNTRY

DELCO 1112628 |DISTRIBUTO|DISTRIBUTOR + —_—~| INTEGRO Fig. 2.6.


DELCO 1112637 |DISTRIBUTO| DISTRIBUTOR INTEGRO .
DELCO 1112685 |DISTRIBUTO] DISTRIBUTOR INTEGRO Using the index
DELCO 1968325 |SEAL SEAL INTEGRO expression Upper
1962885 |DISTRIBUTO| DISTRIBUTOR CAP DELKINS 1M
1962111 |DISTRIBUTO| DISTRIBUTOR CAP DELKINS (CUST_ NAME).
PGS-8 OIL OIL SENDER INTEGRO
_4798Z SPRING SPRING CLIP USSE
CLUTCH B & S 381972
89888652 SEAT WSSE
89891182 SEAT SEAT CUSHION USSE
1-644988-12 |PACKING PACKING LL PARKER
1941613 SEAT SEAT ASSY WSSE
6-649881-Z | PACKING PACKING UNKNOWN
6-649884-Z2 | PACKING PACKING (915DN-Z.5X3.@X1} LANDSLIDE
854414 SEAT SEAT CUSHION
854415 SEAT SEAT BACK
98882212 SEAT SEAT CUSHION

nae File Edit Database. Record Program Pipes Browse

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

System File Edit Database Record Program Window Browse


LJ INUNTRY

Fig. 2.8. 42878 CABLE CABLE IGGY 173MGG-Z-38


LPG-1617 REGULATOR REGULATOR JA ENTR 688
Using the index LPG-1885 COVER COVER JA ENTR. AU6-783
expression Upper LPG-1806 REPAIR REPAIR KIT JA ENTR. R11-Z8
LPG-1823 VAPORIZER VAPORIZER ADJ JA ENTR. 11AZ8
(CUST_ NAME) + 66344 CHECK VALVE 1” SWITCH JENSON 392A
DTOC(DATE). 1181393 JMZ 9397LPD
116387 JMZ 9397LPD
6133-1658 JMZ
98068-25 JOSH
8288-18013 TORQUE CONVERTER CREB JOSH CORPORATION
FD-734974 WHEEL CYLINDER JOSH
FE-1476C MASTER CYLINDER JOSH
FE-1476A MASTER CYLINDER JOSH
CL-1188 CONVERTER CONVERTER JOSH INDUSTRIES
CL-1231 CLUTCH CLUTCH PACK JOSH INDUSTRIES
CL-1239 STATOR STATOR JOSH INDUSTRIES
CL-1248 ACCUMULATO} ACCUMULATOR KIT JOSH INDUSTRIES

Defining Database Structure


Because you’re creating a new database file, start by choosing New from
the File menu. FoxPro displays the New dialog, shown in figure 2.9. Fox-
Pro assumes that you want to create a new database file and highlights
that choice, so you only have to choose OK, and you’re on your way.

System File Edit Databas e Record Program Win dow

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.

System File Edit «Structure

ila ais ieAA a ee Fig. 2.10.


Structure: Untitled The Structure
Name Type Width Dec ;
dialog.

<Insert>

<Delete>

« OK »

«Cancel >

Fields: @ Length: 1 Available: 3999

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.

Defining the fields is, in technical programming language, a “piece of


cake.” Enter the field name and press Enter or Tab. FoxPro moves to the
Type column, which has a default of Char. This column is a scrollable list
field, so you can choose a different type from the list, or simply enter the
first letter of the type you want: N for numeric, M for memo, and so on.
The valid field types are as follows:

Field Default Decimal


Type Length Places
Character 8
Numeric 8 2
Float 8 Z
Date 8
Logical 1
Memo 10

The Date, Logical, and Memo lengths cannot be changed.

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.

System’ File. Edit 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 >

Fields: 18 Length: Available: 3887


Chapter 2: Designing and Creating a Database 71

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.

FoxBase + users follow a similar procedure. The command to create a


new database file in FoxBase+, which can also be entered in the FoxPro
Command window, is as follows:

CREATE dbf_name

where dbf_name represents the name of the database you’re creating.

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.

Bytes remaining: 4088

CURSOR <-- —> INSERT DELETE Up/Down Field: 1 4


Char: +t 4 Char: Ins Char: Del Cursor Menu: “Home
Word: Home End |] Field: *N || Word: “Y |] ExitvSave: “End Fig. 2.12.
Pans “+ *4 Help: Fl Field: “U |] Abort: Esc The Create
Database screen
field name type width dec field name type width dec in FoxBase+.

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

System File Edit Database Record Program. Window

Fig. 2.13.
« View > Work Areas « Relations >
The View dialog.
<On/0ff > > INUNTRY 4
+
‘Files >

«Browse?

< Open >

«Close >

System File Edit Database Record Program Window

Fig. 2.14. Database: INUNTRY


The Setup dialog. Structure: <Modify> Indexes:

> 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

Setting Filters and Fields


You can tell FoxPro you don’t want to see all the fields of the database by
using the Fields check box. Setting Fields to On displays the Fields dialog,
which asks what fields you want to see. From then on, FoxPro acts as if
only those fields exist in your database for display purposes (you can still
compute, look up, or delete the hidden fields). In FoxBase+, you set
fields with the SET FIELDS field1, field2, field3 command.

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:

SET FILTER TO expression

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.

System File Edit Database Record Program Window

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.

System File Edit Database Record Program Window

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

If you need to define an index on several fields or use FoxPro expressions,


select the Expr box to display the Expression Builder dialog. In this dialog,
you can build index expressions from multiple fields or from expressions
involving mathematical or logical operations.

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

INDEX ON expression TO index_ name

where expression is a valid FoxPro indexing expression and index_ name


is the name of the index file that FoxPro or FoxBase+ will create.

Attaching Index Files to Database Files


When you define an index file, FoxPro updates and uses that index file for
the current session. If you close the database, or quit FoxPro and return
later, you must tell FoxPro to associate the proper index files with the
database.
Chapter 2: Designing and Creating a Database 75

In FoxBase+, or in the Command window, you can open a database and


indexes with the following command:

OPEN dbf_name INDEX index_namel1l, index_name2

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.

Modifying the Controlling Index


If you define only one index for the database, FoxPro uses that one to
control how the data is presented and processed. If you define more than
one index, you must tell FoxPro which index is controlling; that is, which
index FoxPro should use to present and process the database. All open
indexes of a database are updated automatically, but only one at a time
can control the database.
You can change the controlling index in the Setup dialog of the View win-
dow. Where before you chose Add to add indexes to the database, now
you use the Control text box to tell FoxPro which index to use. If the
indexes aren’t open, use Add to open them, then choose the one you want
to control the database and select Control. Until you change it again, Fox-
Pro will use the selected index to control how it presents and processes
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

OPEN CUST INDEX CUSTNAME, ZIP, PHONE

the database will be controlled by the CUSTNAME index. To change the


controlling index to the ZIP index, enter the following command from the
command line in FoxBase+ or the Command window in FoxPro:

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.

Deleting or Modifying Indexes


It is easy to delete or modify an index’s expression. Go to the Setup dialog
of the View window and, in the index corner, select Remove to take an
index off the database, or Modify to change its expression. Note that using
the Remove option doesn’t erase the index; it simply tells FoxPro that, for
now, you don’t want that index updated as you make changes. Use this
option with caution, because if you make changes with an index removed
and then later attach that index to the database, the index file will not
reflect the state of the database. To you, the result will be puzzling:
records you know are there will not be found, the Browse window will
show records in a funny order, and reports will not work like they did last
time. When these symptoms occur, you should reindex the database,
which will update the index.

Saving the View


If it seems cumbersome to open a database file and attach indexes each
time you want to use them, you can use the View feature of FoxPro and
FoxBase+. A view saves information about what databases are open and
what indexes are attached to them. You give the view a name and, after
that, you open the view from the File menu, and FoxPro and FoxBase+
will set themselves up just as they were when you defined the view.

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

System File Edit Database Record Program Window

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:

SAVE ENVIRONMENT AS view_name

and you recall it with

SET VIEW TO view_name

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.

Entering Records into a Database


When you have finished defining a database structure to FoxPro, you are
asked if you want to enter data. If you answer yes, FoxPro presents you
with a simple data-entry window. Whether you're using this default data-
entry window or a custom-designed one (it is easy to design elegant cus-

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.

Using the Default Data-Entry Window


If, after defining your database structure to FoxPro, you answer yes to
FoxPro’s question, Do You Want to Enter Data Now?, you are presented with
the default data-entry window (see fig. 3.1). As you can see, each field of
the database has a label, which is the field name, and a data-entry field.
The cursor is in the first field, awaiting your input.

System File Edit Database Record Program Window Browse


INUNTRY

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

System File Edit Database Record: Program: Window. Browse


5 INUNTRY =
Part_num IN 2232
Keyword SEAL F
Descr SEAL, HYDRAULIC PUMP .
A Supplier |CANSTEWART Fig. 3.2.
Qty_onhnd 3 FoxPro moves to
Qty_rorder 1 ; .
eee teaesz first field of the
Cost 32.38 subsequent data-
Auto_rordr 2
Comments memo CHiry, record.

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.

Building a Custom Data-Entry Screen


If you ever have entered large amounts of repetitious information into a
computer, you know how tiresome it can be. Any help you can give your-
self pays dividends in fewer errors and less mental fatigue. You can create
elegant data-entry and viewing screens quickly and easily with FoxView, a
stand-alone program. Although there is no comparable program for Fox-
Base+ users, if you use FoxBase+, you may want to read through this
section anyway; FoxView is a powerful incentive to upgrade from Fox-
Base+ to FoxPro.

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

Using FoxView to Create a Quick View


You start FoxView by choosing FoxView from the program menu. You
also can start FoxView from the MS-DOS prompt or the Command win-
dow by entering

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

<C:\FOXPRO\CUST > Friday 93/82/98


Welcome to FoxView 3.8
Press Fl for HELP
Fig. 3.3.
FoxView C+ >USE INUNTRY_
The FoxView
command shell.

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

USE file. name

where filename is the database name. To continue the example from


Chapter 2, enter JNVNTRY for the file name. FoxView responds by telling
you the number of fields loaded. Now you are ready to design your form.
First, though, some information about FoxView will help you understand
what you’re doing and form a solid foundation on which you can build
your FoxView knowledge.

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.

C: INUNTRY. DBF 2,8 Page: i

Part_num
Keyword
Descr Fi
IZ. 3.4.
Supplier
Qty_onhnd The default form
ee
ric
FoxView creates
Cost for INVNTRY.
Auto_rord
Comments

C: INUNTRY. DBF 5,6 Page: 1

Inventory Database Inquiry | Fig. 3.5.

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

FIELD: can be up to 18 alphanumeric characters and underscore

Changing Data-Entry Labels


Each of the data fields has a label attached to it—the text to the left of the
field. But as you can see, these labels leave something to be desired. As
Chapter 3: Entering, Editing, and Viewing Information 85

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


Form design and modification is easiest in Form view. Return to Form
view from Table view by pressing F10.

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.

Adding Text to the Screen


You can add text strings to your data screen by pressing Ctrl-N. A new
object, labeled text string, appears on-screen. When FoxView creates the
object, it also selects the object and presses the F3 key for you so that you
can move the object with the arrow keys. Because text object probably
doesn’t fit into your design for the screen, you can edit it in the lower left
corner of FoxView just as you edited the data field labels. In this example,
the text object becomes a screen title, centered above the data fields (see
fig. 3.8). Once placed, the title becomes like all other objects—it can be
selected and moved to a new location.
86 Part I: FoxPro Fundamentals

C:INUNTRY.DBF @ 6,13 Page: 1

Fig. 3.7.
The redesigned Part Number: Keyword: Description:
INVNTRY
database form. Suppl ier:
Price:
Cost:

Qty Onhand:
Reorder Level:
Automatic Reorder?
Comments:

C: INUNTRY.DBF © 3,26 #£Page: 1

Inventory Database Inquir


Fig. 3.8. se he oe
A text object a
added, and then Part Number 3 Keyword : D escription
i 4

edited and
Supplier:
moved to form a price:
title. Cost:
Qty Onhand:
Reorder Level:
Automatic Reorder?
Comments:

Adding Boxes to the Screen


Boxes can make or break a data screen. If your data screen has logical
blocks of data, enclosing them in boxes makes the important areas stand
out. Even if you don’t need boxes for that reason, a simple box enclosing
the screen provides a pleasing border. Uncontrolled use of boxes, how-
ever, clutters a screen and makes it confusing. Use boxes sparingly, but do
use them.
Chapter 3: Entering, Editing, and Viewing Information 87

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.

C:INUNTRY.DBF @ 3,26 Page: 1 SELECT BOX

Inventory Database Fig 3.9

The Box menu.


Part Number: Keyword: De

Supplier: Inverse Box


Price:
Cost:
BoxStringl
Qty Onhand: Se SS
Reorder Level:
Automatic Reorder?
Comments:

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.

Using Picture and Function Codes


The way the data fields are defined for the default screen, you can put just
about any character into any field. The numeric fields will accept only
digits, a decimal, and a plus or minus sign, but the other fields are wide
open. In many cases, you will want to limit which characters users can
enter into a data field and which characters FoxPro will present. You do
this by specifying picture clauses, which tell FoxPro what to accept and
present, and how to format the field.

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

C: INUNTRY.DBF © 5,6 Page: 1

|Inventory Database Inquiry |


Fig. 3.10.
The completed Part Number: Keyword: Description:
INVNTRY i PE cere,
database inquiry Supplier:
form. Price:

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.

Picture Template codes apply on a character-by-character basis. If a field


is five characters long, you can tell FoxPro you want the first character to
be uppercase, the second a digit, the third a decimal point, the fourth any
character, and the fifth alphabetic only.

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

The format of Function codes and Picture Template codes in FoxPro is as


follows:

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

Field Type Picture Clause Data Result


CHARACTER "@A” abc989dwxyz8a abcdwxyza
The A Function code allows only alphabetic characters to be entered or
displayed.

Field Type Picture Clause Data Result

CHARACTER "@R 99/99" 1225" P2723

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.

Field Type Picture Clause Data Result

NUMERIC "$$$,$$9.99" 12332.56° $12,332.56


The $ Picture Template code tells FoxPro to place floating dollar signs
before any numbers. The comma and decimal point forces those charac-
ters into the appropriate position in the number. (Cobol programmers
will recognize this picture clause.)

Experimentation is definitely the best teacher for Function and Picture


Template codes. You will find these codes to be useful when you need to
ensure that data is in a certain format.

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

Generating the Format Screen from FoxView


Once you have finished creating your screen and specifying how FoxPro
should use its fields, you have one last step before you can use the screen.
FoxView has to generate program code that FoxPro can use. When you
have become more proficient with FoxPro and FoxView, you will learn
how to create entire applications from screens in FoxView; for now, you
will generate Format files that FoxPro uses in Append and Edit modes.

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.

Using the FoxView Screen


To use the FoxView screen, you first need to tell FoxPro that you want to
use the screen for adding, editing, and viewing data. You do this through
the View Setup dialog. Choose Format, and all Format files will appear in
the scrollable list (see fig. 3.11). Select your Format file, in this example,
INVNTRY, and choose Open and OK in the Setup dialog to return to the
View window. Close the View window and any other windows that may
be open.

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

System File Edit. Database Record Program Window

SET FORMAT: Fig. 3.11.


Selecting a
Cea Format file to
ADV. FMT = ; fi ;
CONTACT. FMT associate with a
CUST. FMT database.
CUSTOMER. FMT Directory
INUNTRY. FMT
ORDER. FHT
ORD_ENTR. FMT
TEST. FMT
TESTX. FMT

{ ] All Files

Part Number: Keyword: Description: Fig 3.12


YT 381739 SEAT SEAT CUSHION
Editing a record
Supplier os
Quantity On Hand: with the Change
Reorder Point: option of the
Price Record menu,
Cost

This brief introduction to FoxView has only touched on its capabilities.


With FoxView, you can create polished data-entry screens that are pleas-
ing to the eye and easy to use, even in databases that require access to
many different files simultaneously.
Q2 Part I: FoxPro Fundamentals

Editing in Data-Entry Fields


Just as you can edit your text entry in the dialog text fields of FoxPro, you
can edit the data you’re entering into your database. When you're in a
data-entry field, the following editing functions are available to you:

Key Function

End Moves to the end of text in the field

Home Moves to the start of text in the field

Backspace Deletes the character to the left

Del Deletes the character at the cursor

PgUp Moves to first character of the current field, then to


last character of the previous field

PgDn Moves to last position of the current field, then to


first position of the next field
Ins Toggles insert/overwrite mode

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.

Using the Browse Window


The Browse window is a window into your database. Like any window, it
shows you only a small portion of the whole scene at any one time. With
your database open, choose Browse from the View window, and the
Browse window appears (see fig. 3.13).

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

frertarun [reword [Deser_[suel


Ld INUNTRY =|

189468 , |FRAME Fig. 3.13.


283128 ARMATURE
28497168 TORQUE CONVERTER The Browse
eesat9 window,
232719
236969
237819
361733
323488 SEAT CUSHION
9449261-0C PLATE
5881468 SEAL
5887888 SEAL KIT
5818583-18 PISTON ROD
5828887-68 W/7 SINGLE SWITCH

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.

Changing the Browse Window


A number of customizations to the standard Browse window can be made
in the View Setup dialog. In this dialog, you can specify which fields you
want to appear in the Browse window by selecting the Fields check box.
A dialog appears in which you specify the fields FoxPro is to display (see
fig. 3.14). Until you specify otherwise, only these fields will appear in the
Browse window.

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

ZIP > 90000

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

System File Edit Database Record Program Window

Fig. 3.14. Database Fields: Selected Fields:

The dialog to PART_NUM c 7) Move >


select fields for KEYWORD c t)
FOxPrO i DESCR c r) All +
OO SUPPLIER c a
display. QTY_ONHND | N )
QTY_RORDER | N r) Remove
PRICE N z
COST N Zz Clear

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.

System File Edit Database Record Program Window Browse


2 INUNTRY =

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

Another common situation in the Browse window occurs when you


want to hold one field in the window while scrolling horizontally through
other fields. In the INVNTRY database, for example, you might want the
PART_NUM field to be visible as you scroll left and right through the
other fields.

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.

System File Edit Database Record Program Window Browse


INUNTRY =

189468 189468 a FRAME Fig. 3.16.


263128 263128 1 ARMATURE | og
2647168 2647168 ) The partitioned
229943 2293493 2 Browse window.
2327193 232719 1
236969 236969 i)
237613 237619 z
361733 361733 i)
323488 323488 7)
449261-0C 449261-0C 4
5861468 5661468 Zz
5887688 5807888 1
5818583-18 5818583-18 1
58628887-68 5628887-88 }

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

Using Browse Options


If you enter the BROWSE command from the command line, you can
specify many options. You can tell FoxPro not to allow modification of
data in the Browse window (NOEDIT), or not to open a data-entry win-
dow for appending new records (NOAPPEND), or not to allow deleting a
record (NODELETE). You might do this when someone else is going to be
using the system, and you want to limit their capability to alter the
database. You also can tell FoxPro to use the size and format of the last
Browse window of this database (LAST), or to inhibit display of the
Browse menu (NOMENU).

Finding Specific Records


If you’re looking for a specific record in a FoxPro database, especially a
big database, browsing through the database becomes a real chore. Fox-
Pro provides several ways to jump right to the record you're looking for.
Two of these ways, the Seek and Find options, require that the database
be indexed on the field you’re searching for; the Locate option will find a
record based on any field in the database, indexed or not.

Using Seek and Find


When you want to find a specific record, you are looking for a specific
value in one of the database’s fields. You may want to find the ABC Com-
pany in a customer database, for example, or part number IN 4434 in an
inventory file. To use Seek or Find, you must have the database indexed
on the field in which your search will take place. In the previous exam-
ples, the INVNTRY database must be indexed by PART_NUM and that
index must be the controlling index of the database if you want to seek
on a part number. If this seems bothersome, consider the advantage:
because FoxPro uses the index to find the record you want, the search is
almost instantaneous. Even in huge databases, a Seek or Find process sel-
dom takes more than a second.

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

System File Edit Expression


TNUNTRY

=) Ee] Ge] Ge]


Value to SEEK <expC> (Index = PART_NUM):
Pig 317
The Expression
Builder.

Field Names: Database: Variables:

> PART_NUM INUNTRY > ALIGNMENT


KEYWORD
DESCR
SUPPLIER
QTY_ONHND
QTY_RORDER
PRICE
COST hls)
ae
oe
Soo
dhe
ate
Ate
©

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.

Using Locate and Continue on Nonindexed Fields


You will encounter situations in which you need to find a record based
on a value in a field you haven’t indexed. The Locate option enables you
to do this. Choose Locate from the Record menu, and you see the Locate
dialog.

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

Warning: | In a large database, a search can take a Jong time. With-


out an index to help find the record, FoxPro will plod
through the database until it finds a record. You will, on
average, search through half the database if you’re look-
ing for just one record. Even with a high-powered com-
puter, sequential searches take time.

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

Packing the Database


In some advanced database systems, hundreds of records are added and
hundreds marked for deletion each day. Obviously, unless those marked
for deletion are discarded, the database will be full of records that are
never used. Even in small databases, it is wise to pack the database peri-
odically to remove unused records.

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.

Calculating and Summarizing


Information in a Database
The quickest way to summarize information in your database is with the
options in the Database menu. To experiment with summary options,
open a database with a numeric field (in this example, INVNTRY is open),
close all windows except the Command window, and choose Sum from

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.

Sirsacnm File Edit Expression

Fig. 4.1.
The Expression
SUM
Peo] Gow] Fon] Ce]
Clause: <expL>
Builder dialog.

Field Names: Database: Variables:

> PART_NUM INUNTRY > ALIGNMENT


KEYWORD
DESCR
SUPPLIER « Verify
QTY_ONHND PADVANCE
OQTY_RORDER « PAGENO
PRICE PBPAGE
COST « Cancel
ZaAzAANA|. PCOLNO

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

System File Edit Database Record Program Window


3287 records summed.
QTY_ONHND QTY_RORDER PRICE COST
4159 1899 66452. 65 38892.66
Fig. 4.2.
The results of a
Sum command.

= Command.
use inyvntry
SUM

<

System File Edit Database Record Program Window

Fig. 4.3.
The Count
Memory Variables: dialog.

feakScope.,

fo) For...
< Cancel >
Co Whilles..

To Variable:

Scope is FoxPro’s way of asking, “Which records should I process, based


on their location in the database?” Scope allows you to limit the database
search to specific records, based on where the records are in the database.
Later, you will learn how to limit FoxPro’s searching and processing by
using values in the database fields with the For and While clauses. The
four Scope radio buttons are as follows:
104 Part I: FoxPro Fundamentals

System File Edit Database Record Program Window

Fig. 4.4.
The Scope dialog.

Eee Scopes...
« Locate »
C&T For...
« Cancel >
{C J] While...

C2) AL If you select this option, FoxPro searches all


records, starting from the beginning of the database.

( ) Next If you select this option, FoxPro searches the next


n records, starting from its current position in the
database. When you select Next, an input window
appears in which you specify the number of
records to search.

( ) Record If you select this option, FoxPro processes only one


record. An input window appears when you choose
Record to ask what record number you want to
process.
( ) Rest If you select this option, FoxPro processes all
records from the current position to the end of the
database.

Choosing one of these options tells FoxPro which records to search as it


processes the command for which the scope is specified; these limits
restrict the search and processing to certain locations in the database
without regard to what is in the record. ALL says, “Process all records,”
Next says, “Just process a certain number from the current position,”
Record identifies one specific record number, and Rest says, “Start in the
current position and process all records to the end.” After you have cho-
sen one of the radio buttons, choose OK. The Count dialog appears; choose
OK again. FoxPro then shows the results of its count on-screen.
Chapter 4: Sorting and Summarizing Data 105

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.

Refining Database Searches


Scope allows you to restrict FoxPro searches by the position of records in
the database. But what do you do if you want to summarize information
from all records in a certain ZIP code range? You can restrict FoxPro’s
database processing to specific records by using a combination of three
capabilities: expressions and the For and While clauses. Using these three
features, you can slice your database in different ways to receive the infor-
mation you need. In this section, you will learn about building expres-
sions and using them in conjunction with the For and While clauses.

Using the Expression Builder


You were introduced to FoxPro expressions in earlier chapters, where
you used the Expression Builder dialog to tell FoxPro which data to dis-
play and delete. Now you will delve more deeply into expressions, which
are the most powerful way—short of programming—to tell FoxPro which
database records you want it to search for and process. First, you will look
at expressions to limit searches of the database to records with fields con-
taining values you define. When you have mastered that skill, you will
apply it to more complex ways of summarizing your data, using For and
While restrictions on the search.

If you want to look at or summarize some specific records of your


database, you must tell FoxPro how to decide which records to include.
You do so by using FoxPro expressions. An expression is just an equation;
FoxPro evaluates the equation for each record the program encounters in
a database search. If the equation evaluates to true, FoxPro includes that
record in the process; if the equation evaluates to false, FoxPro skips over
it. If you want to see only records where the value in field NAME is
JONES, for example, you need to tell FoxPro, “Look at each record; if the
name is equal to JONES, list the record to the screen; if not, skip the
record.” To give this command in a form FoxPro understands, you can use
the Expression Builder. The Expression Builder dialog pops up whenever
you need it.
106 Part I: FoxPro Fundamentals

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

SUM QTY_ONHND FOR COST > 4.00

This command is simply a sentence telling FoxPro what to do and how to


do it. SUM is the verb of the sentence, telling FoxPro what to do.
QTY_ONHND is the object. FoxPro is to sum the QTY_ONHND fields.
FOR COST > 4.00 tells FoxPro what records to sum—those in which the
value in the cost field is greater than $4.

The expression is

COST > 4.00


For every record in the database, that expression will be either true (the
cost is greater than 4.00) or false (the cost is equal to or less than 4.00).
FoxPro will make that comparison for every record it encounters in the
database. If the expression is true for a record, FoxPro will add the
QTY_ONHND of that record to the total it is keeping. If the expression is
false, FoxPro will skip over it.

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

COUNT FOR ((LEFT(PART_NUM,2)="IN”) AND (QTY_ONHND = 0))

Although this expression is much more complicated, the principle is the


same. FoxPro will evaluate the expression to the right of the FOR for
every record in the database. If the expression is true for a record,
FoxPro will count the record; if the expression is false, FoxPro will skip
that record.

Building and Beginning Expressions


Eventually, you will become experienced enough to enter expressions
like the preceding from the Command window, but FoxPro provides the
Expression Builder dialog to ease the creation of all expressions. To open
the Expression Builder dialog, you need to give FoxPro a task that
requires an expression. In this section’s example, the INVNTRY database
Chapter 4: Sorting and Summarizing Data 107

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.

System File “Edit Expression

Fig. 4.5.
The Expression
FOR Clause: <expL> : q
Builder dialog.

Field Names: Database: Variables:

> PART_NUM INUNTRY > ALIGNMENT


KEYWORD
DESCR
SUPPLIER
QTY_ONHND
QTY_RORDER
PRICE
COST oo
=
Vige!
oe
Moe
ail
4A

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.

Obviously, this is a fairly easy example, but it illustrates the power of


building expressions. With expressions, you can search databases quickly.
To build more complicated expressions that slice the database into finer
and finer increments, you need to use some of FoxPro’s functions, the
topic of the next section.

Using FoxPro Functions


A FoxPro function is much like a “black box”; you put some piece of data
into it, the function does something with that data and returns some other
piece of data.
AVERAGE() and COUNT() also are functions, and they operate the same
way. FoxPro offers many functions, and you can use each to build an
expression. To see FoxPro functions, choose Sum from the Database menu
and then choose Expr to bring up the Expression Builder. You will see
four boxes, labeled Math, String, Logical, and Date. These are the four
categories of FoxPro functions. To see each of the functions, open up the
scrollable list for each as you review the categories. (Mouse users can
click in the box to open the scrollable list; keyboard users need to press
Alt-X to pull down the Expression menu and then choose the appropriate
function. )

In working with functions, you will encounter the word argument. An


argument is a value or series of values that the function needs in order to
do its job; arguments are placed inside the parentheses after the function
name. You will see arguments in the examples that follow.

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

REPLACE ALL field_name WITH UPPER(field_name)


where field_name is the name of the database field you want to convert.
With string functions, you also can strip off leading and trailing blank
spaces, remove certain parts of a string, or insert one string into another.
Some other useful string functions are ALLTRIM(string expression), which
returns a string stripped of leading and trailing blanks, and RIGHT(string
expression, numeric expression), which returns the rightmost number of
characters in the string. The number of characters is specified in the
numeric argument.

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

CDOW(<exprD>) returns a character string with the name of the day of


the week for the date specified as an argument. CMON does the same for
the name of the month.

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:

4 DTOC(date argument) returns a string representation of the


date. Then you can combine the string date with other strings
for printing and searching and indexing.

UY CTOD(string argument) takes a string argument in the form


mm/dd/yy and converts it to FoxPro’s internal date format, from
which you can calculate the day, month, and year differences
between dates and all FoxPro’s other date capabilities.

Now that you know the basics of functions, you can learn how to put
functions to use.

Using the For and While Clauses


To Limit Searches
For and While allow you to limit FoxPro’s processing of your database
based on the value of one or more of the fields in each record. Scope
limits the processing based on where records are in the database file, but
For and While can include or exclude records based on any expression
you can concoct. (You also can combine Scope with For and While
expressions, telling FoxPro, “Include only the records that meet both the
For and While expression and the Scope expression.’)
Chapter 4: Sorting and Summarizing Data J 1 J

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.

System File Edit. Database. Record -Program Window Browse

TAN Fig. 4.6.


BUSH The AGES
Davis database,
GENTRY :
GRIFFEY indexed on
B HESS Name.
JAMES
JAMISON
JERROLD
JOHNSON
MARK
0ZGO0D
PETERSON
SMITH
STEWART
WILSON
ZUMWALT

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

results in the sequence shown in figure 4.7.

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

WHILE age < 30

gives you the sequence shown in figure 4.8 and a result of 28.

As you can see, While depends completely on how the database is


indexed. If you index the AGE database on the Age field and issue the
SUM command on the same

WHILE age < 30

expression, you get the sequence shown in figure 4.9 and a result of 101.
eT
112 Part I: FoxPro Fundamentals

‘System File Edit Database Record Program Window Browse

Expression: FOR age < 38

Fig. 4.7. Start True, include it ——————» f WILSON «Start positioned


Processing the False, skip it ————————> f JAMES here
. False, skip it ————————> OZGOOD
expression FOR False, skip it ———————> | HESS
AGE < 30. False, skip it —————————> #f GENTRY
False, skip it ————————— Jf SMITH
True, include it ———————~» JOHNSON
False, skip it —————————> @ BUSH
False, skip it ————————— PETERSON
True, include it ———————> @ JAMISON
False, skip it ————————> ZUMUALT
True, include it ———————» J AJAX
False, skip it ————————> JERROLD
True, include it ——————— ff DAVIS
False, skip it ————————> STEWART
False, skip it —————————> MARK
True, include it ———————» @f GRIFFEY

Expression: WHILE age < 38

Fig. 4.8. Start True, include it ——————> [Iasax


Processing the qe stop processing ————»> § BUSH positioned
expression Davis
GENTRY
oe
WHILE AGE GRIFFEY
< 30. HESS
JAMES
JAMISON
JERROLD
JOHNSON
MARK
O0ZGOOD
PETERSON
SMITH
STEWART
WILSON
ZUMWALT

If you’re working with a large database, searching and summarizing with a


For clause can take a long time, because FoxPro and FoxBase+ must look
at each record and evaluate the expression for it before deciding whether
to include the record. Even if only one record in the entire database will
pass, every record is checked. If you find yourself in this situation, use the
following trick.

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

System File Edit. Database Record Program Window Browse

Expression: WHILE age < 38

Start True, include — JAMISON Fig. 4.9.


True, include i DAVIS positioned Using WHILE to
True, include i WILSON here
True, include i GRIFFEY : PIGCES the AGES
True, include JOHNSON database,
True, include AJAX indexed by Age.
False, stop processing —————> [§ STEWART
MARK
JAMES
JERROLD
0ZGOOD
PETERSON
ZUMWALT
HESS
GENTRY
BUSH
SMITH

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.

System File Edit. Database Record Program Window Browse

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

Using Memory Variables To Store


and Display Information
Often you will find that you want to save the value of a summed field, a
count, or an average and use it later. FoxPro provides the means to store
values (numeric, logical, date, and string) and reuse those values later.
Memory variables are the tools you use for this purpose.
A memory variable is much like a home’s mail slot at the post office. It has
a name and holds something—in FoxPro’s case, a number, string, logical
value, or date. You create a memory variable simply by assigning a value
to it. Figure 4.11 shows the FoxPro screen as you assign values to memory
variables in the Command window. FoxPro shows the results of these
actions in the upper left corner of the screen.

Mteiacn File Edit Database Record Program Window


1880
Mannie the Fish
Sie Command
Fig. 4.11. 83/24/46 iny_val = 1088
Assigning values name = “Mannie the Fish”
isesulle—waTs
to memory birthday = CTOD("@3/24/46")
variables.

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:

SUM QTY_ONHND FOR COST > 4.00 TO TOT.ONHND

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 result is 34588.


Chapter 4: Sorting and Summarizing Data 1 J 5

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:

INV_VAL = 1000 (creates a numeric variable)


INV_VAL = "Zip” (creates a character variable)
You cannot combine different memory variable types. Figure 4.12 shows a
correct way to add memory variables, and figure 4.13 shows an incorrect
way to add memory variables.

System File, Edit Database’ Record. Program Window

° Command
= 1080 Fig. 4.12.
2008 Adding memory
inv_val + add_amt ; variables.

System File Edit Database Record Program Window


1088
2008

Fig. 4.13.
Command .
i HOMUAT Adding memory
add_amt variables of
add_amt : ;
? inv_val + add_amt differing types.

Operator/operand type mismatch.


1 16 Part I: FoxPro Fundamentals

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)

Memory variables are absolutely essential for programming in FoxPro (as


they are in all computer programming languages), but you will find them
useful in all FoxPro and FoxBase+ operations. As soon as you find your-
self entering some value repeatedly, think about assigning that value to a
memory variable with a shorter name; from then on, you can use the
memory variable and be assured that you aren’t making a mistake entering
the value.

Rearranging the Database


You often will be adding records to and deleting records from your
databases. And seldom, if ever, will the database remain in the same logi-
cal order after you add and delete records. For example, if you started out
entering records alphabetically because that’s how you want to see them,
the first time you add a record, you will have a problem. FoxPro, like just
about all databases, adds new records to the end of the file. When you add
the AAAAA Zebra Company to your customer database, however, you
need some way to make it the first record—or at least appear to be the
first record. FoxPro provides two ways to order your database: sorting and
indexing.

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

System File Edit -Database Record Program Window

Database Fields: Sort Order: Fig. 4.14.

PART_NUM « Move 4 > The Sort dialog.


KEYWORD
DESCR < Remove >
SUPPLIER
QTY_ONHND Field Options
QTY_RORDER (+) Ascending
PRICE ( ) Descending
COST { ] Ignore Case
AUTO_RORDR Ai
She
Seer
peli
or
bal
Moo)
oe
A FD
ONNDTOTAORT0

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.

System File Edit Database Record Program Window

Database Fields: Sort Order: Fig. 4.15.


The completed
PART_NUM « Move + > t INUNTRY->SUPPLIER Sort dial -
KEYWORD 1 INUNTRY->PART_NUM nos. with
DESCR « Remove > a two-field sort.
SUPPLIER
QTY_ONHND Field Options
QTY_RORDER (+) Ascending
PRICE ( ) Descending
COST {C ] Ignore Case
AUTO_RORDR (Se
Se
Sil
a
eer
oe
9ee ®
MPNNDTWOOVEAVAE

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.

System RTRs Utes ey eyeersto

if " . FOR Clause: <expL>


he ULES EL inuntry->part_num = “IN”
Builder.

Field Names: Database: Variables:

> PART_NUM INUNTRY »ADD_AMT


KEYWORD INU_AMT
DESCR TOT_AMT
SUPPLIER < Verify > INU_VAL
QTY_ONHND ALIGNMENT
QTY_RORDER « OK »
PRICE
COST ee)
alse
hse
sex)
Sh
aoe
ar
ee
& « Cancel > a)
Sh
Su
<i>
pe
se
Salil
Ad
m6

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.

Warning: | Because FoxPro and FoxBase+ physically create the


sorted file, plus possibly some intermediate files, a sort
can take a great deal of disk space. You need to have free
disk space equal to at least the size of the database you’re
sorting. When the sort is done, you get the free space
back, but running short in the middle of the sort causes
the process to stop. Also, sorts can take a long time, even
Chapter 4: Sorting and Summarizing Data 1 19

for FoxPro and FoxBase + , which have well-deserved rep-


utations for being faster than competitive database pro-
grams. The length of the sort depends on how long the
sort key is, how long the database records are, and, most
of all, how big the database is. The INVNTRY database
used as an example in this book is about 19,000 records
long; sorting on the PART_NUM field takes FoxPro about
1 minute and 40 seconds on an 80386, 20 MHz com-
puter. Compare that number with about 23 seconds
for indexing it on the same field, and you see why sorting
is seldom required.

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

An example of the index file for such a database, indexed alphabetically,


follows:

(the first alphabetical record is #1)


(the second alphabetical record is #7)
(the third is #3)
(the fourth is #5)
(the fifth is #6)
Ie (the sixth
ONDWWwW is #9)
120 Part I: FoxPro Fundamentals

8 (the seventh is #8)


2 (the eighth is #2)
4 (the ninth is #4)
To present this database in alphabetical order, FoxPro would look at the
index file and use the order of the indexes to present the database:
database record 1 first, record 7 second, record 3 third, and so on. To the
user, the database appears to be in alphabetical order, because there is no
appreciable delay in FoxPro getting the index first and then listing the
correct record.

Indexing versus Sorting: Which Is Better?


Indexing is almost always the better choice. You can have up to seven
different indexes open at one time on a database file, so you can have
seven different ways of looking at the database simply by changing which
index “controls” the database. If you need more ways, you can simply cre-
ate the indexes and update them as necessary. While an index is open,
whether controlling or not, any changes to its key fields automatically
update the index file. In the preceding example, changing the AAA Com-
pany to the MMM Company would automatically update the index and
rearrange the presentation. Such updating of open index files is almost
instantaneous.

Creating a new index is much faster than sorting; FoxPro and FoxBase +
are superior performers in indexing.

Are there advantages to sorting? Arranging an index in descending order is


a difficult—but not impossible —task, but arranging a database in descend-
ing order is easily done with a sort. Sorted database files don’t need index
files, but they do need to be sorted each time the sort field changes.
In short, opt for sorting only if you cannot make indexing accomplish
what you need. In years of developing FoxBase + and FoxPro applications,
I have included only one sort.

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

System .File Edit Database Record Program Window

Database: INUNTRY Fig. 4.17.


Structure: <Modify> Indexes: The Setup dialog.
> PART_NUM
KEYWORD
DESCR
SUPPLIER
Fields: 18 Length: 113 Index expr:
Index filter:
C J Set Fields...
€ >) On G*: OFF
C J] Filter...
{C ] Format...

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.

System File Edit. Database Record Program Window

Fig. 4.18.
Open Index File:
The Open Index
Drive File dialog.

Directory

« Open »

< New >

« Cancel >
{ 1 All Files
122 Part I: FoxPro Fundamentals

FoxPro responds to your request by bringing forward the Index On dialog


(see fig. 4.19). Here you tell FoxPro which fields and expressions to use
in creating the index. If you want to simply index on fields in the
database, clicking on the fields in the field picker window adds them to
the index expression. If you need to define a more complex expression,
click on Expr.

System File Edit Database Record -Program Window

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 familiar Expression Builder dialog appears (see fig. 4.20).

System File Edit Expression

The Index On INDEX ON: ‘expr?


Expression inuntry->supplier + inyntry->part_num_
Builder.

Field Names: Database: Variables:

> PART_NUM INUNTRY > TNU_VAL


KEYWORD NAME
DESCR IS_FULL
SUPPLIER « Verify BIRTHDAY
QTY_ONHND ADD_AMT
QTY_RORDER « TOT_AMT
PRICE _ALIGNMENT
COST ale
aw
ay
&
ee}
i
oe
ahe « Cancel _BOX fit
op
al
Nt
Lem
4s)
pele
si
Chapter 4: Sorting and Summarizing Data 123

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

SUPPLIER + PART. NUM

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

SUPPLIER + STR(QTY_ONHND * COST)

Here, you convert the inventory value (QTY_ONHND * COST) to a char-


acter string by using the STR() function in order to combine it with the
character string SUPPLIER. Remember, you cannot combine expressions
of different types.

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

= eports are the most visible part of your database, particularly to


= other people who will use them. If your reports are clear and under-
standable, your database will be far more usable. On the other hand, if
your reports are muddled and difficult to read and understand, the most
elegant database design will be for naught. Reports from computer sys-
tems have to be good or you might as well not develop the system.

It used to be true that the only thing comparable to the importance of


good reports was the tedium of creating them. In the old days, program-
mers laid out the report format on a sheet of grid paper, and then trans-
lated the rows and columns of the report to programming code; if you
wanted to change the report, the program code had to be changed. With
FoxPro, you can create elegant, understandable reports with a minimum
of effort.
In this chapter, you learn how to use FoxPro’s Layout window to define
and create reports on your databases. First, you will see how simple
reports are created using just database fields and some basic titles. Then,
you move on to more useful reports, in which you add boxes and lines to
emphasize important data, and use FoxPro’s built-in functions to provide
date and time stamping of reports.

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.

The basic process of report writing in FoxPro is designing your report in


the Layout window, putting fields and text where you want them on the
report, and then running the report from the Database menu.

125
126 Part I: FoxPro Fundamentals

Using the Layout Window


To open a new report, make sure that the database on which you want to
report is opened and that the proper index controls it. To continue the
example from earlier chapters, make sure that INVNTRY is opened and
the PART_ NUM index is controlling. This ensures that your report will be
in the right order. Choose New from the File menu, and then select
Report and OK. FoxPro presents the Layout window, which is the basis for
report design (see fig. 5.1).

System File Edit Database. Record Program. Window Report


2 UNTITLED.FRX
Ri: @C: @ Page Header
PgHead _
Fig. 5.1. PgHead
PgHead
The Layout PgHead
window. Detail
Detail
Detail
Detail
PgFoot
PgFoot
PgFoot
PgFoot

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.

Next, you will create a report on the Layout screen.

Creating a Simple Report


The first step in creating a report is to put the database fields you want
reported into the Detail band. Move the cursor to the Detail band and
place the cursor where you want your first field, using the arrow keys or
by clicking the band with the mouse. Now, from the Report menu, choose
Field or press Ctrl-F. FoxPro displays the Report Expression dialog (see
fig. 5.2). In this dialog, you tell FoxPro information about a field you’re
placing in the Layout window and how to format that field.

System File Edit Database Record Program Window Report


UNTITLED. FRX”
Detail

Fig. 5.2.
The Report
Report Expression: Expression

« Expr... ? dialog.

<« Format... > Width: 7)

EJ Style... Eo Stretch Vertically


{C 1]Totaling... C 1] Suppress Repeated Values
{ ] Float as Band Stretches

<« Cancel >

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

System File Edit Expression


UNTITLED.
FRX

The Expression |
Report ‘expr>: |
Builder.

Field Names: Database: Variables:

> PART_NUM INUNTRY > ALIGNMENT


KEYWORD
DESCR
SUPPLIER LMARGIN
QTY_ONHND PADUANCE
QTY_RORDER PAGENO
PRICE PBPAGE
te
Pe
eile)
elt
ail
4 PCOLNO eae
ae
Te
4)
AJ

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.

Adding Database Fields


Suppose that you want the PART_NUM field to be on the layout; choose
PART_NUM from the scrollable list to place the field in the Expression
Builder. Select OK to return to the Report Expression dialog. The Expr text
box now has the field INVNTRY—>PART_NUM in it. Choose OK again to
return to the layout. When you return to the Layout window, you see a
field with the PART_NUM identification on-screen where the cursor was
located (see fig. 5.4).

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.

Using Objects on the Layout View


FoxPro treats everything you put on the Layout window as an object. You
can add objects, delete objects, and move them around. For objects that
contain text (database or calculated fields, or text such as titles and
labels), you can assign character styles, such as underline, bold, and italic.
To change the format of your report, you simply add objects and move
objects already created.
Chapter 5: Creating Reports in FoxPro 129

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

System File Edit Database Record Program Window Report


UNTITLED.
FRX:

Fig. 5.5.
The Layout
Mi are
basic report.

Using Page Preview


FoxPro’s Page Preview feature makes viewing your report creation a snap.
Choose Page Preview from the Report menu; FoxPro shows you what
your report will look like if you were to save and run it right now. Figure
5.6 shows your example report as it now is defined.
ee

1 40 Part I: FoxPro Fundamentals

System File Edit Database Record Program Window. Report


ba Preview

AC 4715349-3 BEARING BEARING (DEADLINE 48%


Fig. 5.6.
Page preview of
the report as PACKING PACKING KIT (DEADLINE 407
defined.
BEARING BEARING (DEADLINE 487%

REGULATOR REGULATOR (DEADLINE 467%

KIT KIT (DEADLINE 48%

« Done » < More > Column: 8

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

Adding and Deleting Lines in a Report


FoxPro makes some assumptions about how many lines you want in the
different bands of the report. Initially, all bands have four lines. You can
change this default by placing the cursor in the band and selecting Add
Line or Remove Line from the Report menu. Figure 5.7 shows the Layout
view with the excess lines deleted from the Detail band to make the
report more concise.

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

System File Edit Database: Record Program ‘Window Report


e : UNTITLED, FRX :
Page Header

Fig. 5.7.
ad The Layout
Detail
PgFoot
screen with
PgFoot excess Detail
PgFoot Bands removed.
PgFoot

Adding a Computed Field


You probably realize that adding a computed field is just a matter of plac-
ing a field object on the Layout view and telling FoxPro how to calculate
the value in an expression. In the example, a calculated field, total value
(which is the QTY_ONHND field multiplied by the cost field), has been
added. After placing the cursor at the desired location in the Detail band
and choosing Field from the Report menu, choose Expr to display the
Expression Builder dialog.

In the Expression Builder box, enter

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.

Adding a Page Header or Footer


To add a page header or footer, you place objects in those bands. Any
objects in the PgHead band are printed at the top of each page of the
report, and objects in the PgFoot band are printed at the bottom of the
page. Later you will learn how to add objects that will be printed just
once at the beginning of the report or just once at the end.
132 Part I: FoxPro Fundamentals

System File Edit Expression


UNTITLED. FRX

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:

PART_NUM Cc > ALIGNMENT Cc


KEYWORD G _BOX L
DESCR Cc _INDENT N
SUPPLIER C _LMARGIN N
QTY_ONHND N _PADVANCE G
QTY_RORDER | N _PAGENO N
PRICE N _PBPAGE N
>COST N _PCOLNO N

System File Edit Database Record Program Window Report


2 Preview

49715349-9 BEARING BEARING (DEADLINE


Fi 4998799 PACKING PACKING KIT (DEADLINE
ig. 5.9. 081999 BEARING | BEARING ( DEADLINE
Page preview of 185719 REGULATOR REGULATOR (DEADLINE
th 4 ‘ 186668 KIT KIT (DEADLINE
e report with a 187329 RESISTER RESISTER (DEADLINE
calculated Sield. 108228 TUBE TUBE (DEADLINE
113158 LOCK LOCK RING (DEADLINE
1ZAL39SP LATCH LATCH (DEADLINE
GESCR1S9 BOARD BOARD (DEADLINE
CYLINDER CYLINDER (DEADLINE
SWITCH (DEADLINE
SPRING (DEADLINE
(DEADLINE
(DEADLINE
(DEADLINE DENANERRENNN
rPONEF

287489 SHAFT (DEADLINE


113838 BUSHING BUSHING (DEADLINE
« Done » < More > Column:

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

System File Edit Database Record Program Window - Report


O 5 UNTITLED.FRX
Heo ANTES Se Move Page Header
PgHead
PgHead 5 Inventory Report :
PoHead = Fig. 5.10.
patens —s A title added to
etai
Bl PoFoot keyword | x) SS the Layout
PgFoot window.
PgFoot
PgFoot

Formatting Fields on the Report


Fields can be formatted and styled. Formatting refers to how characters
are presented on-screen. To change the formatting of a field, place the
cursor on the field and press Enter; mouse users should double-click the
field. FoxPro will display the Field dialog. In the Format text box, you can
specify Function codes and Picture Template codes, just as you did when
creating a data-entry screen. You also can click the Format box, which
displays a dialog to help you create formats.

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

System’ File Edit Database Record Program Window. Report


: : UNTITLED.
FRX
Page Header

Fig. 5.11. Inventory Report


The Style dialog.

Normal
Bold
Italic «
Underline
Subscript « Cancel >
Superscript
Condensed
Double

Adding Page Headers and Footers


Another common use of objects in the PgHead band is for column head-
ings. Place text objects, describing each column, in the bottom row of the
PgHead band. Move them as necessary. This causes the column headings
to be printed once on each page, just above the first line of data from
your database. Figure 5.12 shows the column headings after they are
added to the Layout. The resulting page preview is shown in figure 5.13.

System File Edit .Database Record Program ‘Window .Report


UNTITLED.FRX
Page Header

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

System File Edit Database. Record Program Window Report


2 : Preview

Inyentory Report Fig 5 B

Part Number Keyword Description Page preview


MAC 4715349-9 BEARING BEARING (DEADLINE
ixAC 4998799 PACKING PACKING KIT (DEADLINE with column
xBA 881999 BEARING BEARING (DEADLINE headings.
BA 185719 REGULATOR REGULATOR (DEADLINE
BA 186668 KIT KIT (DEADLINE
BA 187329 RESISTER RESISTER (DEADLINE
188228 TUBE TUBE (DEADLINE
113158 LOCK LOCK RING (DEADLINE
BA 1ZAL39SP_ —LATCH LATCH ( DEADLINE
BA GESCR159 BOARD BOARD (DEADLINE
BA HRB1A CYLINDER CYLINDER (DEADLINE
KB S361ZEE SWITCH SWITCH (DEADLINE BREFNNNRFPRFPRENNN

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

System File Edit Expression


UNTITLED.
FRX

Fig. 5.14.
Adding the Report ‘expr>:
_pageno variable ilj] |_pageno
in the Expression
Builder.
Field Names: Database: Variables:

> PART_NUM _ALIGNMENT


KEYWORD BOX
DESCR _INDENT
SUPPLIER « Verify _LMARGIN
QTY_ONHND _PADVANCE
QTY_RORDER « _PAGENO
PRICE _PBPAGE
« Cancel _PCOLNO

System File Edit Database Record Program Window Report


2 UNTITLED.
FRX
RSs Ceite Page Header
PgHead
Fig. 5.15. PgHead Inventory Report
f . PgHead
Adding a page PgHead Part Number Keyword Description Qty Cost
number to the Detail ;
report
iu,
on Layout.
Ae
PgFoot
PgFoot
Page: Misia
PgFoot
PgFoot

BA GESCR1S9 BOARD BOARD (DEADLINE 487


BA HRB1A CYLINDER CYLINDER (DEADLINE 487%
BA S361ZEE SWITCH SWITCH (DEADLINE 487%

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

System File Edit


. Database Record: Program Window Report
Ld Preview

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.

Adding Summary Fields in the Summary Band


As you may have guessed, summary fields are simply objects. You place
the cursor in the Summary band and choose Field from the Report Menu
to bring forward the Report Expression dialog. Place an X in the Totaling
check box to tell FoxPro that this field will contain information totaled
from the report. FoxPro displays the Totaling dialog, in which you enter
information about the totaling field (see fig. 5.18).

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

System File Edit Database Record Program Window Report


3 UNTITLED.
FRX
R: 18 C: 29 Summary
Title Inventory Report, sorted by Part Number
Fig. 5.17. PgHead
The Report Title Poliend
PgHead
dialog. PgHead Keyword |} Report Title: st.) EXts cost
Detail il |
PgFoot [CX] Title Band
PgFoot [X] New Page
PgFoot »
PgFoot
Summary *** End of Report Summary: < Cancel >

CX] Summary Band


CX] New Page

System File Edit Database Record Program Window Report


UNTITLED.
FRX
R: 18 C: 20 Summary
Title Inventory Report, sorted by Part Number
- PgHead.
Fig. 5.18. PgHead

The Totaling PgHead


é PgHead
dialog. Detail Reset:
PgFoot
PgFoot
PgFoot Total: +) None « OK »
PgFoot Count
Summary Sum « Cancel >
Average
Lowest
Highest

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

System File Edit .Expression


2 UNTITLED..FRX

Report <expr>: Using the


invntry->qty_onhnd_ | Expression

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.

Although the numbers are right, their formatting leaves something to be


desired. You can change the formatting in the Format dialog. You display
the Format dialog by double-clicking in the field or by moving the cursor
to the field with the arrow keys and pressing Enter. Then select Format in
the Report Expression dialog. Figure 5.21 shows the Format dialog for the
summed QTY_ONHND field. In the Format text box, place five 9’s, which
tell FoxPro to use a five-digit number with no decimal places to format
this field.
140 Part I: FoxPro Fundamentals

System. File Edit Database Record Program Window .Report


Ld Preview

Fig. 5.20.
The end of the
Totals:
report, showing
the summed
fields.

« Done » <« More > Column:

System File Edit. Database Record Program Window. Report


UNTITLED.FRX
R: 18 C: 53 Summary
Title Inventory Report, sorted by Part Number
z PgHead
Fig. 5.21. PgHead
Formatting the PgHead Format: Editing Options:
PgHead 39993 __ xt. Cost
total Detail C Left Justify Wt ry—>qty}
OTY_ONHND PgFoot ( ) Character (+) Numeric C Blank if Zero
oid PgFoot ( ) Date ( ) Logical C (Negative)
Sield. PgFoot C Edit “SET” Date
PgFoot C British Date
Summary por C CR if Positive unites) |
c DB if Negative |
C Leading Zeros
C Currency
< Cancel > C Scientific

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

System File Edit “Database Record Program Window: Report


UNTITLED.FRX
R: 18 C: 68 Summary
Title Inventory Report, sorted by Part Number #
PgHead 3 ;
PgHead Fig. 3.22.
PgHead Format: Editing Options: Formatting the
PgHead 999799959 xt. Cost total
C Left Justify una ce) cs
( ) Character (+) Numeric [ Blank if Zero QTY_ONHND *
( ) Date € ) Logical E
C
(Negative?
Edit “SET” Date
COST field.
C British Date
{C 1 CR if Positive un (Satine)
[ DB if Negative
[ Leading Zeros
C Currency
« Cancel > C Scientific

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.

ystem. File Edit Database Record Program. Window Report


UNTITLED.
FRX
RENZIC235 Page Header
Title Inventory Report, sorted by Part Number #
cas
PgHead Inventory Report
:i Fig.§ 5
5.23.
3.
PgHead i Layout view of
PgHead Keyword Description Oty Cost Ext. Cost the completed
Detail keyword | iqty_o—cost.
—- Minuntry- qty é
PgFoot a inventory report.
PgFoot
PgFoot
PgFoot
Summary port Totals: inuntry->qty
142 Part I: FoxPro Fundamentals

System File Edit Database. Record Program Window Report


Preview

Fig. 5.24.
The end of the
report, showing
the formatted Totals:
fields.

« Done » < More > Column: 7)

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.

Running the Report


To run your report, choose Report from the Database menu, and choose
from the File Picker scrollable list the name of your report. (You must
choose Report in the Type scrollable list to see your report in the File
Picker window.) Notice that you can limit what records your report pro-
cesses with Scope, For, and While options. Figure 5.25 shows the Report
dialog you will use to start your report running.
You remember from the previous chapter how to use Scope, For, and
While to limit what is processed in a database. These clauses apply to
Report processing as well. If you want to limit your report to a certain
number of records, based on their location in the database and the cur-
rent position of the database pointer, use the Scope option. If you want to
look at certain records, based on values in the fields, use the For option to
limit the report processing to just those records. Use While to limit pro-
cessing to records with a certain value in a field starting from the current
position.
Chapter 5: Creating Reports in FoxPro 14 4

System File Edit -Database Record Program Window

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:

ALL All records in the database will be processed for the


report.
Next Choosing this option opens a data-entry box, in which
you enter a number that represents how many database
records you want the report to process, starting from the
current record in the database. If the current record in
the database pointer is in the middle of the database and
you enter 100 in the Next field, your report will process
the next 100 records and end.

Record Choosing this option also opens a data-entry box, in


which you enter the record number of the record you
want processed. In this case, your report will report only
on that one record.

Rest Choosing this option causes your report to start at the


current location in the database and process all the
remaining records.
144 Part I: FoxPro Fundamentals

Creating More Advanced Reports


Now that you have created a simple report, you’re ready to move on to a
more advanced one. In the next report, shown in figure 5.26, you will add
boxes and lines to improve the readability, group the data to generate
subtotals and make the report easier to understand, and add an object to
print out a memo field. When you have mastered these facets of FoxPro
reporting, you will be able to create superior reports, becoming a verita-
ble Michelangelo of the Layout window.

ystem File Edit Database. Record Program Window Report


“Preview

An advanced Part Number Keyword Description Qty Cost Ext. Cost!


report. IME 48568-78
omments:
se
This part no longer
“C" WASHER
available. Use part IN
8 8.68 8.

34423 instead.

IE WMP1-88 bileal “C’ WASHER


(Comments: This part no longer available. Currently,
no replacement part numbers are known to
work in its place. Customers wanting to
order this part must be notified

Keyword Totals

Page:

« Done » < More >» Column: 8

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.

Adding Groups and Subtotals


In nearly every database, the records can be grouped logically. In the
INVNTRY database, for example, you could group the records by the key-
word, contained in the KEYWORD field. When reporting on the INVNTRY
database, it would be beneficial to group the records by that keyword, to
have a subtotal of the QTY_ONHND fields, and to have a computed subto-
tal of QTY-ONHND multiplied by cost to show how many of each key-
word is in inventory, and what the value of that keyword type’s inventory
Chapter 5: Creating Reports in FoxPro 145

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.

System File Edit Database Record Program Window Report


CHAPS. FRX

Inventory Report, sorted by Part Number

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

System File Edit Database Record Program Window Report


i CHAPS. FRX

Inventory Report, sorted by Part Number


Fig. 5.28.
The Group Info
dialog.
Group Info:

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

System File Edit Database Record Program. Window Browse


a INUNTRY =

Start here 18588 DASH DASH POT


Fig. 5.29. First group ———— 1868-K DASH DASH POT
Progressing 1868K DASH DASH POT
Dir b New aby Er a 9317-8 DIAPHRAGM |DIAPHRAGM, PRIMARY R
through a start new group 4184-198 |DIAPHRAM |DIAPHRAM ASSY
database New KEYWORD, 58758-88 : DIFF. BEARING CAPS D
. start new group 5875Z-59 a
grouping on 40235
KEYWORD. New KEYWORD, 58911-59
start new group 88869
995829
GE-1878
GE-1169
GE-1218
GE-1268

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.

In this example, a new index is created, based on the index expression

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

System File Edit Database Record Program Window Report


CHAPS. FRX

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

System. File Edit Database Record Program Window Report


2 CHAPS. FRX
Ree SCeesZ Group Header
Title Inventory Report, sorted by Part Number
; PgHead
Fig. 5.31. : PgHead Inventory Report
The Layout view PgHead
with a
group on PgHead ®Part Number Keyword Description Qty Cost
, e r 1-keywo EL
KEYWORD. ri-keywo Keyword: [inst
Detail &
Li-keywo
3
PgFoot
PgFoot Page:
PgFoot
PgFoot
Summary *** End of report Totals:

System File Edit Database Record Program Window


Preview
Z WAY VALUE
° eyword: Z-FLUID
Fig. 5.32., ICO @2-468-238 Z-FLUID §_Z2-FLUID POWER BRAKE VALVE
Page Preview
with the report eras
grouped on 24U COIL
KEYWORD 24 CONTACTOR

ZND COUNTERSHAT & CLUTCH

3 WAY VALVE

36-48 36-48V COIL


36-48 36-48V COIL
36-48 36-48 COIL
Done » < More > Column: 8

Adding a Group Summary Field


Often, you will want to summarize information at the group level, receiv-
ing subtotals of numeric fields in the group, or counts of the records
printed in the group. Group summary fields are defined and placed in the
Group Footer band in the same manner as you defined and placed report
summary fields.
Chapter 5: Creating Reports in FoxPro 149

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.

System File Edit Database. Record Program Window Report


CHAPS, FRX

Inventory Report, sorted by Part Number


Fig. 5.33.
Setting Reset on
a totaling field
inuvntry->keyw
ri-keywo Keyw
| to the grouping
Detail expression.
Li-keywo Keyw None « OK »
PgFoot Count
PgFoot Page Sum « Cancel >
PgFoot Average
PgFoot Lowest
Summary *** Highest

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

System File Edit Database Record Program Window Report


= : CHAPS. FRX
Re 8°02 38 Group Footer
Title Inventory Report, sorted by Part Number
PgHead .
Potiead Inventory Report Fig. 5.34.
PgHead Layout of the
PgHead &Part Number Keyuord Description Qty Cost report with a
1-keywo
T1-keyuo Keyvord: Paring group summary
Detail SEI
Li-keyuo Keyword Totals Qian
aty_d :
field.
PgFoot
PgFoot Page:
PgFoot
PgFoot
Summary *** End of report Totals:
1 50 Part I: FoxPro Fundamentals

Systen File Edit Database

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

System File Edit Database Record Program Window Report


= CHAPS. FRX
R: 3.C: 58 Page Header
Title Inventory Report, sorted by Part Number
PgHead
PgHead Inventory Report Fig. 5.36.
PgHead Layout of the
PgHead #Part Number Keyvord Description Qty Cost
rl—keywo report with lines
and boxes added.
Keyword Totals
aty_o
qty_o

Summary 0 End of report Totals: qty

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

System File Edit Database Record Program Window Report


Preview

Inventory Report Fig. 5.37.


Description Qty Cost Ext. Cost
Page preview of
the report with
lines and boxes
9/16-18 THREAD NUT
Keyword Totals added.

398 DEGREE SWIVEL


3@ DEGREE STREET ELBOW
98 DEGREE ELBOW LONG
98 BULKHEAD UNION ELBOW
38 DEGREE ELBOW

« Done » < More > Column:


1 52 Part I: FoxPro

Adding Memo Fields


You also can add a
important capability hand ~
fields. A memo field, you will remember. be 2S bre as OOO charac

aan 4 feng time rae © Frot 3


Wrapped from hme to line, so that no
6 “ean Bisel ee Red
Once you have 2aGGgded 2 memo held.
(see fig eg ) tice that the memp
= Riese G2ER Lith iit

“mM mntate tho


to accommodate the

System - File e t Pree Winden Repert

Sorted 24

Ne
mire—connents | See SISAL
oa ane i NAa
Chapter 5: Creating Reports in FoxPro 1 53

Systen File Edit Database Record Program Window Report


; Preview

Keyuord Description ‘ Page preview of


c C” WASHER a] : a report using
* This part no longer available. Use part IN
34423 instead. Stretch
Vertically.
E WHP1-88 rc. “C” WASHER
* This part no longer available. Currently,
no replacement part numbers are known to
work in ite place. Customers wanting to
order this part must be notified

Keyword Totals

«< Done » *¢ More » Column:

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

Quick Start 2: Tapping the Power of FoxPro

Designing, Defining, and Creating Relational Databases

Entering Data with FoxView

Managing Multiple-File Databases

Creating Custom Reports


1 56 Part II: Intermediate FoxPro
Quick
Start

Tapping the Power


of FoxPro
o far, you have used FoxPro as a sophisticated file manager, working
=U with only one database file at a time. You have learned the basics of
FoxPro—defining databases, creating data-entry screens and reports, and
looking at the data in many different ways. Now, it’s time to tap FoxPro’s
power. FoxPro is a relational database system, and this section of Using
FoxPro teaches you the why’s and how’s of FoxPro’s relational capa-
bilities. When you’re finished with Part II, you will understand how the
relational power of FoxPro, combined with its extraordinary ease-of-use,
makes this program the most powerful and capable database program in
the PC world.

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

database, this database will reside in the subdirectory \FOXPRO\CUST, so


move to that directory by issuing the MS-DOS command

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.

In Quick Start 1, you created a CUSTOMER database, the structure of


which is shown in figure QS2.1.

System File Edit Database Record Program Window


Structure for database: C:\FOXPRO\CUST\CUSTOMER.
DBF
Number of data records: 15
Date of last update +: 82/28/98
Fig. QS2.1. Field Field Name Type Width Dec
The structure of CUST_NAME Character
ADDR_1 Character
the CUSTOMER ADDR_Z Character
database. CITY Character
STATE Character
ZIP Character
PHONE Character
CONTACT
DANOUW
DWN Character
CREDIT Numeric
LAST_PUR Date
LAST_AMT Numeric
PREFERD Logical
** Total xx

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

mYestne File Edit Database Record Program Window


Structure for database: C:\FOXPRO\CUST\CONTACT.
DBF
Number of data records: 13
Date of last update : B1728/98
Field Field Name Type * Width Fig. QS2.2.
CUST_NUM Character 6
CONT_DATE Date The structure of
SALESPERS Character the CONTACT
FOLLOW_DTE Date
CONT_RPT Memo database.
SALE_MADE Logical
x* Total xx

To create multiple file, related databases, follow these steps:

1. To create the CONTACT database, choose New from the File


menu. In the New dialog, select Database and OK, and then define
the database in the Structure dialog. Figure QS2.3 shows the
CONTACT database defined in the Structure dialog. When you’re
finished, select OK and name the new database CONTACT.

System File Edit “Structure

Fig. QS2.3.
Structure: C:\FOXPRO\CUST\CONTACT.
DBF The SUTACUT, e
Name Type Width Dec dialog, with the

CUST_NUM Character BONA :


CONT_DATE Date <Insert> database defined.
SALESPERS Character
FOLLOW_DTE Date <Delete>
CONT_RPT Memo
SALE_MADE Logical

«Cancel >

Fields: 6 Length: 37 Available: 3963


160 Part I: Intermediate FoxPro

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.

System File Edit Database -Record Program Window


13 records indexed

Fig. QS2.4.
The View dialog,
showing the « View > Work Areas « Relations >

CONTACT <On/0ff> + CONTACT.


database in work
«Files >
area A.
anisce>

<Setup >

<Browse>

< Open >

<Close > |CONTACT Records: 13

If CONTACT is not in work area A, select work area A, choose


Open and pick CONTACT in the File Open dialog that appears. If, for
some reason, CONTACT is in a work area other than A, select
CONTACT and Close, and then select work area A and reopen
CONTACT in that work area with the Open dialog.
Quick Start 2: Tapping the Power of FoxPro 161

2. Select work area B. Because no database is in that work area, the


File Open dialog appears; pick the CUSTOMER database you
created in Quick Start 1. When you return to the View window, it
will look like figure QS2.5.

System File Edit Database Record Program Window


13 records indexed

Fig. QS2.5.
The View
« View > Work Areas « Relations > window, with the

<On/Off> “CONTACT CONTACT and


CUSTOMER
‘Files >
databases open.

§ <Setup >

«Browse >

< Open >

<Close » |CUSTOMER Records: 15

3. Open a Browse window on the CUSTOMER database by choosing


Browse from the Database menu. Return to the View window
(press Ctrl-F1 until the View window appears or select View from
the Window menu). Select the CONTACT database to make the
CONTACT databasethe active database, indicated by the active-
database symbol. Now, open a data-entry window on the
CONTACT database by choosing Append from the Record menu.
A data-entry window appears, and the screen looks like figure
QS82.6.
4. Clean up your screen by making the View window active and
choosing Hide from the Window menu. Next, make the Command
window active and do the same. Now, only the CUSTOMER
Browse window and the CONTACT data-entry window are on-
screen.
Select the CUSTOMER Browse window, then move and size it
until you can see the Browse window and the data-entry window
at the same time. Figure QS2.7 shows the screen with both
screens visible.
162 Part II: Intermediate FoxPro

System File Edit Database Record Program Window Browse


CUSTOMER
CONTACT

Fig. QS2.6.
The FoxPro
screen with a
Browse window
on the
CUSTOMER
database and a
CONTACT data-
entry window.

System File Edit Database Record Program Window . Browse


@ records indexed
CONTACT

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

5. Return to the CONTACT data-entry window by selecting it, and


enter records into the CONTACT database. To tie the two
databases together correctly, you must make sure that when
you're entering a customer’s name in the CONTACT database it
exactly matches the customer name as it exists in the CUSTOMER
database (differences in upper- and lowercase will not affect the
relation).
Quick Start 2: Tapping the Power of FoxPro 163

You can move from the CONTACT data-entry window to the


CUSTOMER Browse window by clicking in the CUSTOMER
window or pressing Ctrl-F1 until the CUSTOMER Browse window
is active. You can scroll to the record you want and return to the
data-entry window where you can enter the CUST_NAME field,
referring to the CUSTOMER Browse window to make sure that
the name is correct. Figure QS2.8 shows a record being entered in
the CONTACT database with the appropriate CUSTOMER record
in view in the CUSTOMER Browse window.

System File Edit Database Record Program Window Browse


@ records indexed
: CONTACT
Cust_name (Moye pep Es sts ts.
Fig. QS2.8.
Entering a
CONTACT record
Sale_made while the
CUSTOMER
record is visible.
CUSTOMER
nde
West Hill Florist 32981 Znd Ave So
Northvest Microsystems, In]18968 127th Pl

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.

The Copy command tells FoxPro to make a copy of what you


have highlighted and hold that copy in the computer’s memory.

7. Return to the CONTACT data-entry window by clicking it or


pressing Ctrl-F1. If the cursor is not in the CUST_NAME field,
move it there. Choose Paste from the Edit menu or press Ctrl-V
(the keyboard shortcut for Paste). FoxPro places in the field a
copy of what you highlighted in the CUST_NAME field of the
CUSTOMER Browse window. Figure QS2.9 shows this field pasted
into the CONTACT database. This is an excellent way to ensure
that the two fields match exactly.

System File Edit) Database Record. Program Window : Browse

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

8. Enter information into the CUST.NAME, CONT_DATE, SALESPERS,


and FOLLOW_DTE fields. When you reach the CONT_RPT field,
press Ctrl-PgDn. This field is a memo field, different from other
FoxPro data types in that it is unlimited in how much information
you can enter into it. Pressing Ctrl-PgDn opens a text-entry
window. In this window, you can enter descriptions that might
apply to a sales contact by a customer. Figure QS2.10 shows such
a window.
Quick Start 2: Tapping the Power of FoxPro 16 5

System File Edit Database Record Program Window


bl : CONTACT >CONT_RPT =

Fig. QS2.10.
A text-entry
window for
entering
information into
OMER the memo field,
[pct | | CONT. apr.
4923 Wilson Rd
Me) SouthCenter Mall

2 . When you have finished entering information into the text


window for the CONT_RPT field, press Ctrl-W, or click the
window-close symbol; you return to the data-entry window for
the CONTACT database.
10. Continue entering records into the CONTACT database. You
should enter CONTACT records for at least several different
customers, and more than one CONTACT record for two or three
of the customers. Figure QS2.11 shows a Browse window with
some records entered.

System File Edit Database Record Program Window Browse


ce) CONTACT =

Cosars Continent 11/38/89 Fig. QS2.11.


Hess Aviation Inventory -}}10/10/89 A 4
4) )
Metropolitan Corp 12/12/38 ibe Browse
Northend Music Lt window showing
OshKosh Cow Company 12/15/89 82/81/98 records in the
OshKosh Cow Company 03/81/89 12/30/89
8 SCIL 12/21/89 81/15/98 CONTACT
SCIL 81/15/98 database.
Studio 11 Art 82/15/98
T. Moore & Associates 18/31/89
West Hill Florist 83/29/98
West Hill Florist 12/29/89
166 Part II: Intermediate FoxPro

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.

You have now created and entered information into a multiple-file


database. So far, it has been much like using a single-file database, as in
Quick Start 1. To understand and use the real power of FoxPro, you must
tie the two databases together and learn how to draw information from
both at the same time.

Tying Together Two Databases


Each of the related databases must have a common field, which FoxPro
uses to tie the two together. Both the CONTACT and CUSTOMER
databases contain a CUST_NAME field. Once the relation between the two
is specified to FoxPro, the active record in the CUSTOMER database will
always be the record that has the same CUST_NAME as the active record
in the CONTACT database. To set the relation between the two databases
and see how this relationship works, do the following:

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.

System File Edit Database Record Program Window

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 >

<Close > {CONTACT Records: 14


Quick Start 2: Tapping the Power of FoxPro 167

2. Select work area B and open the CUSTOMER database in that


work area.

3. With the CUSTOMER database selected, choose Add from the


Open Index dialog. The CUSTOMER database must be indexed on
the field that ties it to CONTACT, and that index must be
controlling the order of the database. From the Open Index
dialog, select the CUSTNAME index created in Quick Start 1. If
this index does not exist, choose New and create an index on the
CUST_NAME field, naming it CUSTNAME.

HS Return to the View window by choosing OK in the Open Index


dialog.
5. Select the CONTACT database. A Browse window opens
automatically; close this Browse window (you don’t need it right
now). Click or select Relations. CONTACT appears at the top of
the Relations dialog, and an L-shaped arrow appears below it. The
View dialog now looks like figure QS2.13.

System File Edit Database’ Record Program Window


@ records indexed
1Z records added
Fig. QS2.13.
- Selecting
« View > Work Areas « Relations >» CONTACT as the

<On/0ff> Bea | CONTACT controlling


“CUSTOMER { |»L4 database in a
‘Files > relation.

“Setup >

«Browse?

< Open >

“Close >» |CONTACT Records: 14

6. Move back to the work area box and select CUSTOMER. An


Expression Builder dialog opens to receive information on what
field will tie CONTACT to CUSTOMER. Choose CUST_NAME. You
return to the View window, where CUSTOMER now appears in
the Relations box, as shown in figure QS2.14.
168 Part II: Intermediate FoxPro

System File Edit Database Record Program Window

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?

<« Open >

<Close > |CONTACT Records: 14

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:

1. Open a Browse window for each database. First, in the View


window, select CONTACT in the work area box, and then choose
Browse. Return to the View window without closing the
CONTACT Browse window. Select CUSTOMER in the work area
window and again select Browse. FoxPro opens a Browse window
on the CUSTOMER database.

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

System File Edit Database Record Program: Window Browse

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

3. Make the CONTACT Browse window active. Select a record in the


CONTACT database by clicking the record or moving the
highlight with the up- and down-arrow keys. Now make the
CUSTOMER Browse window active. You will see that the record
in the CUSTOMER database has the same CUST_NAME as the
record you selected in the CONTACT database. FoxPro has moved
the database pointer of the controlled database, CUSTOMER, so
that the value in the common field, CUST_NAME, is the same as
the value in CUST_NAME in the controlling database, CONTACT.
Figures QS2.16 and QS2.17 show this process in the two Browse
windows.

System File Edit Database Record Program Window Browse

CONTACT Fig. QS2.16.


Selecting a record
in CONTACT.
x

addr
“CUSTOMER

Oriental Cuisine 94432 International Ave


OshKosh Cow Company 5534 E. Dairy Rd
SE EEE EE

170 Part IJ: Intermediate FoxPro

System: File Edit Database “Record Program Window Browse

Fig. QS2.17. _ CONTACT:


The same
CUST_ NAME
record selected in
CUSTOMER.

- CUSTOMER

=
Moore & Associates ae
=
+4

4. Return to the CONTACT browse window and select another


record in the database. If you return to the CUSTOMER Browse
window, you can see that FoxPro has again matched the records
of the two databases.
5. Make the CUSTOMER Browse window active and select a record
in that database by clicking it or moving to it with the up- and
down-arrow keys. Now move to the CONTACT database. You will
see that the active record in this database has not changed. A
relationship is a one-way street; CONTACT can control the
database pointer in CUSTOMER, but CUSTOMER has no control
over CONTACT. (If you wanted CUSTOMER to control
CONTACT, you would break the relation from CONTACT to
CUSTOMER and make a new one in the other direction.)

To see what happens when FoxPro cannot find a match between


CUST_NAME in CONTACT and CUST_NAME in CUSTOMER, return to the
CONTACT Browse window and edit one of the CUST_NAME fields. Now
return to CONTACT and see what has happened. The active record in
CUSTOMER is the first record. FoxPro could not find a match and so gave
up, pointing to the first record.

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

System File Edit° Database Record Program Window

: ——— Fig. QS2.18.


Save View as:
The Save View As
dialog.

Directory CUST

« Save »

{ ] All Files « Cancel >

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.

Creating Reports on Related Databases


The best database design in the world does little good if you cannot
report on it. Fortunately, FoxPro’s report writing capabilities are well-
suited to creating reports on multiple-file databases. Once you have set up
your databases with the correct relations between them, FoxPro can draw
information from many databases at one time (up to 25). To create a mul-
tiple-file database report, do the following:
172 Part II: Intermediate FoxPro

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.

System File Edit Database Record Program .Window Report


UNTITLED.
FRX
Detail

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

System File Edit Expression


CONTACT.
FRX

Break <expr?:
Peed |ee Fig. Q92.20.
Changing the
database to
CUSTOMER.

Field Names: Database: Variables:

>»CUST_NAME | CONTACT y > ALIGNMENT


CONT_DATE 4) CUSTOMER BOX
SALESPERS INDENT
FOLLOW_DTE ‘« Verify > LMARGIN
CONT_RPT PADVANCE
SALE_MADE « OK » PAGENO
PBPAGE
« Cancel PCOLNO

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

System: File Edit Database Record Program Window Report


CONTACT. FRX
Group Header

Fig. QS2.21.
The Layout view.

zip

sal follow.d cont_rpt

9. Test your report by choosing Page Preview from the Report


menu. FoxPro will run your report and place the output on-
screen. Figure QS2.22 shows the output from the report as it now
exists.

System File° Edit Database Record Program. Window Report ~


int Preview

Fig. QS2.22.
The output of Kirkland 98332
OU AIGENE “CHZ 82/15/98 Purchased restoration materials.

CHZ 12/29/89 Discussed service/maintenance possibilities.

CHZ 81/15/89 Discussed warranty information on parts presente

ess Aviation Inventory


334Z Aviation R
Hangar 10
« More > Column:

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

1. Select the field CONTACT—>COMMENT, which is a memo field in


the CONTACT database. Memo fields have special editing
functions on the report because they can be any length.

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.

System File. Edit Database Record Program Window Report


CONTACT.FRX
Detail

Fig. QS2.23.
The Report
Report Expression: Expression

contact->cont_rpt dialog.

« Format... > Width: 58

EeaeStulesa. {C ] Stretch Vertically


{ J] Totaling... C J Suppress Repeated Values
{ J] Float as Band Stretches

« Cancel >

3. Return to the Layout view. Select Page Preview to show the


report with the CONTACT—>COMMENT field as defined.

4. Return to the Report Expression dialog for the


CONTACT—>COMMENT field and select the Stretch Vertically
option.

5. Move the CONTACT—>SALESPERS field to a position below the


CONTACT—>COMMENT field. Open the Report Expression dialog
on the comment field. When the Report Expression dialog opens,
notice the option Float as Band Stretches. Because the field
above the CONTACT—>SALESPERS field is a memo field that you
have allowed to expand, you must tell FoxPro that fields below
that expanding memo field can float on the page, always staying
one line below the expanding field. Select the Float as Band
Stretches option and OK.
176 Part Il: Intermediate FoxPro

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.

System: File Edit Database Record Program’ Window Report


: Preview

Customer Contact Report


Fig. QS2.24.
The improved
report.

Kirkland

Sales- Follow-up
person Date Report

82/81/98 CHZ 82/15/98 Purchased restoration materials.


Sale Made? Yes Check next call for additional sheet metal,
hydraulic requirements
11/38/89 CHZ 12/29/89 Discussed service/maintenance possibilities.
Sale Made? No Need to provide info on warranty tracking.

11/38/89 CHZ 81/15/89 Discussed warranty information on parts presente


Column: @

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.

Now your report is finished. You have succeeded in reporting on


the CONTACT database and drawing information from the related
CUSTOMER database for the report. This process is the same for databases
that contain two, three, or more database files. With FoxPro, reporting on
related databases follows the FoxPro philosophy of combining ease-of-use
with database power.

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.

In this chapter you learn the essentials of working with multiple-file


databases. Defining the databases and how they are to work together is
the most important part of creating these applications.

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

Understanding a Relational Database


The current buzz word in database systems is relational. All the latest
database systems are relational. Rather than trying to define the why’s and
wherefore’s of relational database systems, first let’s look at how data in
the real world fits together. From that, you can see how a relational
database can represent that data in the computer, making it easier for you
to create database systems.
In just about every system you might computerize, the data falls into logi-
cal groups. A wholesaler computerizing its operation, for example, would
find it has information about each inventory part, each customer, and each
order it takes. In database-ese, each of these logical groups of information
is called a data entity. In this company’s database system, each entity
would have its own database file to hold that information.

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.

Figure 6.1 shows a diagram illustrating the relationships between the


wholesaler’s data entities.

ANCUStOMErine lise PLACES cence son flit Olen e

Fig. 6.1.
Database
relationships. which refers to
a part in the

. inventory
Chapter 6: Designing, Defining, and Creating Relational Databases 18]

In prerelational database times, the databases and relationships could be


defined in a database system, but once defined, were extremely difficult to
change. These databases were called flat-file databases. When a user
wanted to add more types of information and new relationships to the
database structure, he was usually greeted with laughter (or tears) and
enormous bills for the redesign of the database, not to mention the recod-
ing of many routines. Flexibility was not a part of the flat-file database.

These databases often didn’t reflect reality, particularly in the business


world where reality is constant change. Today you may want the cus-
tomer information tied to the ordering system, but tomorrow you also
may want it tied to a customer contact system, and the next day you may
want it related to something entirely different. Relational databases enable
you to define these relationships on the fly, as you need them. In fact,
relationships often change many times in just one database application
development.

Relational database systems, such as FoxPro, have advantages over other


types of systems. FoxPro enables you to make your computerized
database system represent the real world more realistically. Relational
databases also make that system more consistent and reliable, because
there is almost no duplication of information in different database files.
Because there is no duplication, a relational database system like FoxPro
saves disk space and reduces the effort required for data entry and editing.

Designing a Relational Database


In Part I of this book, you designed a database system that had only one
file, a CUSTOMER or INVNTRY file, for example. Designing, defining, and
creating a multiple-file, relational database is not much different, but it
requires more thought at the beginning and more testing along the way to
ensure that everything is all right.

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.

As an example, suppose that you want to create a relational system that


stores and reports on customers, orders, and inventory. Figures 6.2
through 6.5 show outputs that you have to plan for in this system.
eccentrics apa pa a a

182 Part I: Intermediate FoxPro

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

Fig. 6.2. Number: 1


Name: West Hill Florist
ALCUSLOTHES, Address: 32901 2nd Ave So
report.
City: Renton State: WA
Phone: (206) 228-9932

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

report. 4019-1 "on "Cc" WASHER 0 ; 0.00


490560-78 et "Cc" WASHER te) . 0.00
WMP1-156 el "Cc" WASHER . 0.00
50647-13 Ket "C" WASHER . 0.00
WMP1-88 eeu "Cc" WASHER . 0.00
50724-4 UKor "C'" WASHER 0.00
0.00

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 ;

Soldkro:s 10 Fig. 6.4.


OshKosh Cow Company A Sales report.
5534 E. Dairy Road
Pasture 8
Oshkosh WI 88332
LEER ODE DT I OM IND ARM PANT P NOS Badd EMEPATLIO DNDN LEDEEEALPALA GOLBatLt 2 TyFinZakDRALLA Tt PLA AiALR EIdatPD LA 2
Order Date: 01/01/90 Salesperson: JWZ
CAMEENE PDE PECTSER EYTEP RTL PLANT ARID TIO AR ESTADO LAENL tah deCAL A A RtPaloean Ant DEM A STA Pat UD dalga A A
Part Number Qty Keyword Description Price
IEEE LILI CPE DINE ETB CDSE DESL TR EMAOS TINCT DOEPASDT FTA PLJECT TEAL PTDN CUE lal 2 AL EAP CAS LE ae
IN F-17200 1 MASTER MASTER CYLINDER 58.43

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

Part No. Keywor Description Ordere y Date Qty :


CBU DS MT TN Fol FO 0S) ESTES UA PETLI BW LAL PY CY a AE PY AGT AN PSS SATEST Aaa?dat Pt DY EYAAT LN Ae PAY GOTDy BIRTQO doRYOY Bie PAYAY Sekt ZN. eyCY MaRYA ADR At LAE Oi had Al at LY Fig. 6.5.

A 988642 BEARING BEARING SCIL 03/24/90 10 An Inventory


T.Moore & Assoc, 10/10/89 2 . E i" -
SN1467 NUT NUT SCIL 02/01/90 10 Ordered report.
1303012 OIL OIL SEAL Studio 11 Art 01/03/90 9
626115 SPRING SPRING Studio 11 Art 01/08/90 10
991867 BREATHER BREATHER Studio 11 Art LAOS yA2Koyy ALC)
E-2138 PULL PULL ROD, 38" West Hill Florist 01/22/89 100
E=-2355 RING RING Hess Aviation Inv. 01/15/90 a
E-2514B SHIM SHIM, .025 Hess Aviation Inv. 01/15/90
E-3060 2ND 2ND RED GEAR OshKosh Cow Co. 12/15/90
Hess Aviation Inv. 12/12/89
E-3070 WASHER WASHER Comair 01/15/90
T.Moore & Assoc. 02/02/90
F-17200 CYLINDER CYLINDER OshKosh Cow Co. 01/01/90
184 Part II: Intermediate FoxPro

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.

Defining Databases and Relationships


Both the CUSTOMER and INVNTRY databases in this multiple-database
system were defined in Part I. Using your design work, the structure of
the ORDER database can be defined. At this point, you have defined the
databases necessary to hold all the data you need in your system. Now
you must decide how to define and create the relationships you know
exist between the databases. In this system, you need to define the rela-
tionship that exists between the CUSTOMER and ORDER databases, and
another relationship that exists between the ORDER and INVNTRY
databases.

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

from the CUSTOMER database. Similarly, if you define a relationship


between the ORDER database and the INVNTRY database, FoxPro will be
able to access information from the INVNTRY database about the part
actually ordered.

In the E-R diagram, a relationship is represented by a diamond, with its


name inside. Figure 6.6 shows an E-R diagram for the ORDER IS PLACED
BY entity-relationship.

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.

When you establish a relationship between two FoxPro databases, one


database will be the “controlling database” and the other the “controlled
database.” As FoxPro accesses records in the controlling database, it auto-
matically updates the database pointer in the controlled database. (The
database pointer is an imaginary arrow that points at the active record in
a database.) In this example, you want the database pointer in CUSTOMER
always to point at the record of the customer who placed an order, which
is in the ORDER database. You must tell FoxPro how to locate the correct
record in CUSTOMER.
Both the ORDER database and the CUSTOMER database have a common
field: CUST_ NAME. You define this relationship to FoxPro by telling it to
tie these two databases together based on the value of the field
186 Part II: Intermediate FoxPro

CUST_NAME. Then, whenever you choose a record in the ORDER


database, FoxPro does the following:

1. Reads the value of the field CUST. NAME in the active record of
the ORDER database.

2. Moves to the CUSTOMER database and finds the record in that


database that has the same value in CUST_ NAME.

3. Sets the database pointer to this record, making it the active


record in CUSTOMER.

4. Returns to ORDER to do any processing the user may want to do,


such as editing, viewing, or printing data.

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.

ORDER < IS PLACED BY —> CUSTOMER ENE ;


Adding the
relational
CUST_NUM CUST_NUM
expressions to
the Entity-
Relationship
diagram.

You also can draw an arrow pointing from the controlling to the con-
trolled entities to remind you which is which.
ee ee

Chapter 6: Designing, Defining, and Creating Relational Databases 187

The controlled database must be indexed on the relational expression or


FoxPro will not be able to establish the relationship. So, under the entity,
put the index expression that you will need for this database. In this case,
it is the field CUST_ NAME. The controlling database does not have to be
indexed on the relational expression.

Your Entity-Relationship diagram now describes two databases, ORDER


and CUSTOMER, the relationship that exists between them (IS PLACED
BY), and how that relationship is established. Figure 6.8 shows another
E-R diagram with the INVNTRY database added and a relationship, REFER-
ENCES, between ORDER and INVNTRY.

Fig. 6.8.
ORDER < IS PLACED BY > »——> CUSTOMER The completed
Entity-
CUST_NUM CUST_NUM Relationship
diagram.

< REFERS TO ——P INUNNTRY

PART_NUM PART_NUM

Entity-Relationship diagrams are excellent tools to think through your


database design before you define it to FoxPro. This introduction to E-R
diagramming has been kept simple so that you can see how to use them.
As you develop more advanced FoxPro applications, you may want to
learn more about E-R diagrams; an excellent discussion of them is con-
tained in Advanced Structured Analysis and Design, by Lawrence Peters.

You’re probably thinking, “Holy Mackerel. Do I have to go through all


this?” No, you don’t, but you skip it at your own risk. You easily can make
changes to FoxPro databases and, as noted before, flexibility is essential in
designing and creating FoxPro databases. Still, the diagramming exercise
helps ensure that your databases have the fields needed to tie them
together, and that you have a good idea of the structure of your system.

When you have designed your databases and relationships on paper, you
must define the system to FoxPro.
188 Part II: Intermediate FoxPro

Creating Relational Database Systems


The first thing to do when creating relational database systems in FoxPro
is define the database files, just as with a single-database file system.
The example used in this chapter uses the three database files ORDER,
CUSTOMER, and INVNTRY. Table 6.1 shows the structure of these
databases.

Table 6.1
Database File Structures

Structure for database : C:\FOXPRO\CUST\ORDER.DBF


Number of data 6 IY
records
Date of last update 01/27/90

Field Field Name Type Width Dec

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

Structure for database : C:\FOXPRO\CUST\CUSTOMER.DBF


Number of data rage ey
records
Date of last update 02/11/90

Field Field Name Type Width Dec

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

Structure for database : C:\FOXPRO\CUST\ORDER.DBE


Number of data eel
records
Date of last update : 01/27/90

Field Field Name Type Width Dec

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

Using Work Areas


When you use multiple databases in FoxPro, you use work areas to keep
them separate and identifiable. The View window has a box labeled Work
Areas. Each work area can hold one database file and all the information
associated with that file; index files, formats, field statements, and filters.
FoxPro has 25 such work areas, although only 10 can be seen in the Work
Area box at any time. You will put each database in your system into a
different work area, along with its formats, filters, and index files. All 25 of
the work areas can be in use at any time. You will seldom, if ever, use all
25 at once, however.

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

System File Edit Database Record Program Window

6.9. « View > Work Areas « Relations >


Fig.
The View «On/Off>
window, showing
«Files >
work areas A
through J. « Misc ?
<Setup >

<Browse>

< Open >

«Close >

Identifying Work Areas with Aliases


When you have databases open in multiple work areas, you can tell Fox-
Pro to access fields by specifying the name of the field, prefixed with an
alias to tell FoxPro in what work area the database with that field resides.
If, for instance, you have selected a database in work area B and want to
access the name field of the CUSTOMER database in work area A, you tell
FoxPro to use the value in CUSTOMER>NAME. Alternatively, you can
prefix the field with the work area letter, A>NAME or its number,
1>NAME. In all cases, FoxPro knows where to get the name field.

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.

To add a second database (the CUSTOMER database in this example),


select work area B and follow the same Open and Setup process. When
you are finished, your View window should appear as in figure 6.11.
You continue to open databases by selecting subsequent work areas and
opening the database and its index files in that work area. After adding a
third database, INVNTRY, the View window looks like figure 6.12.
Chapter 6: Designing, Defining, and Creating Relational Databases 191

System File Edit ‘Database Record Program Window

« View > Work Areas <« Relations > Fig. 6.10.

A <On/Off> The View


a
¢ window with
Dea CUSTOMER
i | added in work
“Setup > area A.

«Browse?

« Open >

<Close > |ORDER Records: 17

System File Edit Database Record Program Window ,

« View > Work Areas « Relations > Fig. 6.11.


The View
<On/off> | |» ORDER x ; f
“CUSTOMER ¢ window showing
‘Files > , CUSTOMER and
« Misc >
ORDER.

«Browse?

< Open >

<Close » |CUSTOMER Records: 15

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

192 Part II: Intermediate FoxPro

System File Edit Database Record Program Window

Fig. 6.12. « View > Work Areas « Relations

The View ; <onvoff> | |» ORDER


window showing “CUSTOMER
ail tree ‘Files > + INUNTRY
databases. « Misc >

«Setup >

<Browse>

<« Open >

<Close > |
HINUNTRY
INUNTRY Records: 3Z87
3287,

Specifying Relationships in FoxPro


Looking at the Entity-Relation diagram you created in designing your sys-
tem, you can see what relationships must be set up. In the example used
in this chapter, when processing the ORDER database, there must be a
relation between ORDER and CUSTOMER, so that when FoxPro processes
an ORDER record, it can retrieve information about the customer
(CUST_NUM) from CUSTOMER. Because FoxPro will be processing the
ORDER database record by record, and retrieving information from
CUSTOMER, you know that ORDER is the controlling database and
CUSTOMER the controlled one. To set this relationship, select the con-
trolling database (ORDER) and choose Relationships. The controlling
database name appears, with an L-shaped indicator (see fig. 6.13).

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

System File Edit -Database .Record Program Window.

« View > Work Areas « Relations > Fig. 6.13.


Bonoff» | |» ORDER =, | ORDER Specifying the
‘CUSTOMER ¢@ |>L-+ controlling
‘Files > + INUNTRY 3
database in a
relation.
“Setup >

«Browse?

« Open >

<Close > |ORDER Records: 17

Sustem File Edit Database. Record Program Window

« View > Work Areas « Relations > Fig. 6.14.


<On/Off> | |» ORDER , |?ORDER Tie View {
‘CUSTOMER @ | L-+4CUSTOMER window with the
«Files > + INUNTRY ORDER-

CUSTOMER
relationship
established.
«Browse?

« Open >

<Close > |ORDER Records: 17

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.

System File Edit Database Record Program Window

Fig. 6.15. « View > Work Areas « Relations >


View
ee og ; <On/Off> | |» ORDER 4 |PORDER
window with all “CUSTOMER CUSTOMER
databases and ‘Files > . INUNTRY
relationships.

«Browse?

<« Open >

<Close » |ORDER Records: 17

Setting Relationships in FoxBase +


The concepts behind defining and designing relationships in FoxBase+
are the same as for FoxPro. Defining the relationship differs, though,
because FoxBase+ does not have FoxPro’s window-based user interface.
In FoxBase+, you must set up the database files and define the relation-
ships from the command line. In FoxPro, you can use these same com-
mands if you want to work in the Command window.

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 A && select work area A


USE CUSTOMER && open CUSTOMER in this work area
SET INDEX TO CUST._.NUM && open the cust_num index

SELECT B && select work area B


USE ORDER && open ORDER in this work area
SET INDEX TO ORD_CUST && open the ord_cust index, which
&& is on field cust_num in the
&& ORDER database

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:

SELEGT 2 && move to controlling database


SET RELATION TO CUST_NUM INTO A
SET RELATION TO PART_NUM INTO C ADDITIVE

The ADDITIVE command in the second SET RELATION command tells


FoxPro to add this relation to any existing relation for this controlling
database. Without this option, FoxPro will replace any existing relation-
ships with the one being specified.

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

Saving the Setup


Setting up the databases and relations can be a time-consuming process.
You often will find that each thing you want to do in your database sys-
tem—reports, inquiries, data-entry—requires a different setup of files,
indexes, and relationships. FoxPro provides a facility to save a setup and
reestablish it later with one command. Because all that is saved can be set
up in the View window, these files are called View files.

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.

System File Edit Database~ Record Program Window

Fig. 6.16.
Save View as:
The Save View
dialog.

Directory CUST

« Save »

{ J All Files < Cancel >

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.

Saving and Using Views in FoxBase+


FoxBase + also provides the facility to save and reuse Views. Again, you
have to do this from the command line. In FoxBase+, you can save an
environment with the command
Chapter 6: Designing, Defining, and Creating Relational Databases 197

SAVE VIEW AS ORDR-1

and you can reestablish that environment with the command

SET VIEW TO ORDR-1

As before, FoxPro users can also use these commands in the Command
window to accomplish the same purpose.

Testing a Relational Database System


Before you charge off to create the FoxReports and FoxView screens you
need for your relational database, you should test the files and relation-
ships to make sure your design works. This can be done easily, and will
save you hours of time later on if you find that a relationship was set up
incorrectly or essential data not included.

Test the database structure by creating a quick-and-dirty report using


fields that show whether the relationships are set up or not. For example,
you can test to make sure that the relationships for the Order report are
in place.

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:

ORDER CUSTOMER INVNTRY

CUST_NUM CUST_- NUM PART_NUM


PART_NUM NAME KEYWORD

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

198 Part II: Intermediate FoxPro

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.

System File Edit Database Record~ Program’ Window ‘Report


: UNTITLED. FRX

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

ORDER CUSTOMER INVNTRY


5 S Comar
EN) E=2398 IN E-2398 ROLLER

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

Hess Aviation Inventory


ROLLER

Hess Aviation Inventory


E-2514B E-2514B SHIM

Hess Aviation Inventory


1178 SEAT

2 Northwest Microsystems
BA 992518 BA 992518 RING

10 10 OshKosh Cow Company


CENTURY 2260E CENTURY 2260E CARBURATOR

10 10 OshKosh Cow Company


CL 1754428 CL 1754428 SHIFT

3 3 ScIL
CASCADE 662458 CASCADE 662458 SEAL

3 3) SCIL
F=869 F-869 POLY

i 13 T. Moore & Associates


BA 988619 BA 988619 BRACKET

13 1S T. Moore & Associates


LP 1425-3328 BPeL425=33'28 BEARING

a 1 West Hill Florist


CASCADE 6045

At West Hill Florist


IN, H=2233 PULL

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.

You have learned how to design multiple-file databases, using one


database for each data entity. You have learned how to define those
databases and, more importantly, the relationships that tie the databases
together. Simple tests of the data enable you to make sure that your
design is good and that your implementation of the design works.
200 Part II: Intermediate FoxPro

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.

System File Edit Database Record Program Window


Oy CONTACT. FMT : =
Program.: CONTACT. FMT
Author..: John Zumsteg
Fig. 7.1. Date....: 81/81/98
The Text Editing Notice..: Copyright (c) 1998, Northwest Microsy
: Version.: FoxBASE+, revision 2.18
window. Notes...: Format file for CONTACT. DBF

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

System File Edit Database Record Program Window


e CONTACT. FMT
Program. : CONTACT.FMT
Author..: John Zumsteg
Date....: 61781798
Notice..: Copyright (c) 1998, Northwest Microsystems Fig. isan
Version.: FoxBASE+, revision 2.18 Text selected,
Notes...: Format file for CONTACT. DBF
ready to be cut
or copied.

SET COLOR TO ,N/U


5,44 GET Cust_num PICTURE “@!”
6,44 GET Cont_date
7,44 GET Salespers PICTURE “@!”
8,44 GET Follow_dte
FYaqaaqa

From the keyboard, you also can navigate in the text window. To move
the cursor, use the following keys:

Key Action

Right arrow Move one character right


Left arrow Move one character left
Up arrow Move up one line
Down arrow Move down one line
Home Move to start of current line
End Move to end of current line
PgUp Move up one window
PgDn Move down one window
Ctrl-Right Arrow Move one word right
Ctrl-Left Arrow Move one word left
Ctrl-Home Move to beginning of text
Ctrl-End Move to end of text

To select a range of characters to be copied or deleted, place the cursor


to begin selection, then hold down the Shift key and use the arrow keys to
move the cursor to the end of the selected text. The selected text is
highlighted.
To delete text one character at a time, use either the Del key or the back-
space key. You also can highlight the text you want to delete and choose
Clear from the Edit window.
204 Part II: Intermediate FoxPro

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.

Understanding How FoxPro


Writes and Reads Screen Fields
FoxPro uses GET and SAY commands to read information from the screen
and display information on the screen. The format of the GET and SAY
commands, which are used only in Format and Program files, is

@ row, col SAY field_name

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.

Using FoxView To Create


a Multiple-File Form
FoxView has extraordinary capabilities for creating elegant data input, edi-
ting, and query screens. You can use these capabilities to create a screen
that presents data from several related files. To start this process, choose
FoxView from the Program menu.

Loading the Database Files


First, set up in FoxView the databases you want to use. You must set them
up just as you do in FoxPro. You probably have already saved a View with
the databases, so make sure that you know which databases are in which
Chapter 7: Data Entry and Editing with Multiple Files 205

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.

<Ci\FOXPRO Sunday 63/84/96 |RIREYART

Welcome to FoxView 3.8


Press F1 for HELP
Fig. 7.3.
FoxView C: use order : .
S field(s) loaded Opening multiple
databases in the
FoxView C: >select Z FoxView shell.
FoxView C: >use customer
1Z field(s) loaded

FoxView C:>select 3

FoxView C:>use inuntry


18 field(s) loaded

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.

Moving Fields and Pages


First, move through each page and delete fields you don’t want on your
screen. Seldom do you need to see the fields that form the relationship in
all files, so you can delete the fields on all but one page. (In the example,
you could delete CUST.NUM from Page 1 or Page 2, and PART.NUM
from Page 2 or Page 3.) Any other unneeded fields also should be
removed at this time.

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

C:INUNTRY.DBF ©@ Z,@ Page: 1

Cust_num
Ordr_date
Fig. Wee Salespers
, Part_num
The first aty
database used in
the FoxView shell
appears on Page
1 of FoxView.

C: INUNTRY.DBF @ Z, Page: Z 11 54°am

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

C: INUNTRY.DBF © 3,6 Page: 1

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

208 Part UJ: Intermediate FoxPro

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.

C:INUNTRY.DBF @ 3,27 Page: 1

Order Information Query


Fig. 7.8.
The complete Customer Number:
Customer Name
query screen, Address
using three
related databases. City State ji] Zip ay
Phone

Order Date Salesperson [gj


Part Number Oty Keyvord Description Quantity Onhand

Supplier Price Cost

Changing GETs to SAYs


You need to make one more change to the Table view before you leave
FoxView. Return to Table view by pressing F10. Notice that all the fields
have a GET in the (Fld) field. This is because FoxView assumes that you’re
creating a data-entry screen, and GET tells FoxPro to get some informa-
tion from the screen. To create a screen to display data, change the GETs
to SAYs by placing the highlight on the GET and pressing the space bar.
One press changes the value to SAY, a second to HIDE (which means the
field disappears), and a third returns to GET. Change all the GETs to SAYs
to create a data display screen.

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

SET FORMAT TO fmt_filename


Chapter 7: Data Entry and Editing with Multiple Files 209

in the Command window.

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?

System File Edit Database .Record Program Window

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.

Creating a Form Generator


for Multiple Files
When you told FoxView to create a Format file from your screen design,
it did not simply generate that format file directly from your screen. It
actually called a program named FORM1 that read the FoxView table you
created, and then FoxView processed the information in the table into a
FoxPro Format file. If you want to see what this format file looks like,
ee a ee ees

210 Part II: Intermediate FoxPro

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.

System File Edit Database Record Program Window


a ORDER_Q. FMT
* Program.: ORDER_Q. FMT
* Author..: John Zumsteg
* Date....: 83/84/98
Fig. 7.10. : * Notice..: Copyright (c) 1998, Northwest Microsystems
The Format file x Version.: FoxBASE+, revision 2.18
created in * Notes...: Format file for ORDER. DBF
*

FoxView. SET ‘aD COLOR TO R/N


4,8,11,79 BOX “Fy f=”
@ 5S, 2 SAY "Customer Number:
@ 12,8 TO 18,79
@ 13, 2 SAY “Order Date ”
@ 13,22 SAY “Salesperson “
914, Z2 SAY “Part Number "
9 14,18 SAY “Oty ”

SET COLOR TO N/W


@® 5,19 SAY Cust_num
@ 13,13 SAY Ordr_date
13,34 SAY Salespers
15, 2 SAY Part_num
9 15,18 SAY Qty PICTURE "99999"

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

Understanding How FoxView


and FoxCode Work Together
FoxView does not have a way of directly generating Format files or any
other kinds of files. FoxView invokes a Template program, FORM1, to read
the FoxView table and create an FMT file from it. If you had chosen
FORM2, FoxView would have invoked a Template program named
FORM2 to read the table and do different things with that information,
resulting in a different output file. You can have any number of these
Template files, each of them doing something totally different with the
table you created in FoxView.
A i ae ts a lS sapere
Chapter 7: Data Entry and Editing with Multiple Files 21 J

These Template files are in a language specific to FoxPro, called FoxCode.


For now, you don’t need to know the specifics of FoxCode or anything
about writing programs in it. Just remember that a FoxCode program
reads the FoxView table, digests it, and creates a FoxPro program file of
some sort.

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.

Modifying the Form File Generator


In this section, you modify several FoxCode template language files. You
don’t need to know anything about the FoxCode template language for
this exercise, but if you want to learn more about FoxCode, refer to the
FoxView-FoxCode FoxDoc manual.

To modify the FORM1 template file to handle multiple database forms,


open the FORM1.GEN file by choosing Open from the File window and
selecting Program. Open the directory \FOXPRO\TEMPLGEN, place an X
in the ALL Files check box, and select FORM1.GEN. FoxPro displays that
file in the Text Edit window. Immediately save this file with a different
name, using the Save As option from the File menu. Save the file as
FORMALL.GEN. Now you can edit the file to make the necessary minor
changes. When you're finished, you have a new template file, which will
appear as FORMALL on the FoxView template list. This new template will
create format files that display data from multiple database files in FoxPro.

First, change the title, which is on the first line, from

<<title 'Format File Generator'>>

to

<<title ‘Multiple File Format Generator'>>

Move through the FORMALL.GEN file to row 18, which contains the line
<<#include 'GENFLD. INC'#>>

Change GENFLD.INC to GENFLDAL.INC. Move down three lines and change


the line that reads
<<#include 'GENFMT.INC'#>>

to

<<#inc Lude 'GENFMTAL. INC#>>


Pal 4 Part II: Intermediate FoxPro

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.

System File Edit Database Record Program Window


= : FORMALL.
GEN
«<title "Format Multiple File Generator’>>
Ct

Fig. UAL : <<«x-—-Declare global variables-—-*>>


The modified string fpath, fname, fext
FORMALL.GEN string prgname,datafile
string fldprefix
file.
«<*-—-GENHUE vars-—->>
integer lasthue, forecolor, backcolor

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

if fldvals $ "AM! <<* PRIMARY and MEMORY workareas *>>


delete the A in 'AM!.

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.

System File Edit Database Record Program Window


= : GENFMTAL.INC

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

just before the forall pages line, and place

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.

System File Edit Database Record Program Window


2 GENFMTAL.
INC

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

Compiling the New Form File Generator


The last step in preparing your template file is to compile it into some-
thing FoxView can use. To do this, you must leave the comfort of FoxPro.
Quit from FoxPro and enter the following commands from the MS-DOS
prompt:

CD \FOXPRO\TEMPLGEN
FOXCODE FORMALL

When FoxCode is finished, copy the output COD file to the directory
\FOXPRO\TEMPLCOD by typing

COPY FORMALL.COD C:\FOXPRO\TEMPLCOD

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 cust is the name of your directory. In FoxPro, choose FoxView.


Because you have already created your FoxView table, you can simply
enter the command,
LOAD table_name

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.

<C:\FOXPRO\CUST > Sunday 83/84/98


Welcome to FoxView 3.8
Press F1 for HELP
1h, Tol by
FoxView C:>LOAD ORDER Loading the
Z1 field(s) loaded saved FoxView

FoxView C:>_ table ORDER.

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

System File Edit Database Record Program. Window

Order Information Query


Fig. 7.16.
Customer Number:
The multiple-file Customer Name [@ehietg
format. Address BEE YA IT DO olofoboheum yp UU1-1

City (pee irenaa State W@) Zip Geeer!


Phone

Order Date GIRBEVE) Salesperson |My


Part Number Qty Keyword Description Quantity Onhand
IN E-2398 BEARING [BEARING (DEADLINE 407
Supplier Price Cos t
RBC T-74284 8.80

Using the Multiple File Form


for Data Inquiries
Using a form designed from multiple files is not much different than using
single-file forms. You do have to ensure that the current database is the
controlling database in your relational setup, otherwise none of the rela-
tions will work and your form will display funny answers. In the example,
the ORDER database is the controlling database, and the CUSTOMER and
INVNTRY databases are controlled by relationships. Using the View win-
dow, set up your databases. If you have done this previously and saved the
setup as a View file, open that file to bring the setup into 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

SET FORMAT TO fmt_filename

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.

Using RANGE and VALID Clauses


A leading cause of database problems is bad data—the old “garbage in,
garbage out” syndrome. You should use any method you can to ensure
Chapter 7: Data Entry and Editing with Multiple Files 27,

System File Edit Database Record Program - Window

Database: ORDER PS ail


Structure: <Modify> Indexes: The View Setup
dialog, with the
> CUST_NUM c 6 ;
ORDR_DATE | D 8 Format file
SALESPERS | C 3 specified.
PART_NUM & |) a6
Fields: S Length: 38 Index expr
Index filter:
C J Set Fields...
COLOR ceo oLe
Ea Filtersc.
CX] Format... C:\FOXPRO\CUST\ORDER_Q.
PRX

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.

Using RANGE clauses


A RANGE clause defines the upper and lower limits that FoxPro will
accept for a data entry field. You specify a RANGE clause when you are
working with the form in FoxView ( or you can add it to the Format file
that FoxView creates). To add a RANGE clause to a field in FoxView,
move to the Table View by pressing F10, then place the cursor in the
RANGE column of the field. (On the initial Table View, RANGE cannot be
seen; you must Tab right to make the Table View scroll the RANGE clause
onto the screen.) Once the field is highlighted, enter the lower limit of
the field, then the upper limit of the field, separated by a comma. Figure
7.18 shows the Table View of FoxView, with a RANGE specified for the
field CREDIT. With this RANGE clause in place, FoxPro will not, during
data entry, accept a value below 0 or above 5,000.

Using a VALID Clause To Check Data Entry


The VALID clause is a FoxPro expression that will be checked against the
entered data. If the data passes the test, FoxPro accepts the field; if not,
FoxPro rejects the data and puts a message on the screen. Using VALID
clauses helps ensure the data is accurate before it gets to the database.
218 Part II: Intermediate FoxPro

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)

RANGE: <lower exp>,‘upper exp»; press Fl for Help

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:

DATA_ENTERED = the VALID expression

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

ZIP = "98080" .OR. "98081" .OR. "98082"


A VALID clause equivalent of this expression would be

VALID(98080" .OR. "98081" .OR. "98082")


To enter this valid clause in the Table View in FoxView, move the high-
light to the VALID column for the field ZIP. Enter

"98080" .OR. "98081" .OR. "98082"

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

t . Als Field Typ Wid Dec Picture Range Valid Init


1 A BOXOBJECT 73 7
2 A
3. B Fig. 7.19.
4. B Adding a VALID
5 B
6 B clause to the ZIP
7 B field in FoxView.
8 B 1 REEL) £
B ae
A BOXOBJECT
A Ordr_date
A Salespers
A Part_num
A Qty 1£6, S688)
C Keyvord it 1c
Cc Descr IC iit
C Qty_onhnd It it
C Supplier OQAo
OSs
wz
O20
oc
OO it It Sy
eee,
er
ere
aye
ery
Se
ae
Se

= OR; “S8G8L) .OR. “988827


VALID: expression to verify during the read

Creating More Sophisticated VALID Clauses


There will be times when the test you want to make in a VALID clause is
more complex than can be put in one FoxPro expression. For these occa-
sions, you can create a User Defined Function (UDF). Remember, a VALID
clause checked the data entered into a field against an expression. If that
test returned a TRUE, meaning the entered data met the test, FoxPro
accepted the data. A UDF is a mini-FoxPro program which will take the
value entered into the data field, process it in some way, and return to the
VALID clause a TRUE or FALSE. If the return is TRUE, the VALID clause
accepts the data, otherwise it rejects it. This allows you to create some
extremely sophisticated tests for your data.

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.

1. In FoxView’s Table view, in the VALID column of the field ZIP,


enter

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.

If the value equals 98080, 98081, or 98082, the function returns a


.T. to the VALID clause, which is FoxPro’s shorthand for true. If
the data entry value is not one of these three, the function returns
an .F., for false.

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.

Testing Relational Values with


a User-Defined Function
When entering data into a database that is related to another, it’s impor-
tant that the data in the relational fields (the fields that tie this database to
a related one) is accurate. If, for instance, two databases are related on a
CUST_NUM field, you want to make sure that the value entered into the
CUST_NUM field of the controlled database actually exists in a record in
the controlling database. You don’t want to enter CUST.NUM "90021" if
there is no 90021 in the controlling database. A UDF can accomplish that
test.
Chapter 7: Data Entry and Editing with Multiple Files 221

In pseudo-English, the following is a UDF to accomplish that. The


CUST_NUM entered into the data entry field will be passed as the
PARAMETER NUM:
FUNCTION CHK _NUM
PARAMETER NUM

move to the controlling database (it must be opened already)


seek on NUM (the value entered)
move back to the original database
if the seek was successful (the number was found)
return a true to the VALID clause
else
return a false to the VALID clause

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.

User-Defined Functions can be simple or quite complex. They are an


advanced use of FoxPro, but one which can make life much easier by
making sure the data entered is valid.

Using the Record Menu To Find Records


Pick Choose from the Record menu (or type edit in the Command win-
dow) to display the Form with the information from all three databases
shown. The relationships that emanate from the controlling database
(ORDER in this example) control which records are presented in the con-
trolled databases. If you set all the GETs to SAYs in your form design, you
will be unable to change any information. You can, however, use the
options offered in the Record menu to access any record in the controlled
database and its related databases.
If you use the Seek or Locate options to find specific records, FoxPro does
not automatically display them on your form. Seek and Locate only posi-
tion the database pointer to the correct record. You must select Change
from the Record Menu, or Edit in the Command window to activate the
form with the information on it.

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.

Creating a Keyed Entry


Viewing Program
In working with a multiple-file form, it is easier to find records if you can
enter the key fields of the record in the controlling database that you
would like to display and have FoxPro automatically do the Seek and Edit
to present the field. A fairly simple way to do this is to change the FMT
format file to a PRG program file, make a few additions, and then execute
the program by choosing Do from the Program menu.

The process you want FoxPro to follow in this program file is as follows:

1. Place the format on the screen without data.

2. Get the key field values from the user.

3. If the user doesn’t want to see more, exit from the loop.

4. Seek to find the record with input key field values.

5. Place the values on the screen.

6. Return to the start for another request from the user.

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.

Changing the FMT File to a PRG File


First, use the File Open menu, placing an X in the ALL Files check box to
see all FMT and PRG files. Find and open the FMT file you created in
FoxView. Use the File Save menu to save it as a PRG file. You must specify
the PRG extension or FoxPro will save the file with the FMT extension it
was opened with. Figure 7.20 shows the example FMT file being saved as
a PRG file.
Chapter 7: Data Entry and Editing with Multiple Files 223

System File Edit Database Record Program Window


3 ORDER_9. FMT
* Program.: ORDER_Q,
FMT
* Author..: John Zumsteg
* Date. ss.) 8
* Notice..: C Fig. 7.20.
* Version.: F Savin
* Notes...: F Drive , 8
x ORDER _Q.FMT as
SET COLOR TO ORDER _Q.PRG.
© 4,6,11,79 B
@! 5; 2 SAY : Directory | CUST |
12,8 TO 18,
on Ww N unD <<

135 2Z.5ny) « Save »


oq
gaa147 2, SAY
14,18 SAY " C J] All Files < Cancel >

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"

Adding Memory Variable GETs


The next step is to use the Text editor to add the lines necessary to ini-
tialize and read memory variables for the keyed fields of the controlling
database. This process can be described as follows:

1. Initialize a memory variable for each key field.

2. GET each memory variable at the same location as the SAY of the
form.

3. READ the memory variables.

4. If the memory variables are blank, exit from the routine.

5. Seek on the key fields.

6. SAY all the fields of the controlled and controlling databases.

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:

m_ORD_NUM = " fi && initialize a memory var to


blanks
@ nn, nn GET m_CUST_ NUM && create a GET to get the key
field memory variable value
READ && read a value into the
mem var
IF m_CUST_NUM = " : && if nothing was entered
RETURN && go back to FoxPro
SEEK m_CUST_ NUM && seek on the key field
224 Part II: Intermediate FoxPro

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.

System File Edit Database Record Program Window


2 ORDER_9.
PRG
@ 13,22 SAY “Salesperson ”
14, Z SAY “Part Number ”
Fig. 7.21. Pea toe pike
1

Lines added to ET COLOR TO N/W


the .PRG fi
G file'to x-—— lines added to input and seek on the key field
input and seek mCUST_NUM = “ :
on key field S, 19 GET mCUST_NUM
ye) READ
values. IF mCUST_NUM = ”
RETURN
ENDIF
SEEK mCUST_NUM

x--- end of lines added to input and seek on the key field

9 5,139 SAY A->Cust_num


9 13,13 SAY A->O0rdr_date
9 13,34 SAY A->Salespers
15, Z SAY A->Part_num
15,18 SAY A->Oty PICTURE "99999"

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

Order Information Query

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

Adding a DO WHILE..ENDDO Loop


When FoxPro presents the correct data, it returns to the Command win-
dow for your next command. With just another little change, you can
cause your program to loop until you decide to stop. Again, open the PRG
file you created. From the Command window, you can enter

MODIFY COMMAND prg_filename

to open the file for editing.

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,

Adding a WAIT Statement


Because FoxPro loops quickly through the SAYs, returns to the DO
WHILE .T. beginning of the loop, and asks for another input, you will
never see the key value. It will always be blanked out by the next request.
To enable you to look at the entire data record—key field and all—place
commands that cause FoxPro to pause at the end of the SAYs. The best
way to do that is with the following lines above the ENDDO statement
added above the end of the program:

SET CONSOLE OFF && you will not see anything


WAIT && until you press a key
SET CONSOLE ON && back to normal

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.

Now your program is complete. The following listing shows what it


should look like. This simple program forms the basis for many data-entry
and query screens. Once you understand this process of changing a FMT
format file to a PRG program file, you will find unlimited ways to use this
knowledge. You could, for instance, eliminate the user input and have
another program call this one, passing the key value to seek.

* 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

SET COLOR TO R/N


@ 4,0,11,79 BOX "'UM83>MT3""
@ 5, 2 SAY "Customer Number: "
*-- Lines added to input and seek on the key field

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

SET COLOR TO N/W

*-- end of lines added to input and seek on the key field

a 5,19 SAY A->Cust_num


a 1 3,13 SAY A->Ordr_date
@ 1 3,34 SAY A->Salespers
@ 1 5, 2 SAY A->Part_num
@ 1 5,18 SAY A->Qty PICTURE "'99999"'
SET COLOR TO R/N
6
Gl
Spl mSAV eee a
OFAGeSAY "City
9,355 SAY "State "
Se)Lie SING Ueaifey
0,13 SAY "Phone "
O29

9
®
92

SET COLOR TO N/W


@ 6,19 SAY B->Cust_name
@ 7,19 SAY B->Addr_1
@ 8,19 SAY B->Addr_2
@ 9,19 SAY B->City
@ 9,41 SAY B->State
@ 9,48 SAY B->Zip
@ 10,19 SAY B->Phone
SET COLOR TO R/N
@ 14,24 SAY "Keyword "
@ 14,35 SAY "Description"
@ 14,61 SAY "Quantity Onhand "
16,18 SAY "Supplier "
16,44 SAY "Price sy
3,27 SAY "Order Information Query "
OD SaSAYeucost “
8
®
2
*
®

SET COLOR TO N/W


@ 15,24 SAY C->Keyword
@ 15,35 SAY C->Descr
Chapter 7: Data Entry and Editing with Multiple Files 229

5,61 SAY C->Qty_onhnd PICTURE ''99999!"


7,18 SAY C->Supplier
7,44 SAY C->Price PICTURE ''99999.99""
7,53 SAY C->Cost PICTURE ''99999.99""

SET CONSOLE OFF


WAIT
SET CONSOLE ON

ENDDO
*
* EOF: ORDER_Q.PRG

Using the Keyed Form Program


Using this PRG file is simple. Again, make sure that your databases are set
up properly. Choose DO from the Program menu. You should close all
open windows and resize the Command window to be out of the way,
because this program file will appear on the FoxPro screen, which is
below all other windows. Other windows on the screen will obscure the
data screen your program will display.

Using The Form Program


for Data Entry
You also can use your form for editing data in any of the databases. This
takes just a few minor changes. First, decide which fields you want to be
edited and change the SAYs of those fields to GETs. Include any appropri-
ate RANGE parameters or PICTURE formats. Then, add a second READ at
the end of all the SAY and GET statements, replacing the SET CONSOLE
OFF, WAIT, and SET CONSOLE ON statements. Figure 7.25 shows where
this second READ is added.

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.

A word of caution: I strongly recommend that you not allow a change to


the fields in any database that forms part of the relation between the
database. You should think of the record in the controlling database and
i

250 Part II: Intermediate FoxPro

System File Edit Database Record Program Window


a ORDER_Q.
PRG
@ 16, “Supplier
() “Price
: @ 3, “Order Information Query
Fig. 7.25. 16. “Cost ”
Adding a second x
. SET COLOR TO N/W
READ to edit @ 15,24 SAY C->Keyword
field data. @ 15,35 SAY C->Descr
iC) ,61 SAY C->Qty_onhnd PICTURE “999939”
@ 17,18 SAY C->Supplier
@ 17,44 GET C->Price PICTURE “99999.99"
@ 17,53 GET C->Cost PICTURE “99993. 99"

* EOF: ORDER_9.
PRG
4+

those linked to it by the relationships as a unit. If you change something


that breaks up that unit, you may end up with records in the controlling
database that are not linked to records in the controlled databases or vice
versa. In any case, the integrity of the databases’ relations will be
questionable.

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.

A truth about computer programs is that as a program’s capabilities


increase, its difficulty of use also increases. FoxPro is no exception;
although it is far easier to use than its competitors, maneuvering around
various windows and dialogs can become tiresome. In this chapter you
learn how to set up MS-DOS subdirectories to organize your FoxPro
databases and create batch files to ensure that you can access FoxPro from
the right directories. You also learn how to use Views to ease the task of
setting up different databases and index files.

You learn about two techniques to speed working in FoxPro: keyboard


shortcuts and keyboard macros. You are introduced to using the Com-
mand window to enter commands, often a faster way to do something
than choosing menus and working through dialogs. Finally, you receive a
brief introduction to FoxPro programming, which you can use to auto-
mate many tasks. In all, this chapter’s objective is to ease some of the
burden of working with FoxPro and let you take the first steps toward
being a FoxPro power user.

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.

Using Subdirectories and Batch Files


tf you know anything about MS-DOS you're aware af the DOS Ale Struc
ture, and how # Stores the program and data Mes If yow're wathaniliae
With this system, this section will serve as 2 bref introdmetinn. beease
that file Structure really can help or hinder your use of RaxPra IF Yor
Want to lear more about MS-DOS and 8s Me directory Sractare, there
are many excellent books on that subject. For now, thoagh yor need to
krow some basics.
Before MS-DOS 2.0, PC computers Stored all their Mes QW One STOR aa
the disk. MS-DOS borrowed from the UNIX philosophy ad allowed the
Creation of directories and subdirectories, If fe example, yor had Riles
related tT an accounting system, you could create a Swbeirectary named
ACCTING and put the program files there. Withia ACCHNG. YR COU
Create a subdirectory for the general ledger, name 8 GL. and place the
general ledger Hes in & Ther you could create Subdirectory fr acconass
payable and pat AP Riles there, and so forth Hgure S12 Shows how sack
directory Structure Coukd be created and used.
Along with directories and subdirectories: You Reed tO underst
and the
Concept of the curren? erection You can move around ia the
reckaxnker
Working from different anes using the MS-DOS OD (Qharge Directo
ry)
command. If you wart to work from your ACCTING Subdiire
ntary, dr
example, you see the DOS command
CD \ACCTING
‘ Chapter 8: FoxPro Tips, Tricks, and Techniques 23 4

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

to move to that subdirectory. After changing to a directory, any com-


mands you issue must refer to programs in that directory, because that is
the current directory.

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

Using Different Subdirectories


When you installed FoxPro, the installation program created a directory in
which to put FoxPro (if you used the default, this directory is called
C:\FOXPRO on a hard drive) and a number of subdirectories to store the
demonstration program, the tutorial, and the template files. Figure 8.2
shows the directory structure created during installation.

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.

A FoxPro application is a complete set of database files, indexes, forms,


and reports that form a stand-alone system. For example, you might have
an application that tracks customers and contacts, such as the example
quick start applications. You also might have a FoxPro accounting applica-
tion, an inventory application, or other applications, none of which share
database files. For each of these applications, you can create a subdirec-
tory and run FoxPro from there. FoxPro then works only with the files
and programs in that subdirectory.
Chapter 8: FoxPro Tips, Tricks, and Techniques 235

Figure 8.3 shows an example of a FoxPro set up that I use. Each of


the applications is completely separate. When I run FoxPro from the
application subdirectory, FoxPro “knows” about only the files in that
directory. As a result, when I open a dialog that gives me a scrollable list
of files, I see only the files applicable to the application with which I’m
working. I also removed the directories \FOXPRO\SAMPLES, \FOXPRO
\FOXVDEMO, and \FOXPRO\TUTORIAL.

~ Fig. 8.3.
FOXPRO A FoxPro application An example of

FoxPro
ADV_BOOK A FoxPro application applications in

Separate
A FoxPro application directories

TEMPLGEN FoxPro’s Template Generator files

TEMPLCOD FoxPro’s Template Generator code

To create subdirectories for FoxPro applications, use the MS-DOS MD


(Make Directory) command. Move to the FoxPro directory by entering

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.

System File Edit Database Record Program Window

< View >


Fig. 8.4. Default Drive:
° 2 <On/0fFf>
The View Files erathser < Clear Path >
, <Files >
aealor, USGL C ] Alternate... <Clear Alternate>
change the path < Mise >
FoxPro will use. Procedure... <Clear Procedure>

Help...
C: \FOXPRO\FOXHELP.
DBF
Resource...
C: \FOXPRO\FOXUSER.
DBF

FILE SELECTION

System File Edit Database Record Program Window

Enter path name


Fig. 8.5. C: \FOXPRO
The Enter Path [..] Drive
Name dialog. LADUBOOK]
CADUI
CAMMS]
CBOOK] Directory | FOXPRO
[DEMO]
CFOXUDEMO]
CGOODIES] « Select »
CSCREENS]
CTEMPLCOD] < Open >
CTEMPLGENJ
< Cancel >
Chapter 8: FoxPro Tips, Tricks, and Techniques Day,

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

C:\FOXPRO\AMMS;C: \ FOXPRO \ ADV


FoxPro will look for needed files in the AMMS subdirectory first, then the
ADV subdirectory, issuing an error message only if the needed file is not
found in either one. Be cautious with long paths, though, because they
can get slow and complicated with many directories and subdirectories. If
you set up your subdirectories well, you seldom will need to set long
paths in FoxPro.

Eliminating Subdirectory Errors


When you set up the FoxPro directory and subdirectory structures, you
can use MS-DOS batch files to ease the chore of setting the path correctly
and moving to the right current directory before you start FoxPro. A
batch file is a file with a series of MS-DOS commands strung together.
When you enter the name of the file at the DOS command prompt, DOS
reads the files and executes the commands in order. A nice use of a batch
file is to move to a directory, set a path, and execute a program. I have a
batch file named AMMS.BAT, for example, that contains the following
commands:

PATH = C: \FOXPRO;C: \ DOS;C: \ UTILS;C: \BAT;C: \


CD \FOXPRO\AMMS
FOXPRO

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.

Creating a batch file is simple. If your computer has a word processor or


text editing program, use it to create the file. If not, you can start FoxPro
and issue the command

MODIFY COMMAND C:\ filename.bat


238 Part IJ: Intermediate 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.

Although there are many philosophies on hard drive organization, figure


8.6 shows how I set up mine. I’m comfortable with this organization and
you may find it an excellent starting point.

Utility Programs
Fig. 8.6.
A hard disk drive Batch Files
directory setup.
DOS Programs

ADU_BOOK

Customizing FoxPro with CONFIG.FP


As you use FoxPro more and more, you will find that you want certain
settings to be different from FoxPro’s defaults. For instance, I dislike hav-
ing FoxPro beep at me when I have filled a field, and I prefer my FoxPro
systems to require pressing the Enter key to leave a field. FoxPro gives
you the capability to customize many things through a file named
CONFIG .FP.

The CONFIG.FP (Configuration.FoxPro) file can contain startup defaults


for many of the SET commands. These settings include changing the
actions of the function keys, different color settings, and the initial View
for FoxPro to use, among other things. When you start FoxPro, it looks for
a CONFIG.FP file in the current directory. If none exists there, FoxPro
looks for the file in the directory in which the FoxPro program itself re-
sides. If none exists, FoxPro uses the default settings.

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.

Creating a CONFIG.FP file is simple. Invoke FoxPro in the normal way,


then create the CONFIG.FP file either from the File Open menu, choosing
the Program file type, or from the command line, with the command
MODIFY COMMAND CONMFIG.FP. FoxPro opens the text editor (see fig.
8.7), which you use to create the CONFIG.FP file. When you're finished,
press Ctrl-End, or Ctrl-W to save and close the Text Editor window, nam-
ing the file as you go.

System File Edit Database Record Program | Window


CONFIG. FP ¢ =
BELL=OFF
CONFIRM=ON ;
SAFETY=OFF
TEDIT=\BRIEF\B Fig. 8.7.
UP=\BRIEF\B Entering a
F3="D0 TEST; "_
CONFIG.FP file in
the text editing
window,

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.

4 AUTOSAVE OFF/ON—AUTOSAVE tells FoxPro when to save


database changes to the disk. If this is set to OFF, FoxPro will
saves changes when you close a data-entry or edit window or if
you wait five minutes without doing anything. If you set
AUTOSAVE to ON, FoxPro saves the changes each time a READ
is executed (each time you’re finished entering or editing).
AUTOSAVE ON is a bit slower, because FoxPro writes the data
240 Part II: Intermediate FoxPro

to the disk more often, but it is safer—you run less risk of


losing data that you have entered should the computer’s power
fail.
Q) BELL ON/OFF—This command sets the beeper on or off for
error conditions or when an input field is filled. I dislike FoxPro
beeping at me, so I turn it off.

“I CLOCK ON/OFF—The CLOCK command turns on or off a clock


in the upper right corner of the screen.

) CONFIRM ON/OFF—If CONFIRM is ON, a FoxPro user must


press the Enter key to exit a data-entry field. If CONFIRM is
OFF, the cursor will move to the next field when the current
one is full. I set CONFIRM ON, which makes data-entry
consistent; an Enter is always required. Otherwise, sometimes
you will have to press Enter (when you enter a name that is
less than the size of the character field, for example) and
sometimes you will not (when you fill the field or enter a
logical value, for instance).
I) HEADING ON/OFF—With HEADING ON, FoxPro puts the field
names at the top of a Browse window. With it OFF, those
headings don’t appear.

4 MOUSE <1 to 10>—This command controls the sensitivity of


the mouse to movement; the higher the number, the faster the
mouse pointer moves. The default is 5.

( SAFETY ON/OFF—With SAFETY ON, FoxPro asks whether you


want to overwrite a file when you save a file with the name of
an existing file. With SAFETY OFF, FoxPro assumes that you
want to overwrite that file and will not ask. Be careful; you
cannot retrieve a file that’s been overwritten.

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

The semicolon acts as an Enter, telling FoxPro to execute the command. If


you leave it out, you will have to press the Enter after the F2 key. Now,
when FoxPro starts, you can execute the DO TEST command simply by
pressing the F2 key.

Other possibilities for function key assignments might be to open specific


files or views, set format files, or carry out longer strings of commands. If
Chapter 8: FoxPro Tips, Tricks, and Techniques 241

you want to string two or more commands together, separate them by a


semicolon. The following line,

F2="SET VIEW TO AMMS; SET FORMAT TO AMMS_FMT; APPEND”

executes three commands just as if you had entered, in the Command


window, the following commands:

SET VIEW TO AMMS


SET FORMAT TO AMMS_FMT
APPEND

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:

TEDIT =”\ BRIEF \B”

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.

Using Views To Set Up FoxPro


As you have worked through the chapters and examples in this book, you
have learned something about views and how they can ease FoxPro’s
complexity. A view records information about the way FoxPro is set up
when the view is created or saved. Once a view is created, you can dupli-
cate that environment by opening the view from the File menu, or by
issuing the Command window command SET VIEW TO view_name. The
following list presents the information that is saved with a view, all of
which is set up when you recall the view with the Open or Set command:

) All database, index, alternate, and format files currently open in


all the work areas.

J All fields defined in the set fields list.

4 All relations you have established in the Relations box of the


View Setup window.
242 Part II: Intermediate FoxPro

I All filters for each of the open databases.

“I The default drive and path settings.


Y Several other settings used in advanced FoxPro applications.

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.

System File Edit Database Record Program - Windou

Save View as:


Fig. 8.8.
)
The Save View
| ra ROTABLE. VUE
Drive
As dialog.

« Save »

CJ] All Files

The complication of defining views is you must be certain that everything


is set just as you want it. You must make sure that the database files are in
the work areas you want them in. Indexes must be set along with the
controlling index. Fields and formats must be right, and any relations must
be in place (and tested to make sure that they’re right). Be very careful
that the view is what you want it to be, because if you plan to use that
view when running a report or inquiry, and later find you have the wrong
Chapter 8: FoxPro Tips, Tricks, and Techniques 243

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.

Opening and Using Views


Once you have a view defined, you can open that view any time you want
FoxPro to use the configuration you specified when you saved the view.
Choose Open from the File menu, change Type to View and choose the
view you want. FoxPro will assume the configuration of the view.

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.

System File Edit’ Database Record Program Window Report

Save Report As:


Fig. 8.9.
"OR RPTL.FRX | eS piers

Directory

« Save »

{1 All Files < Cancel >

QX_RPT1. FRX

CX] Save Environment


244 Part II: Intermediate FoxPro

Using Keyboard Shortcuts


Most of the time, you will find that working with the mouse is the fastest
way to get something done in FoxPro. But for those FoxPro users working
without a mouse, or for the times when you have both hands on the key-
board and don’t want to reach for the mouse, FoxPro provides keyboard
shortcuts for many commands. The more important keyboard shortcuts
are as follows:
Window menu

Ctrl-F7 Initiate the Move Window sequence


Ctrl-F8 Initiate the Size Window sequence
Ctrl-F10 Zoom the window
Ctrl Ei Cycle through the windows on-screen
Ctrl-F2 Make the Command window active

Browse menu

Ctrl-T Toggle the delete status of the current record. Each


time you press Ctrl-T, the current record changes
between marked for deletion and not marked.

Edit menu

Ctrl-F Find a record


Ctrl-G Find again, based on the same criteria as the previous
Find
Ctrl-A Select all

When a record has been selected

Ctrl-X Cut the record’s fields


Ctrl-G Copy the record’s fields

Once fields have been cut or copied

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.

< Save > < Neu >

< Restore > < Clear >

<Set Default> < Clear All >

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

Any other macro key combinations assigned also are shown.

Storing and Playing Back a Macro


To store a macro, select New in the Keyboard Macros dialog. FoxPro dis-
plays the Macro Key Definition dialog, which asks for a key combination
246 Part II: Intermediate FoxPro

to which the keystroke sequence will be assigned. Possible key combina-


tions include:

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.

System File Edit ©Database’ Record. Program Window

Fig. 8.11.
The Stop
Recording dialog. Stop recording CTRL_X?

< Insert Literal > « OK »

< Insert Pause > < Continue >


C-) Key to Resume
€ ) Seconds < Discard >

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

Using the Command Window


As you have used FoxPro, you have grown accustomed to seeing the Com-
mand window, because FoxPro keeps it open most of the time. FoxPro
sometimes puts seemingly incomprehensible strings into the Command
window (see fig. 8.12). Now is a good time to learn what that window
does and how you can use it to be more efficient with FoxPro.

System File Edit Database Record Program Window


2 Command
MODIFY COMMAND Untitled
USE C: \FOXPRO\AMMS\ASSY_MST.
DBF
MODIFY REPORT QX_RPT1. FRX
Fig. 8.12.
USE ASSY_DET. DBF
The Command
SELECT A
USE C: \FOXPRO\AMMS\EXP_PART. DBF window, with
BROWSE LAST
SET RELATION TO INTO B ADDITIVE
FoxPro-generated
SET BELL OFF commands.
SET DEVELOPMENT OFF
SET NEAR ON

Before FoxPro, PC database programs operated from a command line—


you entered a command string and the program interpreted it and took
whatever action you requested. Figure 8.13 shows the FoxBase+ screen,
with a command to open a database file and two index files on the com-
mand line.

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.

Serial Number FPD@12777

. USE customer INDEX custnane, cust_num


Command Line ]icc:>]FoxBASE+ 2.18 ¢c) 1988
|
Fox Softuare
Enter a FoxBASE+ command

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.

Understanding a Command String


Command strings are essentially sentences; they contain a verb and an
object. A command string may also contain one or more modifiers or
arguments, things that tell FoxPro how to do something. In the command

USE CUSTOMER INDEX CUSTNAME, CUST_NUM

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.

Nearly all FoxPro commands have numerous modifiers, such as the


INDEX clause in the USE command, or optional phrases. The only way to
learn the nuances of the many FoxPro commands is to spend some time
reading the FoxPro User’s Guide, which lists every command with all its
modifiers and options. If you keep it handy while working in FoxPro, you
can consult it to learn commands.
Chapter 8: FoxPro Tips, Tricks, and Techniques 249

Re-using a Previous Command


The Command window has several features you should know. You can
use the arrow keys to move back to a previous command. Once the cur-
sor is on the command you want, press Enter to reexecute the command.

Editing and Re-using Previous Commands


Before executing a previous command, you can edit it using standard Fox-
Pro editing features. The newly edited command will be put at the end of
the command stack in the window, and the original command will be left
in place (see fig. 8.14). Notice how the original command is back in its
place and the edited command is at the bottom.

System File Edit Database Record Program Window


a s Command
SELECT A
USE C:\FOXPRO\NAMMS\EXP_PART. DBF
BROWSE LAST <— This “BROWSE LAST" was edited p
SET RELATION TO INTO B ADDITIVE to remove the "LAST." The Fig. 8.14.
SET BELL OFF edited command 'BROWSE"
SET DEVELOPMENT OFF The Oe
SET NEAR ON window, with
INDEX ON QX_INTID TO C:\FOXPRO\AMMS\TEST. ID
BROWSE + is appended to the end of the BROWSE LAST
command uindou modified to
BROWSE.

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

Using the Programming Language


First, you should understand that you don’t have to learn to program to
use FoxPro. At this point, you’re able to use most of FoxPro’s power and
you haven’t had to program yet. However, programming in FoxPro can
help you do things quickly and easily.

If you want to gain some programming skills, the FoxPro programming


language is a good place to start, because it is quite easy to learn and use.
By learning the basics of FoxPro programming, you can automate some
FoxPro tasks that views and macros cannot do. So, even if the thought of
programming scares you, take a deep breath and read on; you will be glad
you did.

FoxPro programs range from a series of simple commands, much like an


MS-DOS batch file, to enormously complicated systems. Chapter 11 covers
the basics of systems programming in FoxPro; in this chapter, you learn
the fundamentals of creating and running a FoxPro program to automate
some FoxPro tasks.

Creating a Simple Program


The most basic FoxPro programs are simply series of commands that a
user might enter in the Command window. A common series of actions in
FoxPro might be as follows:

1. Move to the correct work area.

2. Open a database file and index file in that work area.

3. Edit the file.


4. Close the database.

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.

System File, Edit Database Record Program Window


eh : : UNTITLED. PRG
SELECT 1 && move to work area 1
USE amms INDEX amms && open and index amms. dbf
EDIT Fig. 8.15.
USE && closes the database_ A simple FoxPro

program in the
text-editing
window.

To execute a FoxPro program, choose Do from the Program menu. Fox-


Pro presents the Do dialog, with a list of available PRG files. Select the one
you want, and FoxPro will execute it. When the last line of the program is
executed, FoxPro returns control to you.

Using the Trace Window


No matter how simple a program seems, it can run into problems. FoxPro
helps you find the error by opening a window showing the PRG file that
was running, and it highlights the line on which an error was encoun-
tered. You can then correct the error, save the file, and try again. Still,
there are times when you will encounter an unexplainable error and need
more help. The Trace window was made for these times.
252 Part Il: Intermediate FoxPro

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.

System File Edit Database Record Program Window


= Trace
SELECT 1 && move to work area 1
USE amms INDEX amms && open and index amms. dbf
° EDIT
Fig. 8.16. USE && closes the database
The Trace
window, tracing
program
execution.

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

When you designed your multiple-file relational databases, you did so


because you wanted to keep information that logically belonged together
in separate databases and be able to reference that information based on
related fields. Reporting on these databases is no different; you want to be
able to report on one database and draw information from other, related
databases to put into the report.

FoxPro’s power and flexibility in creating and viewing relational databases


is matched by its capability to create clear and concise reports easily.
Reporting on a variety of databases, related in many different ways, is not
a difficult task. You also learn several advanced techniques of reporting on
these multiple-file database systems.

In this chapter, you extend your knowledge of FoxPro’s report-writing


capability to include working with multiple databases. How you want to
report on a relational database system depends on how the databases are
related and what you need from the report. You learn what information
can go into the Detail Band of the report, and what is best placed in
Groups.

255
256 Part Il: Intermediate FoxPro

Designing Your Report


Because reports are often the most visible result of a FoxPro database sys-
tem, it’s important that your reports be clear and easy to read. Following
are some basic guidelines for designing your FoxPro reports:

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.

3. If the information in the report has natural groupings, use the


Data Grouping facility of the FoxPro Report Writer to group your
report. If, for example, you’re reporting on orders your company
has processed, you might want to group the records by the name
of the customer, so that each customer’s orders appear together in
the report. Or you might want to group on the order date so that
all orders received each day are grouped. Grouping data breaks
down a large mass of information into smaller, understandable
chunks.

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.

Creating Multiple-File Reports


Just as with single-file databases, you use FoxPro’s Layout Window to cre-
ate reports on relational database systems. The first thing you must do is
make sure that all your files are set up in the proper work areas, with the
necessary indexes controlling them.
Chapter 9: Reporting on Multiple Database Systems 2 57

Setting Up the Databases for Reporting


As with any FoxPro project, you first must design the report output and
plan your approach for making FoxPro do what you want. An example
report is shown in figure 9.1. This report is done on an ORDER database, a
related CUSTOMER database, and another related INVNTRY database. The
structures of these databases are shown in figures 9.2, 9.3, and 9.4, respec-
tively. The relational fields are CUST.NAME between ORDER and CUS-
TOMER, and PART_NUM between ORDER and PART_NUM. Figure 9.5
shows the View window of these three databases set up to generate the
example report.

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

Order Sales- Part Part Part


Date person Number Quantity Keyword Price

01/01/90 IWZ CENTURY 1 CARBURETOR 125.25


12/15/90 DIZ CL 1754428 4 SHIFT 0.00
FREE TA CALA TOLL RTP ALP OSPIL TA TE LTE PID UELIS TTP LIND CAR DD CD TERA TATE TAIN ET UALR EDI MUL TDD TOE? H

Hess Aviation Inventory


3342 Aviation R
Portland OR 88423
CALM RCL AT OEELATAATACT Mt AS AT DE LT BT Pe BEY ET AT lad Bt AB PAS AR KAY AadA sel PY fot Pa At Tit PAT At ONE Lt YY RTE EUR BS BS SAY ST At Dt EY PS? ae

Order Sales- Part Part Part


Date person Number Quantity Keyword Price

01/15/90 CHZ IN E-2398 at ROLLER Uoaths)


01/15/90 CHZ IN E-2514B 1 SHIM 1.20
12/12/89 DJZ ME 1178 10 FENDER 0.00
CTP LED LLP ID PSA IBTIE (PEPLTEP OLD GD IAPIDITS ELE OLED INRA LELILLE OLED TIA TE BAT EE ELS 2

ORDER is the controlling database, so fields from ORDER go into the


Detail Band. ORDER is indexed on CUST_NAME, to ensure that the report
is printed alphabetically by customer name.

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

? 58 Part II: Intermediate FoxPro

CUST_NAME in the ORDER field, but for illustrative purposes, this report
will group on the CUST_NAME field in CUSTOMER.

System File Edit Database Record Program Window


Structure for database: C:\FOXPRO\BOOK\ORDER.
DBF
; Number of data records: 17
Fig. 9.2. ; Date of last update +: 81/27/98
The controlling Field Field Name Type Width Dec
database in the 1 CUST_NAME Character 25
2 ORDR_DATE Date 8
example report. 3 SALESPERS Character 3
4 PART_NUM Character 12
5 Qty Numeric 5
xx Total ** S54

Command
SELECT B
SELECT A
SELECT B
SELECT C
select a
display struc

System File Edit Database Record Program, Window


Structure for database: C:\FOXPRO\BOOK\CUSTOMER. DBF
A Number of data records: 15
Fig. 9.3. Date of last update : 81/07/90
One controlled Field Field Name Type Width Dec
np 1 CUST_NUM Character 6
database in the Z CUST.NAME Character 25
example report. 3 ADDR_1 Character 25
4 ADDR_Z Character 25
SeiGiny Character 15
6 STATE Character 2
(6 WAS? Character 3
8 PHONE Character 18
3 CONTACT Character 18
1@ CREDIT Numeric 8 é
11 LAST_PUR Date 8 select a
12 LAST_AMT Numeric 8 ie display struc
13. PREFERD Logical 1 select b
x* Total x 153 clear
display sturc
display struc
Chapter 9: Reporting on Multiple Database Systems 2? 59

System File Edit Database Record. Program Window


Structure for database: C:\FOXPRO\BOOK\INUNTRY.
DBF
Number of data records: 3287 Fig. 9.4.
Date of last update * 12785/89
Field Field Name Type Dec The second
1 PART_NUM Character controlled
Zz KEYWORD Character
3)
Bete Peeestae database in; the
4 SUPPLIER Character example report.
5 QTY_ONHND Numeric
6 QTY_RORDER Numeric
7 PRICE Numeric
8 COST Numeric
w AUTO_RORDR Logical
18 COMMENTS
** Total xx

Side File Edit. Database: Record Program Window

« View > Work Areas « Relations > Fig. 9.5.


The View
<On/0FF> > + ORDER 4 |>ORDER ; ee
“CUSTOMER ¢ CUSTOMER window for the
+ INUNTRY INUNTRY databases in the
example report.

«Setup >

«Browse?

« Open >

<Close >» |ORDER Records: 17

Placing Fields in the Detail Band


As with single-file databases, the Detail Band holds fields from the
database through which FoxPro proceeds as it generates the report. In a
relational database system, this will almost always be the controlling
database in a relation. FoxPro starts at the top of the database file accord-
ing to the controlling index, and steps through each record. If there is a
260 Part II: Intermediate FoxPro

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.

System File Edit Database Record. Program Window’ Report

Fig. 9.6. Reegz (bit Page Header


The Layout view PgHead
5 i ig PgHead
with fields from PgHead Order Sales- Part
the controlling PgHead Date _— person Number Quantity
Detail ij
database.
PgFoot
PgFoot
PgFoot
PgFoot

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.

Adding Fields to the Detail Line


The important advantage of related databases is, of course, to be able to
draw information from related files. You will often want to put informa-
tion on the detail line that comes from a related database. To do this, sim-
ply put the field on the line (using Add Field from the Report menu).
Select Expr in the Field dialog, and in the Report Expression Builder dia-
log, select the related database in the database box. Figure 9.7 shows the
related INVNTRY database selected, and the KEYWORD field chosen from
the scrollable list.
Chapter 9: Reporting on Multiple Database Systems 261

System File Edit Expression |

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.

PART_NUM INUNTRY | > ALIGNMENT


> KEYWORD _BOX
DESCR _ INDENT
SUPPLIER « Verify > _LMARGIN
QTY_ONHND _PADUANCE
QTY_RORDER « OK » _PAGENO
PRICE _PBPAGE
COST Amer
Aue
dae
me
eat
ik
sr
Tie
oe
A < Cancel > _PCOLNO

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.

System File Edit Database Record Program Window Report


Preview
Fig. 9.8.
Page preview of
Sales- Part
the report with
person Number Quantity Keyword
CHZ 1486-5589 3 BEARING the Detail Band
CHZ 1488-5589 3 PACKING defined.
CHZ 1488-5589 3 BEARING
CHZ 1468-5589 3 REGULATOR
CHZ 1488-5589 3 KIT
CHZ 1488-5589 3 RESISTER
CHZ 14908-5589 3 TUBE
CHZ 1408-5589 3) LOCK
CHZ 1488-5589 3 LATCH
CHZ 1488-5589 g BOARD
CHZ 1488-5589 3 CYLINDER
CHZ 1488-5589 3 SWITCH
CHZ 1488-5589 3 SPRING
CHZ 1486-5589 3 RING
CHZ 1488-5589 3 KIT
« More > Column: 3)
262 Part Il: Intermediate FoxPro

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.

Grouping on a Related Database


Grouping data lends clarity to your report. Nearly all reports benefit from
grouping the data in some form. Data grouping can be done on a related
database if the controlling database is indexed or sorted on the link to the
related database. In the example, for instance, the report can be grouped
on the customer name, with information from the CUSTOMER database
in the Group Header, because the ORDER database is indexed on
CUST_NAME.
Adding a Data Grouping is the same as with a single-file database, except
that here you use a field in the controlled database as the Group expres-
sion. Figure 9.9 shows the Group expression on the controlled database
field, CUSTOMER—>CUST_NAME.

System File .Edit - Expression :

Fig. 9.9.
Grouping on the [eth J [string] Ltostea:
value of a Break ‘expr>:
related database customer->cust_name
field.

Field Names: Database: Variables:

CUST_NUM CUSTOMER > ALIGNMENT


“BOX
INDENT
« Verify LMARGIN
PADUANCE
« PAGENO
PBPAGE
(Gord
Gods)
Red
CG)
Co
I « Cancel PCOLNO

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

Placing Related Database Fields


in the Group. Header
The Group Header is an excellent place for information drawn from the
related database. Increase the number of lines in the Group Header with
the Add Line option on the Report menu, and place the necessary fields
in the Group Header. As with related database fields in the Detail Band,
use the Field Expression Builder dialog to designate the database and field
you want. Figure 9.10 shows the Layout View with CUSTOMER informa-
tion included, and figure 9.11 shows the page preview of this report.

System’ File Edit Database .Record Program Window Report


CHAPSRPT.FRX
Group Header
Fig. 9.10.
Layout view with
CUSTOMER
information in
the Group
Header.
Part Part Part
Date person Number Quantity Keyword Price
ORDR_DAT PART_NUM

System File Edit Database Record Program Window Report


Preview

Fig. 9.11.
33423 Airport Drive Page preview of
Cinncinnatti OH 43554 arelarional

Order Sales- Part Part database report.


Date person Number Quantity Keyword
81/15/98 DJZ IN E-Z398 3 ROLLER
81/15/9398 DJZ IN E-Z2398 1 ROLLER

Cosars Continent
4923 Wilson Rd
Smyrna TN 33423

Order Sales- Part Part


Date person Number Quantity Keyword
61/83/90 CHZ LP 1466-5589 SEAL
81/88/98 CHZ LP 1425-3378 BEARING
81/83/98 CHZ ME 38129 CHAIN
« Done » <¢ More » Column: 8
264 Part II: Intermediate FoxPro

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.

Generating Controlling Database


Ordered Reports
In the example just presented, the controlling database had a field,
CUST_NAME, on which the report could be properly ordered. Often this
is not the case; you will want the report ordered on a field in a controlled
database. You must resort to some slightly more sophisticated techniques
to achieve your purpose.

Suppose that, instead of having a field CUST_NAME as the relational field


between ORDER and CUSTOMER, you have followed my advice and used
a customer number to link the two. ORDER and CUSTOMER each have a
field named CUST_NUM, and the relation is based on those fields; the con-
trolling database is indexed on the CUST_NUM field. Now, if you use the
same report and run it, you get a different result (see fig. 9.12).

System File Edit Database Record Program Window Report |


2 ; Preview

Fig. 9.12. West Hill Florist


A relational 32981 2nd Ave So
report based on pa: 2
CUST_NUM Order Sales- Part Part Part
eA Date person Number Quantity Keyword Price
instead of 81/82/98 «=iJZ CASCADE 6845 3 3.88
CUST_NAME. 81/22/89 = DJZ IN E-2138 188 PULL 214. 88

OshKosh Cow Company


S534 E. Dairy Rd
shkosh WI 88332

Order Sales- Part Part Part


Date person Number Quantity Keyword Price
81/81/38 JUZ CENTURY 1 CARBURATOR 125.25
2/15/98 DJZ CL 1754428 4 SHIFT 8.88

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.

One way to solve this problem would be to program a custom report.


Though some FoxPro programming can be fun, programming reports sel-
dom falls into that category. To accomplish an alphabetical report, you
need to use one of two FoxPro techniques: the JOIN command, or index-
ing on the related database.

Using JOIN for Reporting


The JOIN command enables you to mesh certain fields of two databases,
forming one database that is a combination of the two. You can, for
instance, join the ORDER and CUSTOMER databases into one database
that has all the order information along with the necessary CUSTOMER
information. Then you can create a simple, single-file report on the result-
ing database, still using a Group to present the CUSTOMER database
information.

The format of the JOIN command is

JOIN WITH alias TO new_database_file FOR logical_expr FIELDS


field_list

First, set up your FoxPro environment by putting each of the databases to


be joined in a separate work area. Start the join by moving to the work
area of one of the two databases to be joined:

SELECT ORDER
Decide the name of the new file; here it will be ORD_CUST.

Decide which logical expression will cause a record to be written to the


new joined database file. Here, you would use

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:

CUST_NUM ORD_DATE QTY SALESPERS PART_NUM

and these fields from CUSTOMER:

CUST_NAME ADDR1 ADDR2 CITY STATE ZIP

Now put all this together into the JOIN command, issued in the Command
window as follows:

JOIN WITH CUSTOMER TO ORD_CUST FOR CUST_NUM = ;


CUSTOMER-—>CUST_NUM FIELDS CUSTOMER—>CUST_NAME, ;
CUSTOMER->ADDR1; CUSTOMER->ADDR1,;
CUSTOMER->CITY,CUSTOMER->STATE, ;
CUSTOMER-—>ZIP, ORD_DATE, QTY, SALESPERS, PART_NUM
Note the aliases used for references to the CUSTOMER and INVNTRY
databases in the logical expression and field list. Because the ORDER work
area is the active work area, no alias is required for references to fields in
ORDER.

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

System File Edit Database Record. Program Window «Browse

; 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

System File. Edit Database Record. Program Window Report


JOINED_1.FRX
Page Footer
Fig. 9.14.
The Layout view
of a report on a
joined database.

Order Sales- Part Part Part


Date person Number Quantity Keyword Price

PgFoot
268 Part II: Intermediate FoxPro

System File Edit Database Record Program Window Report


. Preview
Fig. 9.15.
Page preview of 33423 Airport Drive
the joined Cinncinnatti OH 43554

database report. Order Sales- Part Part


Date person Number Quantity Keyword
81/15/98 DJZ IN E-2398 3 ROLLER
81715798 DJZ IN E-2398 1 ROLLER

TN 33423

Order Sales- Part Part


Date person Number Quantity Keyword
81/83/98 CHZ LP 1488-5589 3 SEAL
81/88/98 CHZ LP 1425-3378 1@ BEARING
81/83/38 CHZ ME 38129 18 CHAIN
« Done » < More >» Column: 8

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

CUST_NUM <> CUSTOMER-—>CUST_NUM

the resulting file would have had thousands of records.

Indexing on a Related Database


There is another way to order this report correctly. It is possible, once
the databases’ relations are set, to index the controlling database on values
in the related record of the controlled database. In this way, you can
order the ORDER database on the CUST_NAME for each related record.

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

causes FoxPro to create an index on ORDER that is based on the value in


the related CUSTOMER-—>CUST_NUM field. Figure 9.16 shows the Browse
window of ORDER, with the records in the order of their customer name,
even though CUST_NAME is not part of the ORDER database.

System File Edit Database Record Program Window Browse


ORDER La CUSTOMER

ESE | EE ae ee. Fig. 9.16.


81715/98 Bill’s Plumbing Z3z3 N. Z3rd ;:
81/15/98 Comar 33423 Airport Drive The Browse
81/83/38 Cosars Continent 4423 Wilson Rd windows of
Hess AViation Inventory |334Z Aviation R ;
Metropolitan Corp 8823 E. Military Rd ORDER and
Northend Music SouthCenter Mall CUSTOMER.
Northwest Microsystems, In]18968 127th Pl
Oriental Cuisine 9432 International A
OshKosh Cow Company 5534 E. Dairy Rd
81/81/98 Pickett’s House of Music
12/15/98 S & C Autos 3342 E. Elwood
62/81/98 SCIL P.O. Box 2231
83/24/98 Studio 11 Art 2231 Fourth
18/18/89 T. Moore & Associates unknown
82/82/98 West Hill Florist 32981 Znd Ave So
81/82/98
81/22/89

17 records indexed

The CUSTOMER Browse window is also shown so you can match


CUST_NUMs to CUST_NAMEs and see the ORDER database is, in fact,
ordered alphabetically by the customer name associated with the
CUST_NUM relational field. By doing this, you can now process the
controlling database using this new index, and know that the records
will be presented in alphabetical order, based on their related
CUSTOMER-—>CUST_NAME field. With this technique, the Layout of the
report is the same as the first example; the only thing changed is the
index that controls the ORDER database during the report processing.

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

Using Advanced Reporting Techniques


FoxPro provides some advanced reporting techniques, primarily for use
on character and memo fields, which may have varying amounts of infor-
mation in them.

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

System File Edit Database Record Program Window Report


CUSTCONT.FRX
Fig. 9.17.
The Report Customer Contact Report
Expression dialog
showing the
Report Expression:
Stretch
Vertical ly Expr... > contact->cont_rpt

Format... > Width: 41


option.

I Styles... {X] Stretch Vertically


] Totaling... [C J Suppress Repeated Values
{ ] Float as Band Stretches

« 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

System File Edit Database Record Program Window Report


be Preview

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

OshKosh Cow Company


5534 E. Dairy Rd
Pasture 8
Oshkosh WI 88332
« Done » < More > Column:

17 records indexed

System File. Edit Database Record Program Window Report


Preview

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

i < Done » < More > Column:

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

VAT De Part II: Intermediate FoxPro

System File Edit Database Record Program Window Report


Preview

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

« Done » < More >» Column:

17 records indexed

System File Edit Database Record Program Window Report


: = Preview
Fig. 9.21.
leld.
The same fie S) Customer Contact Report
not floating. Date: 81/27/98
Time: 11:19:58

West Hill Florist


32981 2nd Ave So

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

« Done » < More » Column:

17 records indexed

Using Relational Reports


Using relational reports is little different from running a report on a single
database system. Reports can be run from the Database Menu with the
Report option, or from the Command window. In each case, there are a
number of options you should understand.
Chapter 9: Reporting on Multiple Database Systems 29>

Using the Database Report Menu


To run a report from the FoxPro menu, choose Report from the Database
menu.
In figure 9.22, you see the Report dialog. In this dialog, you can specify
the many options that are available to you when you run a report. These
options modify settings for the report as well as the report’s destination.

System File. Edit Database Record Program Window

Fig. 9.22.
Report: The Report

‘Form... > CX] Environment Hoe Ose)


reporting
options.
{C ] Plain
{ ] No Eject
C J Summary
fe Heading

ES to Print « OK »
{ J To File
(+) Console On (¢ ) Console Off « Cancel >

Options available are:

J Scope —Allows you to specify a set number of records to be


printed, starting from the current position in the database.

J For —Allows you to specify a FoxPro expression that will limit


the report output to those records matching the expression.

1) While —Allows you to specify a FoxPro expression that will be


matched against each database record encountered. The report
will continue as long as the record matches the expression.

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

(J Heading —The Heading option enables you to add one or more


lines of text which will be centered and added to the top of
each page of the report. This text is additional to any PgHead
and Report Titles you may have placed on the Layout view.
When you select Heading, FoxPro presents an Expression
Builder that enables you to construct the lines of the Header.
‘4 To Print —Tells FoxPro to send the report to the printer. If this
is unmarked, the report will appear on the screen only.

“Y To File—Tells FoxPro to print the report to a disk file, rather


than the printer. A dialog will open to ask for the name of the
file.
“4 Console On and Console Of f—FoxPro echoes the report to the
screen if the Console On option is marked; otherwise, nothing
appears on the screen while the report is printing.

Using the Command Window


If you want to run the report from the Command window (or from a line
in a FoxPro program), the format is

REPORT FORM rpi_name [options]

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

REPORT FORM test HEADER NOEJECT


prints a report with a header and no page eject before the report.

Printing reports on complicated, related databases follows the same pro-


cedures as for simple, single-file systems. You will use Data Grouping
more often and will draw from the related databases, but the basic pro-
cesses are the same. Still, you will find times that FoxReport just will not
do the job. For those needs, FoxPro provides you with programming capa-
bilities for report writing.
Chapter 9: Reporting on Multiple Database Systems 275

Generating PRINTJOB and


ENDPRINTJOB Reports
Sometimes, you may encounter situations in which you don’t want to use
FoxReport and the Layout window to create a report, or you find you
cannot. For these situations, FoxPro provides the PRINTJOB and END-
PRINTJOB commands, which tell FoxPro to treat everything between
them as a report. You tell FoxPro what values to use for page length, right
and left margins, and other report parameters by setting System Variables.

To use PRINTJOB and ENDPRINTJOB, you must do a bit of FoxPro pro-


gramming. The pseudo-English format of such a program is as follows:

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.

The example presented is a bit complex. To learn how to use PRINTJOB


and ENDPRINTJOB, you should work through a simpler program; there-
fore, in the next section you learn how to use this technique with a single
database file.

Writing the Report Program


Figure 9.23 shows a simple report generated with PRINTJOB and END-
PRINTJOB commands in a program file.
276 Part II: Intermediate FoxPro

Customer Contact Report


Date: 01/27/90
Fig. 9.25.
A sim (2 rt TIDAL A COED TANMM CALETA AY ED RUAN DDD LAUTS ALOR CCE REMC! ITRELS ARALLL LITE TLL
i eve, Customer Number: 8 Name: Bill’s Plumbing
generated with a Contact Information:
NT, 02/01/90 CHZ 02/15/90 Purchased restoration materials
PRI JOB. Check next call for additional sheet metal,
ENDPRINTJOB hydraulic requirements
program. GEO ORDO UL ACO COU EAE CEG EAL O28 OOOO OE CEL ONT E EE ES Pe rare.

Customer Number: 5 Name: Comar


Contact Information:
11/30/89 CHZ 12/29/89 Discussed service/maintenance possibilities
Need to provide info on warranty tracking

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

Customer Number: 6 Name: Cosars Continent


Contact Information:
11/30/89 CHZ 01/15/89 Discussed warranty information on parts
presented last visit. Needs more
information on what is covered.

CT ACTION (DFE TROD COMPLICA ETD ALR EE EE CEI DT LTDA DMTaRet aE PEAT PY OY PI IR LE EAL 2

The program file that generated this report is as follows:

SET TALK OFF


* set up the database files and relations
SEEEGIOI
USE CUSTOMER INDEX CUSTNAME

SELECT 2
USE CONTACT INDEX CUST_NUM

SELECT aI
SET RELATION TO CUST_NUM INTO CONTACT

* set some print job variables


_RMARGIN = 80
_LMARGIN = 0
_WRAP = .T.

* start the printjob


PRINTJOB

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

* now reset alignment back to LEFT


_ALIGNMENT = "LEFT"

DO WHILE .NOT. EOF()


?
? REPLICATE(CHR(196)
,79 && put a line above the record
? "Customer Number:', CUST_NUM, 'Name: ',CUST_NAME
? "Contact Information:!
SELECT CONTACT && move to CONTACT database
DO WHILE CUST_NUM = CUSTOMER->CUST_NUM
? CONT_DATE, SALESPERS, FOLLOW_DTE, CONT_RPT
SKIP
ENDDO
SET CONSOLE OFF
WAIT
SET CONSOLE ON
SELECT CUSTOMER && move back to CUSTOMER
SKIP && go to the next record
ENDDO && loop back to start
ENDPRINTJOB

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.

When FoxPro runs a program with the DO command and encounters a


PRINTJOB statement, it knows to format output according to the values of
system variables. These variables control the number of lines to a page,
margins, and so forth. FoxPro continues to format the pages according to
these variables until it encounters an ENDPRINTJOB command. At that
point, FoxPro reverts to a screen-oriented program. By using PRINTJOB
and ENDPRINTJOB, you can create simple or complex reports and not
worry about line counts and page breaks.

Setting System Print Variables


The important system variables you use in PRINTJOB..ENDPRINTJOB
reports are listed below. You set them with a simple assignment state-
ment, such as

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

d _LMARGIN= <expnN> Sets the left margin, from 0 to 254


spaces from the physical left margin of the printer.

J _PCOPIES = <exprN> Number of copies to print.

J _PECODE=<exprC> A string of codes, usually printer codes,


that will be sent to the printer at the start of the PRINTJOB.
This can be used for printer set up codes that may be necessary.
Your printer manual will have more information on this. You
can use _PECODE to set the printer to different character sizes,
italics, bold letters or other options.

1 _PLENGTH = <exprN> Sets the page length. FoxPro will move


the printer to a new page, and print any header information
when it reaches the line defined by _PLENGTH.

LY _PSPACING = <exprN> Sets the line spacing for the report. You
can set line spacing from 1 to 3 lines.

“J _RMARGIN = <exprN> Sets the right margin.


There are many less-used system print variables described in the FoxPro
Commands & Functions manual.

Using the Program


To use a PRINTJOB..ENDPRINTJOB program, save the program with a file
name and DO that file name. By default, output will go to the screen. If
you want output to go to the printer, enter the following command before
you do the report file (you also can include it as a line in the report file):
SET PRINTER ON

If you want the output to go to a file, enter these two commands:

SET ALTERNATE TO /file_name


SET ALTERNATE ON
Chapter 9: Reporting on Multiple Database Systems 279

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

SET ALTERNATE OFF

when you're finished. Otherwise, everything that appears in the command


window also appears in the report file along with your report.

Writing reports with the PRINTJOB and ENDPRINTJOB commands


requires a bit of practice at FoxPro programming. This skill pays off as you
create more complex reports that may loop through different databases or
do different types of summaries depending on the data. For these reports,
you have to do some basic programming. The PRINTJOB and ENDPRINT-
JOB commands simplify the bookkeeping aspects of this programming.

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

Quick Start 3: Bui g an Application

Creating Applications with FoxPro

Programming with FoxPro


282 Part II: Advanced FoxPro
Quick
Start

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.

A FoxPro application is a shell of programs that do the things that you, as


a FoxPro developer, do with the various FoxPro menus and dialogs. The
shell takes care of the details of using FoxPro by opening the proper files,
setting up the correct parameters, and so on. A good application also
limits the menu items to those necessary for the specific application.

This quick start introduces you to building such an application system.


You learn how to create menus for the application, how to put programs
and reports you have written into the application or call FoxPro dialogs
directly from the shell, and how to test the application to make sure that
the application works. When you’re finished with this quick start, you will
have a basic knowledge of FoxPro application programming.

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:

il. Invoke FoxView by selecting FoxView from the Program menu or


entering FoxView in the Command window.

Press Enter when the FoxView opening screen appears to move to


the FoxView command line. There, you can tell FoxView what
database file to use with the USE database command. If you have
already created an input screen for this application and want to
use it, use the LOAD screen_name command. Figure QS3.1 shows
the FoxView command screen with a command to use the
database file CUSTOMER.

<C: \FOXPRO\BOOK> Sunday 02/84/96 j|ReEbR

Fig. QS3.1. Welcome to FoxVieu 3.8


Starting a Press Fi for HELP

FoxView session FoxView C: USE CUSTOMER


by using a 13 field¢s) loaded
database file.
FoxView C:>_

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

C:CUSTOMER.DBF @ 16,35 Page: 1

Fig. QS3.2.
The complete
FoxView screen
Customer Number form for the
Sa CUSTOMER
database.
Name
Address

City
Phone Contact

4. Save the design of your screen by pressing Esc to activate the


FoxView menu bar, moving to the Load pad (use the arrow keys)
and then moving the menu highlight to Save Table. Pressing the
Enter key will place the name of the current FoxView Table
(which is how FoxView saves screen forms) in the text editing
area at the lower left corner of the screen. Figure QS3.3 shows
FoxView waiting for the Table name.

Disk Gen

Current Alias {AF


Load Table {CUSTOMER Fig. QS3.3.
Save Table {CUSTOMER}
Entering a name
MAP Datafile {. dbf} for FoxView to
USE Datafile {CUSTOMER}
use in saving the
Append File {. dbf} FoxView table.
Import Format {. fmt}
Neu Config {.cfg}

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.

The bar titled FoxPro Advanced Application should be highlighted


(see fig. QS3.4). If it is not, use the up- and down-arrow keys to
highlight it and press Enter.

C: CUSTOMER. DBF 16,35 Page: 1

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

Select Template Program with the cursor keys: RETURN accepts

Te FoxView will place the message


Enter FILENAME of program to Generate

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

C:CUSTOMER.DBF ® 16,35 Page: 1

Fig. QS3.5.
Entering a name
for FoxView to
use in generating
an application
program.

Enter FILENAME of program to Generate

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

Do you really want to QUIT FoxView (y/n)?

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

288 Part III: Advanced FoxPro

Unfortunately, some releases of the template used to create this applica-


tion have a bug. Before you can run the program FoxView’s template just
created, you need to fix a little bug in the generated code. This bug
causes the Help file to be constructed incorrectly. If this is the case in
your application and you want to fix it, follow the next few steps. Because
the bug doesn’t affect the operation of the application, you may want to
let the bug go.
To fix this bug, open the Program file CUST.PRG from the File Open
menu or enter MODIFY COMMAND CUST.PRG in the Command window.
When the text editing window with CUST.PRG opens, choose Find from
the Goto menu and find the first occurrence of mx (see fig. QS3.6).

System File Edit Database Record Program Window


2 CUST. PRG

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

System File Edit Database Record Program Window


CUST. PRG

* --- Removes all non-alpha characters from a string replacing then


* --- uith a space Fig. QS3.7.
The fixed lines in
FUNCTION alphaonly CUST.PRG.
PARAMETER msource
mlen = LENCmsource)
mtarget = ’’
FOR mxZ = 1 TO mlen
mtarget = mtarget + IIFCISALPHACSUBSTRCmsource,
mxZ, 1>), SUBSTRCmsource, mxZ>
ENDFOR
RETURN mtarget

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.

Unfortunately, many FoxPro applications will require greater sophistica-


tion, particularly if they use multiple databases. Still, the process to create
a more complex application is not terribly difficult. The process does,
though, require some knowledge of FoxPro programming, and partic-
ularly, of how to create a menu structure in FoxPro. Chapter 11 is
devoted to the joys of FoxPro programming. In this quick start, you can
enter the program as the program is presented and have a working appli-
cation when you’re done.

Creating Menus for an Application


As you have seen using FoxPro, menus are the heart of the graphical user
interface FoxPro uses. Although you could build an old-style command-
line driven application or one using “make a choice” menus, FoxPro pro-
vides you with all the necessary tools to emulate the menu-driven system.
The rest of this quick start shows you how to create an application using
FoxPro’s menus.
290 Part IJ: Advanced FoxPro

Defining Menu Pads


A FoxPro menu comprises two elements: the menu itself, with a number
of pads, and a pop-up menu associated with each pad. In creating a menu-
driven system, you need to define each of the menu pads and the options
that will be included in the pop-up menus for each pad. Figure QS3.8
shows a menu and a pop-up menu and defines the terms you need to
know.

Steet Record USER Ta <— Nenu bar

ae Menu Pads
Fig. QS3.8. Popup —~>
A menu and pop-
an Popup Bars
up menu, with
their elements
defined.

The first thing to do in creating a FoxPro menu application is to decide


what pads you want on the main menu. Then, for each pad, decide what
options you want to include. To implement the options, you may have to
write complete FoxPro programs, or you may be able to have the menu
program issue one or two commands. In the rest of this quick start, you
will see how to create a menu system similar to the one created with the
Advanced Application Generator in the first part of the quick start.

Creating a Menu Program


A menu program in FoxPro is a regular FoxPro PRG program file. Create
the program by choosing New from the File menu of FoxPro and specify-
ing Program for the type. A new text-editing window, UNTITLED.PRG,
will appear. Give the file a name by choosing Save from the File menu.
Now, you're ready to create a menu-driven application program. To create
your menu program, follow these steps:
ve Ww) sabe ‘ee 4—~ ~ Oa < ‘ besVy oi %
\e — font w “ rer
s mn)a= ve Ne) ~ \ehetory
Ww «@ =) we Ne) Ww W
N\ w\ id
\ oS ~ keyfo
“ ,
we AVY ‘oN MA os “~ ¥} a
; %
\ =
ee
hat)
ww we i s Ww
ww
\ &a
\
&oO ‘
\)
ww
’a et PN ‘abet—\ aa) eS —- ay
292 Part II]: Advanced FoxPro

System File Edit Database Record Program Window


eo : ; MENU_1. PRG
+ MENU_1. PRG
*: A test menu application for Quick Start 3
Fig. QS3.10. ao
MENU_1.PRG HIDE WINDOWS ALL
with each of the
DEFINE MENU main
menu pads
defined. DEFINE PAD file PROMPT "'\<Systenm"’
DEFINE PAD Goto PROMPT ''\<GoTo"’
DEFINE PAD Record PROMPT ''\<Record”’
DEFINE PAD Util PROMPT "'\<Utility"
DEFINE PAD quit PROMPT "'\<Quit"’

System File Edit Database Record Program


s MENU_1. PRG
*: A test menu application for Quick Start 3

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

ON SELECTION PAD file main ACTIVATE POPUP file_pop


ON SELECTION PAD goto main ACTIVATE POPUP goto_pop
ON SELECTION PAD record OF main ACTIVATE POPUP rec_pop
ON SELECTION PAD Util OF main ACTIVATE POPUP util pop
ON SELECTION PAD quit OF main DO quit_prc

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

ACTIVATE MENU main.

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

You now have a working menu program, as follows:

*: MENU_1.PRG
*: A test menu application for Quick Start 3

CLEAR
HIDE WINDOWS ALL
DEFINE MENU main

DEFINE PAD file OF main PROMPT "'\<System'’ AT 00, OO


DEFINE PAD Goto OF main PROMPT ''\<Goto" AT 00, 09
DEFINE PAD Record OF main PROMPT ''\<Record"! AT O00, 16
DEFINE PAD Util OF main PROMPT "'\<Utility'’ AT 00, 24
DEFINE PAD quit OF main PROMPT ''\<Quit" ATmOO;ES5

ON SELECTION PAD file OF main DO msg WITH ''System"


ON SELECTION PAD goto’ OF main DO msg WITH ‘'Goto"
ON SELECTION PAD record OF main DO msg WITH ''Record"™
ON SELECTION PAD Util OF main DO msg WITH "Utility"
ON SELECTION PAD quit OF main DO msg WITH "'Quit"

ACTIVATE 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

Saeed Record RUSRRTT Reres

Fig. QS3.12
The MENU_1.PRG
application in
operation.

Chose Record

Defining the Pop-up Menus for Each Pad


Each pad on the Main menu has a pop-up menu associated with the pad.
The bars of the pop-up menu reflect actions the user can take. For
instance, in the Record menu of the example, the user can add a record
by selecting Append or delete a record by choosing Delete. Each of the
selections on a pop-up menu correspond to some action you want FoxPro
to take when the user selects the bar. Adding pop-up menus to your
menus is not difficult—just follow these steps:
1. To add the pop-up menus to your menu program, move the
cursor to a blank line between the last DEFINE PAD line and
before the first ON SELECTION PAD line. Define the pop-up menu
associated with the Record pad using the DEFINE POPUP
command. You must give the row and column coordinates of the
upper left corner of the pop-up menu. Usually, this will be in line
with—or a column or two to the right of—the start of the menu
pad with which the pop-up menu is associated. Figure QS3.13
shows MENU_1.PRG with this pop-up menu defined.
Quick Start 3: Building an Application 295

System File Edit Database Record. Program. Window


MENU_1. PRG
DEFINE PAD Goto OF main PROMPT ''\<GoTo” AT 88, 88
DEFINE PAD Record OF main PROMPT ‘’\<Record'' AT 88, 14
DEFINE PAD Util OF main PROMPT "'\<Utility" AT 88, 22
DEFINE PAD quit OF main PROMPT "'\<Quit” AT 88, 31 Fig. QS3.13.
The first pop-up
ON SELECTION PAD file OF main DO msg WITH ‘'System"
§ ON SELECTION PAD goto’ OF main DO msg WITH "GoTo"
menu defined in
ON SELECTION PAD record OF main DO msg WITH ''Record" MENU_1.PRG.
ON SELECTION PAD Util OF main DO msg WITH "Utility"
ON SELECTION PAD quit OF main DO msg WITH "Quit"

ACTIVATE MENU main

DEFINE POPUP goto_pop FROM @1, 97

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.

System File Edit Database Record Program Window


i. MENU_1. PRG
DEFINE PAD Record OF main PROMPT "'\<Record' AT 88,
DEFINE PAD Util OF main PROMPT "'\<Utility" AT 88, 22
DEFINE PAD quit OF main PROMPT "'\<Quit" AT 88, 31 Fig. QS3.14.
ON SELECTION PAD file OF main DO msg WITH ‘'Systen"’
Adding define
ON SELECTION PAD goto OF main DO msg WITH "GoTo" bars with
ON SELECTION PAD record OF main DO msg WITH ''Record"”
ON SELECTION PAD Util OF main DO msg WITH "Utility"
prompts for the
ON SELECTION PAD quit OF main DO msg WITH Quit” pop-up menu.
ACTIVATE MENU main

DEFINE POPUP goto_pop FROM 61, 87


DEFINE BAR 1 OF goto_pop PROMPT ‘’\<Next"’
DEFINE BAR 2 OF goto_pop PROMPT '’\<Previous"
DEFINE BAR 3 OF goto_pop PROMPT ‘'\<Top of file"
DEFINE BAR 4 OF goto_pop PROMPT ''\<Bottom of file"
296 Part Ill: Advanced FoxPro

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

DEFINE PAD Record oF Ma in PROMPT \<Record AT 88, t4—


DEFINE PAD Util OF ma in PROMPT Neutilita’ AT 88,
DEFINE PAD quit OF ma in PROMPT AcQuit” AT 88, St
Fig. QS3.15.
ON SELECTION PAD file OF main bo Ss
NSQ WITH “Susten" |
Adding the ON ON SELECTION PAD goto OF main bo Ss
NSO WITH “GoTo"
SELECTION..DO ON SELECTION PAD record OF main bo Ss
NSg WITH “Record”
ON SELECTION PAD Util OF main bo Ss
NSQ WITH “utilita’
command for the ON SELECTION PAD quit OF main ba Ss
MSY WITH “Quit!
Goto pop-up
ACTIVATE MENU main
menu.
DEFINE POPUP goto_pop FROM Ot a
DEFINE BAR 1 OF goto pop PROMPT N<Next"
DEFINE BAR 2 OF goto pop PROMPT “\<Previous’
DEFINE BAR 3 OF goto pop PROMPT r “A<Top of file”
DEFINE BAR 4 OF gato S p oO Pp PROMPT "\<Botton of file"

ON SELECTION POPUP goto_pop DO goto _proe NITH BARQO

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

System File Edit Database Record Program .Window s )


ba MENU_1. PRG &

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:

ON PAD pad_name OF menu_name ACTIVATE POPUP


popup_name

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.

System’ File Edit Database Record Program: Window


s MENU_1. PRG

ON PAD File OF main ACTIVATE POPUP file_pop Fig. QS3.17.


ON PAD goto OF main ACTIVATE POPUP goto_pop The ON
ON PAD record OF main ACTIVATE POPUP rec_pop
ON PAD Util OF main ACTIVATE POPUP util_pop PAD..ACTIVATE
ON PAD quit OF main RETURN POPUP
commands
replace the ON
SELECTION PAD
commands.
ee
SEE ee

298 Part III: Advanced FoxPro

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

* define the Main menu

DEFINE MENU main


DEFINE PAD file OF main PROMPT ''\<System'' AT 00, OO
DEFINE PAD Goto OF main PROMPT ''\<Goto" AT 00, 08
DEFINE PAD Record OF main PROMPT "'\<Record"™ AT OO, 14
DEFINE PAD Util OF main PROMPT "'\<Utility"™ AT 00, 22
DEFINE PAD quit OF main PROMPT ‘'\<Quit"’ Ate OOF Sst

* define the File pop-up menu

DEFINE POPUP file_pop FROM 01,01


DEFINE BAR 1 OF file_pop PROMPT ''\<FoxPro Help"
ON SELECTION POPUP file_pop DO file_proc WITH BAR()

* define the Goto pop-up menu

DEFINE POPUP goto_pop FROM 01, O07


DEFINE BAR 1 OF goto_pop PROMPT ''\<Next''
DEFINE BAR 2 OF goto_pop PROMPT ‘'\<Previous"™
DEFINE BAR 3 OF goto_pop PROMPT ''\<Top of file"
DEFINE BAR 4 OF goto_pop PROMPT "'\<Bottom of file"
ON SELECTION POPUP goto_pop DO goto_proc WITH BAR()

* define the Record pop-up menu

DEFINE POPUP Rec_pop FROM 01,13


DEFINEBAR 1 OF rec_pop PROMPT ''\<Append"
DEFINEBAR 2 OF rec_pop PROMPT ''\<Browse"
DEFINE BAR 3 OF rec_pop PROMPT "'\<Edit"'
DEFINE BAR 4 OF rec_pop PROMPT ''\<Delete"
DEFINE BAR 5 OF rec_pop PROMPT ''\<RecaLl"
ON SELECTION POPUP rec_pop DO rec_proc WITH BAR()

* define the Utility pop-up menu

DEFINE POPUP util_pop FROM 01, 21


DEFINE BAR 1 OF util_pop PROMPT ''\<Report"
DEFINE BAR 2 OF util_pop PROMPT "'\<LabelL"
ON SELECTION POPUP util_pop DO utl_proc WITH BAR()
Quick Start 3: Building an Application 299

* tie pop-up menus to Main menu pads

ON PAD fi le OF main ACTIVATE POPUP file_pop


ON PAD go to OF main ACTIVATE POPUP goto_pop
ON PAD re cord OF main ACTIVATE POPUP rec_pop
ON PAD Ut il OF main ACTIVATE POPUP util_pop
ON PAD qu it OF main RETURN

AeSitaltac he Main menu

ACTIVATE MENU main


PROCEDURE rec_proc
PROCEDURE file_proc
PARAMETER mbar
DO CASE
CASE mbar = 1
DO msg WITH ‘tHe Llyay

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

400 Part Il]: Advanced FoxPro

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

ERG Record SRR

Edit
Add
Fig. QS3.18. Brouse
MENU_1,.PRG in Delete
action with pop-
Customer Number
up menus. a

Name [ES SUR Its


Address EVA] MAT Bre)

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.

Defining FoxPro Actions


lo make your menu program work, you now replace the messages your
PROCEDUREs send to the screen with actual FoxPro commands that do
what the pop-up menu choice requires. In many cases, particularly in sim-
ications. these can be one or two FoxPro commands. In more
COMB applications, the pop-up menu choice will activate a FoxPro
PROCEDURE ofr program file Pop-up choices could also activate yet
another pop-up menu or menu
You ais need to add FoxPro commands to open the correct database file
and appropriate index files. To make your menu program into a working
program, perform the following steps

j. At the beginning of the program, insert a USE dbfname INDEX


index1 command to open the database file and attach an index
file to the database. If your program requires a FORMAT file.
insert that line here also. If you have a VIEW file defined that sets
ip FoxPro as you want FoxPro, you could use a SET VIEW TO
se_file instead. In Figure QS3.19, the commands have been added
to the menu program

Syustes File E4it Batabase Becord Progran Uindou


i

i pplication progran using nenmss and popups +

Fee RR a ee ae Ee ea Fig. OS3.19-


os coaren Adding
sl / comments and

USE customer IMUEL cuxt_sun SET commands,


and opening the
database and
OLLAZ
HIDE WINDOWS ALL

DEFINE NEA wrain

DEF IRE PAD file OF wain PROMPT “s<Sucten” AT 0, 22


DEF IKE PAD Goto OF nain PROMPT ’s<GoTo” AT 62, 2
DEFIRE PAD Becord OF wain PROMPT “"s<Record” AT o, 16
DEF IRE PAD Util OF nain PROMPT “<Utility’ AT 8, 24
DEFINE PAD quit OF wnain PROMPT “s<Quit” AT 62, 33
ZOQ2Q rar
aera ea ew Ls en Ses ied oy, eS ee ee ee ee

IJ: Advanced FoxPro

Put a DO WHILE loop around your ACTIVATE MENU command,


to ensure that the program continues until the user chooses Quit.

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.

. For each CASE statement in the PROCEDUREs that process pop-up


menu choices, replace the DO msg command with commands
necessary to execute the right FoxPro actions. Figure QS3.20
shows the PROCEDURE for the Records menu, with FoxPro
commands replacing the DO msg command.

System File Edit Database Record Program Window


MENU_MST.PRG
PARAMETER mbar
DO CASE
CASE mbar = 1
APPEND BLANK
Fig. QS3.20. DO show_rec
READ
The PROCEDURE CASE mbar = 2
for the Record BROWSE
CASE mbar = 3
pop-up menu, DO shouw_rec
with commands READ
CASE mbar = 4
replacing the DO shouw_rec
testing messages. IF .NOT. DELETEDQ)
DELETE
ENDIF
CASE mbar = 5
DO shouw_rec
IF DELETED)
RECALL
ENDIF
ENDCASE

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

Note This doesn’t replicate the application created in FoxView with


the Advanced Application Template, which allows the user to
create or modify reports of labels. Such a program is beyond
the scope of this quick start. If you want to include such an
option, you can open the CUST.PRG file and cut and paste the
appropriate PROCEDUREs from that file into your application.
Quick Start 3: Building an Application 403

6. The Quit choice of the System pop-up menu must restore


FoxPro’s environment to what it was before the program was run.
To do so, insert a USE command, which closes the database and
index files, a DEACTIVATE MENU command to take your
application menu off the screen, and a SHOW WINDOWS ALL
command to display the screen windows that were open when
you started.

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:

PROCEDURE show _rec

Open a new text window with the program CUSTOMER.FMT in


the window by using the File Open menu option. Choose Select
All from the Edit menu, and then choose Copy. Close the
CUSTOMER.FMT window, place the cursor in MENU_1.PRG just
below the PROCEDURE show_rec line, and choose Paste from the
Edit menu. The entire CUSTOMER.FMT file will be placed in the
procedure show-rec, which allows you to call the file from the
MENU._1.PRG.

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

* define the Main menu

DEFINE MENU main


DEFINE PAD file OF main PROMPT ''\<System'' AT 00, OO
DEFINE PAD Goto OF main PROMPT ''\<Goto" AT 00, 08
DEFINE PAD Record OF main PROMPT ''\<Record'' AT 00, 14
DEFINE PAD Util OF main PROMPT ''\<Utility'' AT 00, 22
DEFINE PAD quit OF main PROMPT ''\<Quit" AT 00, 31

* define the File pop-up menu

DEFINE POPUP file_pop FROM 01,01


DEFINE BAR 1 OF file_pop PROMPT '"'\<FoxPro Help"
ON SELECTION POPUP file_pop DO file_proc WITH BAR()
304 Part Ill: Advanced FoxPro

* define the Goto pop-up menu

DEFINE POPUP goto_pop FROM 01, 07


DEFINE BAR 1 OF goto_pop PROMPT ''\<Next"'
DEFINE BAR 2 OF goto_pop PROMPT '‘\<Previous"
DEFINE BAR 3 OF goto_pop PROMPT ''\<Top of file"
DEFINE BAR 4 OF goto_pop PROMPT ''\<Bottom of file"
ON SELECTION POPUP goto_pop DO goto_proc WITH BAR()

* define the Record pop-up menu

DEFINE POPUP Rec_pop FROM 01,13


DEFINE BAR 1 OF rec_pop PROMPT "'\<Append'"'
DEFINE BAR 2 OF rec_pop PROMPT ''\<Browse"
DEFINE BAR 3 OF rec_pop PROMPT ""\<Edit*"
DEFINE BAR 4 OF rec_pop PROMPT ''\<Delete"
DEFINE BAR 5 OF rec_pop PROMPT "'\<Recall"*
ON SELECTION POPUP rec_pop DO rec_proc WITH BAR()

* define the Utility pop-up menu

DEFINE POPUP util_pop FROM 01, 21


DEFINE BAR 1 OF util_pop PROMPT ''\<Report"
DEFINE BAR 2 OF util_pop PROMPT ''\<Label*!
ON SELECTION POPUP util_pop DO utl_proc WITH BAR()

* tie pop-up menus to Main menu pads

ON PAD file OF main ACTIVATE POPUP file_pop


ON PAD goto OF main ACTIVATE POPUP goto_pop
ON PAD record OF main ACTIVATE POPUP rec_pop
ON PAD Util OF main ACTIVATE POPUP util_pop
ON PAD quit OF main RETURN

* start the Main menu

ACTIVATE MENU main

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.

SS Coe ee CH Cee tS mcsssm Program BOE CE

Fig. QS3.21. ‘ Cancel


Resume
The Program
pop-up menu, |
XdTs)
Step
with DO
Talk
MENU_1.PRG
Compile
added to the
FoxVieu
bottom. FoxDoc
FoxGraph.. .

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

System File Edit Database Record Program Window

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

Debugging Your Application


Unfortunately, applications don’t always run perfectly the first time. In
fact, you can get errors when you try to run the program, because at that
time FoxPro “compiles” the program lines into a format that FoxPro can
execute faster; if FoxPro finds problems with the code, FoxPro will stop
and issue an error message (see fig. QS3.23). You must return to the text
editing window and correct the error. Fortunately, FoxPro is nice enough
to highlight the line in which the error was detected.

: 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

DEFINE PAD file OF main PROMPT "\<Systenm"’ AT


DEFINE PAD Goto TO main PROMPT ''\<GoTo" AT
DEFINE PAD Record OF main PROMPT “\<Record"’ AT
DEFINE PAD Util OF main PROMPT "'\<Utility" AT
DEFINE PAD quit OF main PROMPT "'\<Quit" AT

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.

Using the Trace Window


The Trace window allows you to see your program in action, step-by-step.
To use the Trace window, do the following:
1. Select Step from the Program menu. This causes FoxPro to
execute your program one line at a time. Then start your program
running, using either the Do choice from the Program pop-up
menu or the DO MENU_1.PRG from the same pop-up menu if
your program is in the active window.
ee

408 Part III: Advanced FoxPro

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.

System File- Edit Database Record Program Window

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

*--- start the main menu


ACTIVATE MENU main
<Cancel> <Resume>

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

Systen File Edit Database Record Program Window

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

Breakpoint Qx--- start the main menu


marker ACTIVATE MENU main
<Cancel> <Resume>

6. If you need to watch the value of variables in your program, the


Debug window enables you to do so. Open the Debug window
from the Window menu along with the Trace window. In the left
side of the Debug window, enter the variable name you want to
watch. Then, as you run or Trace your program, the value of that
variable will appear in the right side of the window. By clicking in
the column between the right and left sides of the Debug
window, you tell FoxPro to suspend execution of the program
when the value of that variable changes. Figure QS3.26 shows the
Debug window, with a variable listed and a breakpoint set.

System File Edit». Database Record Program Window

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.

Including Functionality in the Application


The functions that make up an application depend, of course, on the appli-
cation. Some applications can be very simple, providing only basic input
and output routines. Other applications can be quite complex, with
menus and submenus calling many different FoxPro functions and many
custom FoxPro programs to perform specific operations.

Generally, though, your application should include a way to enter, edit,


search, and report on each of the databases in the system. If your system
has multiple database files with relations between them, you should have
a way to report and view the database files.

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.

Defining the Menus Structure


Before you start writing the application system, lay out the menus and
pop-up menus you will need to control the system. Doing this enables you
to work from a plan, rather than adding and changing on the fly. Figure
10.1 shows the menu and pop-up menu layout for a simple application;
figure 10.2 shows a more complicated, multifile layout. In both cases, you
can see that, having defined these layouts before you start, your job of
creating the menus and pop-up menus in the application will be easier.
Chapter 10: Creating Applications with FoxPro 41 4

Main Menu pads: Record Utility Quit

Help” ig Fig. 10.1.


C J

Database Menus and pop-


Previous up menus for a
simple
application.

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

Using the Menu and Pop-up Menu Structure


Philosophies about constructing an application are as numerous as appli-
cation developers; everybody has his own style. Another approach is the
top-down approach, in which the highest level of the application menu is
written and tested, then the next level is written and tested, and so on
until the lowest level utility programs are done.
314 Part III: Advanced FoxPro

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.

Prototyping means building the skeleton of the application; the menus


and pop-up menus. You can test to see whether you have all the functions
your application needs and whether they can be accessed from the cor-
rect menus. Prototyping an application ensures that you don’t get to the
last pop-up menu and realize that you cannot access an important func-
tion that was on a menu just deactivated. Once your menus and pop-up
menus are complete and tested, and you know the tough programs can be
done, you’re ready to fill in the application routines.

First, though, you must create the menus and pop-up menus for your
application.

Creating and Using Menus


When you define a menu, FoxPro does not put the menu on-screen auto-
matically. The DEFINE statements describe this menu to FoxPro and store
the definition in FoxPro’s memory. When you activate the menu, FoxPro
puts the menu on-screen and enters its menu-processing mode. In this
mode, the user presses arrow keys or clicks with the mouse to move in a
menu and make choices from pop-up menus. Figure 10.3 shows a FoxPro
menu with the menu elements named.
a
Chapter 10: Creating Applications with FoxPro 41 5

System File Edit .Database Record Program © Window

Fig. 10.3.
A FoxPro menu,
with its elements
labeled.

Defining the Menu


An application, with all its menus, pop-up menus, and FoxPro statements
is a FoxPro PRG program file. The first step is creating an application, and
then opening a PRG file. The sample application in this chapter has been
created as a program file with the New option of the File menu and saved
as CHAP10.PRG.

The next—and easiest—step in creating an application menu is to define


the menu. The format of the DEFINE MENU command is

DEFINE MENU menu_name [MESSAGE <exprC> ]

Each menu has a name, specified in the command as menu_name. This


name is then used to refer to this specific menu with the ACTIVATE
MENU and DEACTIVATE MENU commands. You can add an optional mes-
sage, which is displayed on line 24 of the screen, or a location specified in
a SET MESSAGE TO row, column command. The following line defines a
menu named TOP_ MENU:
DEFINE MENU TOP_MENU MESSAGE "Choose a pad and press Enter”
The DEFINE MENU command tells FoxPro there will be a menu with the
name you give it. To add choices to the menu, you must define the menu
pads.
316 Part II]: Advanced FoxPro

Defining the Menu Pads


Each menu pad has four attributes that must be defined. First, the pad has
a name, which is used for several menu-processing commands. Second,
each pad also has an owner. The owner is the menu of which this pad is a
part. Third, each pad has a prompt, which is the string of characters that
make up the visible pad on the menu. Finally, each pad has a location,
which is specified in FoxPro’s standard row, column format. The format of
the DEFINE PAD command is as follows:

DEFINE PAD pad_name OF menu_name PROMPT <exprC> [AT


row, col],{[ MESSAGE <exprC>]

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:

DEFINE PAD file OF TOP_MENU PROMPT "File” AT 00,00

DEFINE PAD edit OF TOP_MENU PROMPT “Edit” AT 00,06

DEFINE PAD search OF TOP_MENU PROMPT “Search” AT 00,12

DEFINE PAD quit OF TOP_MENU PROMPT "Quit" AT 00,19

Standard FoxPro menus have a character highlighted in each prompt.


Pressing that character from the keyboard activates the pad without hav-
ing to move to the choice with the arrow keys. You can emulate that
behavior in your own menus and pop-up menus. In the PROMPT expres-
sions, the two-character combination \< makes the character following it
the hot character for that prompt. For example, these commands,

DEFINE PAD report OF TOP_MENU PROMPT "\<Report”


DEFINE PAD record OF TOP_MENU PROMPT "Re \<cord”

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.

Defining the Action when a Pad Is Selected


When a user moves to a pad and presses Enter or its hot character, some
action is expected. You define what that action is with the ON SELEC-
TION PAD command. The format of this command is as follows:

ON SELECT PAD pad_name OF menu_name command


Re es
Chapter 10: Creating Applications with FoxPro 417

The command can be any FoxPro command, procedure, or program


name. Often the command will be the name of a pop-up menu that you
want to activate. The following are some examples of ON SELECTION
PAD commands:

ON SELECTION PAD file OF TOP_MENU ACTIVATE POPUP file_ pop

ON SELECTION PAD edit OF TOP_MENU DO EditProc

ON SELECTION PAD quit OF TOP_MENU RETURN

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.

Some application developers prefer to have a pop-up menu associated


with a menu pad appear whenever the pad is selected. This can be done
with the ON PAD command. The format of this command is as follows:

ON PAD pad_name OF menu_name ACTIVATE POPUP pop-up_ name

The pop-up_name is the name of a defined pop-up menu. If you use ON


PAD..ACTIVATE POPUP, the associated pop-up menu appears whenever
this menu pad is selected. ON PAD..ACTIVATE POPUP and ON SELEC-
TION PAD are exclusive, you can use one or the other on each menu pad,
but not both.

Activating the Menu


Once you have defined the menu and each of the pads on that menu, and
specified what action FoxPro should take when a pad is chosen, you can
invoke this menu, putting the menu into action with the ACTIVATE
MENU command. The format of this command is as follows:

ACTIVATE MENU menu_name

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

Deactivating the Menu


Just as a menu has to be activated to be put on-screen, the application
must deactivate the menu when the application is done with the menu
The format of this command is

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.

One note of caution about deactivating menus: when a menu is deacti-


vated, control of the program returns to the line following the ACTIVATE
MENU command. So, if your program executes one or more PROCEDURE
subroutines in response to the menu inputs, don’t deactivate the menu in
the middle of the processing; everything will stop and you will be back to
where you started.

Creating and Using Pop-up Menus


Unlike menus, which are on-screen all the time that they are activated,
pop-up menus appear only while a choice needs to be made trom them
Pop-up menus can list choices for the user, or can contain lists of pro-
grams, files, or databases. In any case, pop-up menus present choices trom
which the user can select.

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.

Defining a Pop-up Menu


As in creating a menu, the first thing to do in creating a pop-up menu is to
define it. The format of the DEFINE POPUP command is more complex
than that for a menu, because the pop-up menu can take more forms and
Chapter 10: Creating Applications with FoxPro 319

provide more options. The basic format of the DEFINE POPUP command
is as follows:

DEFINE POPUP pop-up menu_name FROM row, column

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:

DEFINE POPUP pop-up menu_name FROM row, column


MESSAGE <exprC>

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.

Using The PROMPT FIELD Option


If you define a pop-up menu with the PROMPT FIELD field_name option,
where field_name is the name of a field in the active database, FoxPro
places all the values of that field into the pop-up menu for selection by
the user. This can be useful when you want the user to choose a value
that exists in the database. You present a pop-up menu with the PROMPT
FIELD option; the user cannot choose anything but a valid value in the
field.

Consider the following DEFINE POPUP command:

DEFINE POPUP name_pop PROMPT FIELD CUST_NAME FROM


10,10 TO 30,40

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

420 Part III: Advanced FoxPro

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.

Using The PROMPT FILES Option


The PROMPT FILES option of the DEFINE POPUP command does the
same thing as the PROMPT FIELD option, except that the pop-up menu is
filled with the names of files in the current directory. The format of this
variant of the DEFINE POPUP command is as follows:

DEFINE POPUP pop_name PROMPT FILES LIKE <skeleton> AT


row, col

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.

Using The PROMPT STRUCTURE Option


The last of the three prompt options is PROMPT STRUCTURE. This option
places the fields of the active database into the pop-up menu. The format
of this option is

DEFINE pop_name PROMPT STRUCTURE AT row, col


Chapter 10: Creating Applications with FoxPro 42 1

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:

DEFINE POPUP STRC_POP PROMPT STRUCTURE AT 10, 10 TO


10, 30

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

Defining Each Bar


For most pop-up menus, you will define each bar individually. To do so,
use the DEFINE BAR command. The format of this command is as follows:

DEFINE BAR 1 OF pop-up menu_name PROMPT <exprc>

where pop-up menu_name is the name of a defined pop-up menu and


exprC is the prompt expression. The number assigned to the bar will be
used later to determine which bar a user has chosen. The bars should be
numbered consecutively, starting from the top bar.

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:

DEFINE BAR 1 OF SYS_POP PROMPT “Help”

DEFINE BAR 2 OF SYS_POP PROMPT “Database”

DEFINE BAR 3 OF SYS_POP PROMPT "Open"

DEFINE BAR 4 OF SYS_POP PROMPT "—”

DEFINE BAR 5 OF SYS_POP PROMPT "Quit”

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.

Taking Action on a Pop-up Choice


When a user makes a choice from a pop-up menu, your application must
take some action based on that choice. In menus, you used the ON SELEC-
TION PAD to define the action for each pad as part of the menu definition
process. With pop-up menus, rather than defining an action for each
choice as part of the definition, you define a FoxPro PROCEDURE for the
pop-up menu.
Chapter 10: Creating Applications with FoxPro 423

>
Fig. 10.7.
A pop-up menu
created with
DEFINE BAR
commands.

To define what PROCEDURE is to be executed when a pop-up selection is


made, use the ON SELECTION POPUP command. The format for this com-
mand is

ON SELECTION POPUP pop-up menu_name command

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 PROMPT() returns the character expression that made up the


PROMPT for the choice the user made.

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,

ON SELECTION POPUP SYS-POP DO SYS_ PROC WITH BARC)


324 Part Il: Advanced FoxPro

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:

PROCEDURE /ile_ pop


PARAMETER /ile_ name
statements to take action with the file_name chosen
RETURN

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.

Creating a menu system with associated pop-up menus and procedure


files can seem complicated. But, in fact, the process is quite straightfor-
ward. Following is a quick summary of the steps required:

1. Define the menu, using the DEFINE MENU command.

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

4. For each pop-up menu associated with the menu, do the


following:

a. Define the pop-up menu, using the DEFINE POPUP


command.

b. Specify a procedure file to be executed when a choice is


made from the pop-up menu, using the ON SELECTION
POPUP command. (Cases can occur when you don’t use
a procedure to process the choice, but these cases will
be rare.)

c. Create the procedure file to process the choice.

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.

Adding a Help System


Another feature that users have come to expect of any application pro-
gram is a help system. Your application program should provide one—if
for no other reason than to alleviate the number of calls you get asking for
help. Fortunately, FoxPro provides a simple and direct means of giving
your application a sophisticated help system.

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

Creating the Help Database


A help database for your application is created just as you would create
any FoxPro database, using the New option of the File menu. Your help
database needs at least two fields, a character field with a length of 30
named TOPICS and a memo fieid named DETAILS. (You could have other
fields as well, which could be used to fine-tune the help system, but that’s
for pretty advanced applications. )
You should have one database record for each help topic you want to
present to the user. Each record in the TOPIC field should be a one- or
two-word title for a specific topic, such as Append or Browse. These
entries can also be more application-specific, such as Add Customer, Cus-
tomer Report, or Entering a Contact.

For each record, place the help text in the memo field. Help text can be
any length.

Providing a FoxPro-Type Help System


To implement your application help system, place the following line in
your application’s FoxPro code:

SET HELP TO belp_file- name

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.

Creating a Context-Sensitive Help System


Context-sensitive help systems bypass the requirement for the user to
choose a help topic. If the application provides context-sensitive help,
Chapter 10: Creating Applications with FoxPro A2U.

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:

SET TOP TO topic


Topic refers to the value in the TOPIC field of the help file record you
want to display. For instance, if you want to provide a help screen when a
user is entering information into invoices, you could include in the help
database the topic Entering Invoices. Figure 10.8 shows the help file
INV_ HELP with this record.

System File Edit Database Record Program Window Browse


= INU_HELP 2
Fue i a Fig. 108.
Entering Invoices Memo An INV_HELP file
Entering Customers Memo
Reports Memo record.
4

Each Topic has Help text in the Memo field

When the application program starts the process used to enter invoices,
you should include the following commands:

SET HELP TO INV_ HELP


statements in the application program
SET TOPIC TO "Entering Invoices”
428 Part IJ: Advanced FoxPro

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

«Topics » <¢ Next > < Previous > oon

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.

Defining and Using Windows


As you may have noticed, FoxPro uses windows. You can have your
application program use windows as well. Just as with FoxPro’s windows,
your application program’s windows can be opened, moved, sized and
closed by the user. If you want, though, you can open a window which
cannot be moved or sized or closed. As with FoxPro’s windows, you also
can specify the colors of each individual window, allowing you to have
one color for one part of the application and another color for another
part, or one color for one type of window and another color for another
type of window. Windows for application programs can be completely
controlled by the application developer.
Chapter 10: Creating Applications with FoxPro 429

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.

The basic format of the DEFINE WINDOW command is

DEFINE WINDOW window_name FROM row, col TO row, col

Window_name gives this window a name, which will be used to ACTI-


VATE, DEACTIVATE, HIDE, and SHOW the window. The first set of row,
col numbers indicate the location on-screen where the upper left corner
will be; the second set defines the lower right corner. If you include a
border for the window, the window dimensions include the space taken
by the border.

Options for the DEFINE WINDOW command include the following:

4 TITLE <exprC> The character expression will be the title of


the window, centered in the top border of the window

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

CHR() is a FoxPro function that changes an integer value to its character


equivalent. Screen characters are stored in the computer as integers from
0 to 255 (some are not printable to the screen). The CHR() function con-
verts an integer value to a character value.
The following is an example, which gives you the same border as the
PANEL option:

DEFINE WINDOW winl CHR(219), CHR(219), CHR(221),


CHR(221), CHR(219), CHR(219), CHR(219), CHR(219)
Other options for the DEFINE WINDOW command are as follows:

QO CLOSE or NOCLOSE. If you specify NOCLOSE, the user will not


be able to close the window; the window must be closed by
your application program. CLOSE allows the user to close the
window. CLOSE is the default.

1) FLOAT or NOFLOAT NOFLOAT. This means that the user will


not be able to move the window on-screen. FLOAT is the
default, allowing the user to move the window.

“4 GROW or NOGROW. Specifies whether the user will be able to


change the size of the screen. NOGROW prevents window re-
sizing. NOGROW is the default and allows the user to change
the window size.

4) ZOOM or NOZOOM. Determines whether the user can ZOOM


the window to full-screen size. NOZOOM prevents zooming.
ZOOM is the default and allows the window to ZOOM to full-
screen size.

QO SHADOW. If SHADOW is specified, the window will have the


standard FoxPro shadow on the right and bottom margins.
Shadows serve no purpose other than to make the window
visually more appealing.

“¥ COLOR. You can specify the color of the window. For a more
detailed explanation of how to set colors, see the following
section.

(J COLOR SCHEME. Again, refer to the following section for


information about color schemes.
Chapter 10: Creating Applications with FoxPro 441

Putting the Window On-screen


To put a window on-screen, use the following command:

ACTIVATE WINDOW window_name

Window_name is the name you included in the DEFINE WINDOW com-


mand. Once you activate a window, all output from your program will go
to that window; other windows become inactive.

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.

You could also issue an ACTIVATE WINDOW command on a window that


you have hidden; the window will return, but the window will return as if
it were brand new. That is, the window will have nothing in it.

Many combinations of opening, hiding, showing, and closing windows can


be used with the ACTIVATE WINDOW, DEACTIVATE WINDOW, HIDE
WINDOW, and SHOW WINDOW commands. Basically, you ACTIVATE a
window, HIDE the window to remove the window from the screen tem-
porarily, SHOW the window to return the window to the screen in the
same state, and DEACTIVATE the window to remove the window and its
contents.

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

ACTIVATE WINDOW one


? "Here is a Line of output to Window One!
WAIT

ACTIVATE WINDOW two


? "Here is output to Window Two while it is on the screen!
WAIT

HIDE WINDOW two


? "Here is output to Window Two while it is off the screen!

ACTIVATE WINDOW one


? "Just wrote to Window Two while it was hidden!
WAIT

ACTIVATE WINDOW two


WAIT

ACTIVATE WINDOW one


? "And finally,some output to Window One!
WAIT

DEACTIVATE WINDOW one


DEACTIVATE WINDOW two

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

Using a Color Pair


A color pair is two colors, separated by a / mark. The two colors represent
the foreground color and the background color of an object on-screen
(such as a menu, a window, or a data field). For example, in a field con-
taining text, the foreground color is the color of the text and the back-
ground color is color of the screen behind the text.

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>

For example, consider the following command:

SET COLOR OF TITLES TO W/B, B/W


This command sets the colors of window titles to white (W) text on a
blue (B) background when the TITLE is in standard mode (the window is
not selected) and blue text on a white background when in enhanced
mode (the window is selected).
334 Part III: Advanced FoxPro

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:

SET COLOR TO <standard_color_pair>,<enhanced_color_pair>,


<border_color_pair>,<background_color_ pair>

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.

Using Color Pair Lists and Color Schemes


Color schemes and color pair lists go together. At all times, FoxPro works
with a color scheme, which describes the color pairs of 10 objects on-
screen. Which 10 objects depends on what FoxPro is doing at the time.
For instance, if FoxPro is in its standard operation environment, the 10
objects and the colors assigned to them are as follows:

Pair # Object Color


i SAY field W +/RB
2 GET field W +/W
3 Window border GR +/W
4 An active title GR+/W
5 An idle title B/W
6 A selected item W+/R
y Hot keys B+/RB
8 A window’s shadow B
9 An enabled control B+/RB
10 A disabled control B/RB

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.

FoxPro has 10 different color schemes, each of which represents a differ-


ent part of FoxPro’s environment, and each of which contains 10 color
pairs to tell FoxPro how to color up to 10 objects in that environment.
For instance, there is a Color Scheme for User Windows that tells FoxPro
Chapter 10: Creating Applications with FoxPro 335

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.

Using the Color Picker To Set Colors


The easiest way to work with colors and color schemes is to open FoxPro
and choose Colors from the Window menu.

The matrix of foreground and background colors represents all possible


combinations of colors FoxPro provides. The upper left corner of the
Color Picker shows the objects on a FoxPro screen. In the upper right
corner is a scrollable list that contains the color schemes of FoxPro. When
you select a color scheme from the scrollable list, the objects in that color
scheme are shown in the center of the Color Picker. By selecting one of
the radio buttons from that list, you can click the foreground and back-
ground combination you would like that object to possess. For this, noth-
ing is better than experimentation.

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:

SET COLOR SET TO <color_set_ name>

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.

Deciding between Color and Monochrome


If you know your application will only run on one type of computer mon-
itor, you can use a color set that is appropriate to that monitor. However,
if your application may run on both color and monochrome monitors, you
need to provide a way for the application to determine what type of mon-
itor is being used, and load the appropriate color set. By doing so, you
will not have to maintain separate versions of your application; one for
color, one for monochrome.
336 Part III: Advanced FoxPro

A class of FoxPro functions is called System functions. One of these is


SYS(2006), which returns the type of graphics card and monitor in use.
For instance, if your application is running on a monochrome monitor, the
command

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

In this chapter you learned the basics of creating applications in FoxPro.


Like FoxPro itself, most applications will be controlled by menus. There-
fore, FoxPro provides sophisticated capabilities for you to include menus
in your applications. Also like FoxPro, windows will provide much func-
tionality, and so FoxPro provides extensive windowing capabilities. Colors
provide punch and pizzazz to your applications, and FoxPro allows you to
completely control colors.

A well-crafted FoxPro application is a pleasure to use. Even for beginning


FoxPro users, creating FoxPro applications can be a challenge and a
pleasure.
Programming
with FoxPro
= Chapter 8, FoxPro programming was introduced to overcome some
= shortcomings. This chapter is a more formal introduction to program-
ming. Even if you’re a complete nonprogrammer and you approach this
chapter with some dread, you will find that programming can be fun and
rewarding. Although I know some artistic people who will argue about it
all night (and have), a well-planned, well-crafted program can be a thing
of beauty.

In this chapter, you learn the basics of programming in FoxPro. FoxPro


includes a complete language, which you can use to instruct FoxPro to do
anything you have seen so far: create databases, open windows, accept
input, and write output to the screen or printer or files, along with a host
of capabilities not available from the screen. You can, for example,
develop input routines that test the information you enter and take differ-
ent actions based on that input—accepting it in some cases, opening
another input screen in others, rejecting it with appropriate error mes-
sages in yet others.

The most basic aspects of programming include storing information tem-


porarily in memory variables, having FoxPro take different actions
depending on the value of an expression, reading information from the
screen, writing information to the screen, and creating menus to allow the
user to choose what he wants to do. You learn how to do all these things
in this chapter. Finally, this chapter includes several basic programs that
accomplish tasks your programs will need. From these programs, you can
learn some good programming skills; you also can use them as is in your
programs or modify them to suit yourself.

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.

Creating a FoxPro Program


You have seen FoxPro put into the Command window a translation of
your mouse or keyboard actions into a command. A FoxPro program is
simply a series of those commands, which FoxPro executes one after the
other or according to commands that change the order of command exe-
cution. You can use these commands to do anything you can do with the
mouse or keyboard, and much more.

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

MODIFY COMMAND file_name

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

command to the CONFIG.FPX file (see Chapter 8).


Chapter 11: Programming with FoxPro 439

Using FoxPro Commands in Programs


You may have already started using FoxPro commands in the Command
window. In a FoxPro program, these commands are used exactly as you
would enter them in the Command window. The following is a FoxPro
program made up of nothing but FoxPro commands:

SET TALK OFF


SET ECHO OFF
SET CONFIRM ON
SET SAFETY OFF

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.

Comments should explain parts of the program that may otherwise be


unclear. Following is a code fragment that is well-commented:

* Loop through input routine until user presses Esc to quit


DO WHILE .NOT. done

input program lines

READ
340 Part II]: Advanced FoxPro

* readkey() will return 12 if user presses Esc


IF READKEY() = 12
DONE = .|T. && set loop test to indicate Esc
ENDIF
ENDDO

* user has terminated; close files and return


USE

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.

Using Memory Variables


A fundamental aspect of all computer languages is their capability to store
a piece of data with a name tag and later refer to that data and use it
simply by using the name tag. In FoxPro, memory variables give you this
capability. Memory variables are a way to store data and refer to it by
name.

Assigning Values to Memory Variables


You assign a value to a memory variable with the = assignment; then you
can use that value simply by referring to the name you have given it. For
example, the code

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

assigns 100 to CURR_REC and makes CURR_REC a numeric type variable.


If, later in the program, FoxPro encounters the line

CURR_REC = "This is the current record”


it redefines CURR_REC as a character variable.

You can assign to a memory variable the value from any valid FoxPro
expression. For example, the expression

BIG_NUM = ORDER-—>AMOUNT >= 100000

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.

Once a memory variable has been defined by an assignment statement,


you can substitute it anywhere you could put the actual value—in expres-
sions, for example:

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.

Combining Memory Variables


Because memory variables act according to their types, you can build
expressions that use two or more types as if they were simply values:

STRING1 = "Here is string one ”


STRING2 = "and here is string two”
STRING3Z = STRING1 + STRING2
? STRING3

Here is string one and here is string two


342 Part II]: Advanced FoxPro

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

System File Edit Database Record Program Window


188
Here is string one

Fig. 11.1.
Actions on the
wrong types of
memory
variables. clear
numl = 108
stringl = “Here is string one”
stringZ = stringl + numi

Operator/operand type mismatch.

When you need to combine a character memory variable and a numeric


memory variable, change the numeric variable to a character with the
STR() function:

STRING3 = STRING1 + STR(num1)

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.

Memory variables are an essential part of FoxPro programming, just as


they are an essential part of any computer language.
Chapter 11: Programming with FoxPro
343
Controlling the Flow of Execution
The real power of computer programs is their capability to execute differ-
ently, depending on conditions they recognize. Computer programs can
decide how to run based on the value of a piece of data. In pseudo-English
here is how a computer program might make such a decision:

IF ORDER—>AMOUNT is greater than 10,000


process statements that apply to big orders
ELSE
process statements that apply to smal) orders
ENDIF

This fragment of a program would execute different statements depending


on the value in the AMOUNT field of the current record of the ORDER
database. Statements that dictate how the program will execute are called
flow-of-control statements or constructs; they change the flow of the pro-
gram based on some value or expression. FoxPro has several flow-of-
control] statements, all of which you will use.

Using Logical Expressions


Each flow of control construct has a logical expression; how the construct
acts depends on whether that logical expression evaluates to true or false.
You discover how the flow of control statements use the logical expres-
sion in the following sections.

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

expression_I condition expression_2

The conditions can be any of the following:


4 = Equal. If expression_l and expression_2 evaluate to the same
value, the result of the logical expression is true; otherwise it is
false.
4 > Greater than. If expression_/ is greater than expression_2, the
logical expression is true, otherwise it is false.

J < Less than. The opposite of >. If expression_/ is less than


expression_2, the logical expression is true; otherwise it is false.
344 Part II]: Advanced FoxPro

(J >= Greater than or equal to. If expression_1 is the same as


expression_2 or greater than it, the logical expression is true. If
expression_1 is less than expression_ 2, the logical expression is
false.
I <= Less than or equal to. The opposite of greater than or
equal to.

I) <> Not equal. If expression_1 is not equal to expression_2, the


logical expression evaluates to true; if they are equal, the logical
expression evaluates to false.

You can combine one or more logical expressions using AND and OR.
The format for this is

logical_expression_1 .AND. logical_expression_2

logical_expression_I .OR. logical_expression_2

FoxPro evaluates Jlogical_expression_I and Jlogical_expression_2 sep-


arately. In the case of the AND logical test, only if /ogical_expression_1
and logical_expression_2 are both true will FoxPro evaluate the whole
expression to be true.

In the case of the OR construction, if either /ogical_expression_1 or


logical_expression_2 are true, FoxPro will return a true for the whole
expression. Only if both are false will FoxPro make the whole expression
false.

This is less confusing than it sounds. With a bit of practice, you will
understand these logical expressions and compound logical expressions.

There also are a number of standard, built-in FoxPro expressions that


return a logical value, such as EOF(), FOUND(), and UPDATE(). These
also can be used in flow of control constructs.

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

Optionally you can add an ELSE set of statements:

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.

Following is a fragment of code using an IF..ELSE..ENDIF construct:

IF EOF() && if at end of file


CLOSE DATABASES
ELSE
SKIP
? "Record Number: ", RECNO()
ENDIF

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

DO WHILE logical_expression = TRUE


statements to execute
ENDDO
FoxPro evaluates logical_expression. If it is true, FoxPro executes all the
statements between the DO WHILE and the ENDDO. When it reaches the
ENDDO, FoxPro jumps back to the DO WHILE and evaluates the logical
expression again. As long as that expression remains true, FoxPro keeps
executing the block and jumping back to the DO WHILE. As soon as the
logical expression becomes false, FoxPro jumps to the first statement after
the ENDDO and continues on its merry way.
346 Part II: Advanced FoxPro

Following is a fragment of a program using the DO WHILE..ENDDO


construct:
COUNT = 0
TOT_AMT = 0
DO WHILE COUNT < 1000
COUNT = COUNT + 1
TOT_AMT = TOT_AM + AMOUNT
SKIP
ENDDO

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.

A word of caution: somewhere in the loop you must include a statement


that causes the logical expression to change. In this example, it is the
statement

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.

DO WHILE..ENDDO commands can be for a set number of iterations, as in


the example, or for a variable number. The code fragment also could be
written as follows:

TOT_AMT = 0
DO WHILE TOT_AMT < 10000
TOT_AMT = TOT_AMT + AMOUNT
SKIP
ENDDO
TOVIAME =" 7TOToAMT
Chapter 11: Programming with FoxPro 347

In this case, the number of loops is not predefined. FoxPro continues to


loop through the database, adding the value of the AMOUNT field to the
memory variable TOT_AMT, until TOT_AMT exceeds 10,000. At that
point, the logical expression evaluates to false and FoxPro jumps to the ?
statement following the ENDDO.

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:

FOR MEM_VAR = 1 TO 100


statements to execute
ENDFOR

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.

If you want the memory variable to be incremented by something other


than the default 1, use the STEP clause:

FOR MEM_VAR = 1 TO 100 STEP 2


statements to be executed
ENDFOR

In this example, FoxPro increments MEM_VAR by two at the end of each


loop and then tests to see whether it has exceeded the maximum.

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.

SCAN FOR ORDER—>AMOUNT > 1000


statements to be executed
ENDSCAN

This SCAN..ENDSCAN example is equivalent to the following code:

DO WHILE .NOT. EOF()


IF ORDER—>AMOUNT < 1000
LOOP
ENDIF
statements to execute IF ORDER—>AMOUNT > 1000
SKIP
ENDDO

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.

The format of the DO CASE..ENDCASE is

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

When FoxPro encounters a DO CASE statement, it moves to the first CASE


statement and evaluates the logical expression. If that logical expression is
true, FoxPro executes the statements between that CASE statement and
the next CASE statement. When those statements have completed, FoxPro
jumps to the statement after the ENDCASE and continues.

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:

get a choice from a menu


DO CASE
CASE CHOICE = “A”
SET PROCEDURE TO PROC_1
DO PROG_1
CASE CHOICE — B™
SET PROCEDURE TO PROC_2
DO PROG_2
CASE CHOICE = "C’”
SET PROCEDURE TO PROC_3
DO PROG_3
OTHERWISE
? "That is not a valid menu choice.”
ENDCASE

This fragment sets procedure files and executes a program based on


whether the user entered A, B, or C in response to a menu. If the response
was something other than A, B, or C, an error message is issued.

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

No other computer language I know allows this; the CASE statements


must be on the same variable. Although FoxPro does allow such logical
expression mixing, I recommend avoiding this programming practice. It
makes for confusing programs, and confusion is the last thing you need
when you’re programming.

Using Screen Input and Output


Sooner or later, you must get some information from the user or write
something to the screen. FoxPro provides several ways to read data from
the user and write information to the screen from a program.

Using INPUT and WAIT


The simplest way of getting information from the user is with the INPUT
and WAIT statements. These statements stop program execution and wait
for the user to enter something from the keyboard.

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:

INPUT "Enter your last name: "TO LAST.NAME


In this example, the user’s input is assigned to the variable LAST_NAME. If
you use WAIT, you can optionally assign the user’s response to a memory
variable, but it is not necessary. The following expression,

WAIT "Error encountered”

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.

Using the ? and ?? Statements


You use the ? and ?? statements to place information on the screen in Fox-
Pro. You place one or more expressions after the ? or ?? statements, and
FoxPro writes those expressions out to the screen. If you use the ? state-
ment, FoxPro issues a carriage return/linefeed combination so the list
starts on the next line; using the ?? statement suppresses the movement to
the next line, so the list is printed on the current line, starting at the cur-
sor position. For example, the expression

? ‘This is line 1’
?? ‘This is line 2’

results in

This is line 1This is line 2

In this example, the ? statement causes the line 1 string to be printed on a


new line; the ?? statement simply prints the line 2 character string on the
same line, starting where the first string ended.

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

Amount: 100.00 plus or minus a few bucks.

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:

@ row_num, col_num SAY expr [options]


@ row_num, col_num GET data [options]

The row_num specifies the row number on-screen, from 0 to 24 where


you want the SAY or GET statement to appear; the col_num represents
the column, from 0 to 79, at which you want the SAY or GET to start. In
the SAY command, the expr represents a FoxPro expression. That expres-
sion may be any memory variable or database field or any valid FoxPro
expression. In the GET command, the data represents a memory variable
or database field. The /options] modify the expression or data.

Using SAY To Put Information On-Screen


The SAY statement in a program tells FoxPro to place the SAY expression
on-screen at the location you specify. The following is an example of sev-
eral SAY statements in a program:

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

When FoxPro encounters these lines in a program, it first clears the


screen, then, at row 2 and column 10, places the string

First Name: + FNAME

which concatenates the memory variable to the end of a literal string,


First Name:. The result of this code fragment is seen in figure 11.2.

System File Edit Database Record Program Window


- CHAP11. PRG
Last Name :Pickett fname = “John” Fig 11.2
First Name ‘John lname = “Pickett” E
@ @, O CLEAR &&clear the screen SAY statements
Z, 18 SAY “Last Name :" + Iname with character
3, 18 SAY "First Name :" + fname n
strings
concatenated for
output.

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.

Using GET and READ To Get Information


When you issue an (@GET statement in a program, FoxPro sets a field at
the row number and column number you have specified. You can use a
PICTURE clause to specify the field’s length; otherwise FoxPro will set the
length to be the length of the database field, if your GET is for a database
field, or the current length of the memory variable, if the field is for a
memory variable.
354 Part III: Advanced FoxPro

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

Combining the SAY and GET Commands


Often you will want your GET field to have a literal string before it; in
FoxView these are called /abels. To format your data-entry screen in this
manner, combine the SAY and GET statements into one statement as
follows:

@ row_num, col_num SAY expr GET data

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:

@ 0, 0 CLEAR && clear the screen


@ 1, 10 SAY "Last Name: ” GET LNAME
@ 2, 10 SAY "First Name:” GET FNAME
READ

The results in the data-entry screen are shown in figure 11.4.

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

Using FUNCTION Clauses To Format a Data Field


With FUNCTION and PICTURE clauses, you can improve your screens
and the accuracy of the data on them.

FUNCTION clauses contain codes that format an entire field of data. A


FUNCTION clause is a string of characters, so it must begin and end with
double-quotation marks. The first character in a FUNCTION code string
must be an @. Some examples of FUNCTION clauses are as follows:
FUNCTION "'a!"* This function forces all characters in the field to be
uppercase.

FUNCTION "'@A"* The function displays and accepts only alphabetic


characters.

Following is a list of valid FUNCTION codes:


A Allows alphabetic characters only.

B Left-justifies numeric output in an output field.

C Puts a CR (credit) after a positive number in a numeric field.

I Centers output text.

J Right-justifies output text in the field.

L Displays leading zeros. This causes a numeric field to be


completely full. For instance, in a numeric field with length of 8,
the number 5 will be displayed as 00000005.

M Allows you to specify a list of items that will appear in a pull-


down window. You could, for example, specify:

M Foxbase, Foxbase+ , 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.

S$<n> Limits the field to n characters wide, but allows scrolling if


the input variable is wider.

T Trims the leading and trailing edge blanks from the data in the
field.
Chapter 11: Programming with FoxPro 357

X Places a DB (debit) symbol after a negative number.


Z The field will be blank if its value is zero; otherwise FoxPro
displays a 0. Used only with numeric fields.

( Enclose negative numbers in parentheses.

! Accepts any number, but converts lowercase alphabetic


characters to uppercase.
*“ Displays numeric data in scientific notation.

$ Displays numeric data in currency format.

Using PICTURE Clauses To Format a Data Field


Unlike FUNCTION codes, which format all the characters of a data-entry
or display field, PICTURE clauses format each character of that field indi-
vidually; they are pictures of the way you want the field formatted. For
instance, if you want a numeric field to be formatted with a leading dollar
sign, with commas, and to have four digits before the decimal point and
two after, you would use the following command:

@ 0, 10 SAY DOL_AMT PICTURE "$9,999.99"


The valid PICTURE formatting codes are as follows:

A Allows only an alphabetic character to be entered.


L Allows only logical characters, which are T, t, F f, Y, y, N, n.

N Allows only a letter or a digit.

X Allows any character.

Y Allows only logical Y, y, N, or n to be entered. Lowercase is


converted to uppercase.

9 Allows only a digit to be entered if the field is character. If the


field is numeric, allows digits and the plus (+) or minus (—)
signs.

# Allows digits, blanks, and signs.


' Converts a lowercase character to uppercase.

$ Displays the currency symbol (usually the dollar sign, $).

* Displays asterisks in front of a numeric value; useful for check


protection.
eee
ee

358 Part III: Advanced FoxPro

. The period specifies the decimal position.

, A comma is used to separate digits to the left of the decimal


point.

Using Other GET Options


Many other useful options are available to work with SAY and GET pro-
gramming. These include the following:

RANGE low_limit, high_limits Allows you to specify the range of a


numeric GET statement. FoxPro will beep and display an error
message if the user tries to enter a number outside this range.

VALID <exprLogical> Allows you to test the input data, using a


FoxPro expression or a user-defined function. In either case, if the
result is FALSE, FoxPro will reject the input with an error message.

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.

DEFAULT <expr> Places the expression in the field as a default


value.

MESSAGE <exprC> Defines a character string to be a message which


will be displayed on the last line of the screen during data entry.
This is a good way to have a mini-help system for your data entry
screens.

Creating Structured Programs


Any programmer worth his salt knows about structured programming.
FoxPro provides excellent programming capabilities to create your pro-
grams in a structured, maintainable way. Structure programming simply
refers to breaking your programs down into manageable hunks of code,
each of which does one thing and only one thing. Because FoxPro enables
you to call one program from another, you can create well-structured pro-
grams easily.

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:

issue error message to screen


wait for response to error message

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, issue error message to screen; wait for response
to error message

put the GET statements back on-screen


READ the GET statements
process the information again

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.

To send data to a called subprogram (called passing a parameter), the sub-


program has to know what data is going to be sent to it. The first line of a
subprogram that will receive data should be a PARAMETER statement,
which lists what information the subprogram can expect. In the last exam-
ple, you saw a subprogram called ERROR_MSG, which might print an
error message on-screen and wait for the user to press the Enter key to go
on. Such a routine could be used for many error messages if it could be
set up to receive the error message from the calling program. Here’s how
to do that:

* ERROR_MSG procedure
PARAMETER E_MSG

@ 23, 1 SAY E_-MSG


@ 24, 1 SAY "Press any key to continue...”
SET CONSOLE OFF
WAIT
SET CONSOLE ON
RETURN

Now, when you execute ERROR_MSG, you must pass the error message
string as follows:

DO ERROR_MSG WITH "Invalid Last Name Entered”

or

DO ERROR_MSG WITH "Date must be later than 01/01/80”

When the ERROR_MSG routine is called with the DO command, FoxPro


passes the character string after the WITH option to the subprogram.
ERROR_MSG knows it will get a string to use as the message.

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

Using Procedure Files


One disadvantage of using small, segmented programs is that it slows
down FoxPro. Each time FoxPro encounters a DO statement, it must load
the program into memory and execute it. In a large system, in which Fox-
Pro must search a long directory and then load what may be some rather
large programs, this can add up to long pauses in execution. If you use
procedure files, you can alleviate this delay.

A procedure file is simply a file that contains many FoxPro programs.


Using the SET PROCEDURE TO procedure_file-name command, you tell
FoxPro that it should first look in the procedure file for any programs
called with the DO statement. When FoxPro encounters the SET PRO-
CEDURE TO statement, it loads the procedure file into memory if there is
enough room. (If not, FoxPro does some fancy footwork that will dramati-
cally speed up calls to programs in the procedure file.)

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

waciaia lines of the addline procedure

PROCEDURE edit_line

a lines of the editJine procedure

PROCEDURE error_Ms

program lines of the errormsg procedure


362 Part II]: Advanced FoxPro

A helpful trick to creating program files that may be used in a procedure


file is to include the PROCEDURE proc_name as the first line of every
program file you create, with an asterisk (*) as the first character. That
makes the line a comment, ignored by FoxPro if the program file is exe-
cuted with a DO command. Then, when and if you include this program
in a procedure file, you only have to delete the asterisks to make the pro-
gram a valid procedure.

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.

System Fille Edit Database Record Program Window

UTILS. PRG ERROR_MS.PRG


Fig. 11.5. UTILS. PRG * PROCEDURE error_msg
* a procedure file for utility x Remove the "x" from the ab
Two program programs * to place in a procedure fi
files open at the | J x-------------------------------
same time in PARAMETER msg_str
*: Activates a window, place
different
windows. : do a little housekeeping
: Can’t have a string longe
: fit in the box. If the st
: still works

IF LEN(msg_str) > 75
msg_str = LEFT(msg_str,7
ENDIF

x: activate the window for t


ACTIVATE WINDOW err_win

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

Using Basic Utility Programs


Learning a new programming language, particularly if it’s your first, can be
a terribly frustrating experience. To ease this pain, here are some fairly
simple, but quite useful, FoxPro programs that you can peruse and use.
Although I don’t claim to be the world’s greatest FoxPro programmer,
these programs do work and may form the basis for your own exploits in
FoxPro programming.

Reading To Get a Valid Character


Often, you will want to get a character from the screen that must meet
some criterion. You may, for example, ask the user whether he wants to
file, edit, save, or quit from a data-entry screen, and want your program to
accept a letter from the user which must be either F for file, E for edit, S
for save, or Q for quit; any other letter must cause a message to appear
explaining the situation. Here is a procedure that will receive a message
string and a string against which to check the input. The procedure will
return the valid character.

In pseudo-English, the procedure can be written as follows:

GET message, CHECK_STRING from calling program


open the window
DO WHILE the input character is not in the CHECK_STRING
write the message on-screen
GET the entered character
if the entered character is not in the CHECK_STRING
write an error message
ENDIF
ENDDO
close the window

And the program itself is shown in figure 11.6.


Before this program can be called, you must issue a DEFINE WINDOW
command. The DEFINE WINDOW commands tells FoxPro to set up in its
memory a window, with a name, which can then be put on-screen with
the ACTIVATE WINDOW command and taken off the screen with the
DEACTIVATE WINDOW command. The format of the DEFINE WINDOW
command for this routine is

DEFINE WINDOW MSG_WIN1 FROM 21,0 TO 24,79


364 Part IJ: Advanced FoxPro

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

*: set up the error message to be used if the user enters an


*: invalid character

err_msg = "You must enter one of these characters: " + chk_str

*: activate the window for the message


ACTIVATE WINDOW msg_winl

valid_char = .F.
DO WHILE .NOT. valid_char && loop until users enters a
&& character that’s in the chk_str

*: Center the string on the first line of the box


@ 0, (80 - (LEN(msg_str)+ 3))/2 SAY msg_str GET ret_char PICTURE ’!
READ

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

DEACTIVATE WINDOW msg_winl

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)

tells FoxPro to change the character entered (RET-CHAR) to uppercase,


change all the characters in the check string to uppercase, and see
whether the uppercase RET_CHAR exists in the uppercase CHK_STR. In
this way, you can ensure that the user doesn’t have to worry about
whether he is entering an upper- or lowercase character; either will work.
The $ symbol is FoxPro’s shorthand for “is in”; you could read this com-
mand as if the uppercase RET_CHAR is in the uppercase CHK_STR.
The expression,

("80 — LEN(MSG_STR))/2 SAY”


Chapter 11: Programming with FoxPro 365

centers the MSG_STR on a line. The program adds two to the length of the
MSG_STR,

("(80 — (LEN(MSG_STR) + 2) /2 SAY"

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.

Using Memory Variables for Database Input


Most APPEND operations add a record as soon as the user moves out of
the last field of the data-entry screen. Often, though, you will want to give
the user the opportunity to edit the entered data before adding it to the
database. This gives the user a chance to make sure that the data is cor-
rect, and gives you some assurance that data going into the database is
right. It is always easier to correct data before it is added to a database file
than afterward.

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.

Programming is not a mystic art. FoxPro programming is quite simple and,


like all else about FoxPro, amazingly powerful. Experiment with it and
have fun.
366 Part II]: Advanced FoxPro

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

*: loop while the user wants to enter records


entering = .T.
DO WHILE enteri ng
mCustName SPACE (25)
mAddri SPACE (25)
SPACE (25)
SPACE (25)
SPACE (2)
SPACE (9)

SAY "Customer Name


SAY Address
SAY "

SAY UJ City
SAY J State
SAY " Zip

*; loop through the read/validate routine until user says it’s ok


*: to save in the database
editing =. Ae
DO WHILE ed iting
427 GET mCustName
2a) GET mAddri
3B, PY GET mAddr2
27 GET mCity
27 GET mState FUNCTION "@!"
244) GET mZip PICTURE "@R 99999-9999"

IF READ KEY() = esc_pressed


edi ting = .F.
ent ering = .F.
ELSE
cho ice c=annt
DO get_char WITH "Do you want to Edit, File or Quit? (E/F/Q)
DO CASE
CASE choice Loh && user wants to edit the data
editing SUie,
entering = .T.
CASE choice = "F" && user wants to file the data
APPEND BLANK
REPLACE cust_name WITH mCustName
REPLACE WITH mAddr1l
REPLACE WITH mAddr2
REPLACE WITH mCity
REPLACE WITH mState
REPLACE WITH mZip
editing
entering =
CASE choice = wants to quit without filing
editing =
entering
ENDCASE
ENDIF
ENDDO && while editing
ENDDO & while entering

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.

Using expanded and extended memory is a complicated topic. If you


know how to set up your computer to do this. I refer you to the FoxPro
manual for specific instructions. If “expanded memory,” “extended mem-
ory,” and “software drivers” are foreign terms to you, I suggest you enlist
the aid of an expert. 367
368 Using FoxPro

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:

MKDIR C:\FOXPRO CD C:\FOXPRO

If you want to install FoxPro on a drive other than C:, replace the
C: in this command with the appropriate drive letter designation.

4. Now, place Disk 1 in drive A: and type

INSTALL C:

If you’re installing FoxPro on a drive other than C:, replace the C:


with the correct drive letter. FoxPro displays the screen
containing installation information. Press any key to continue.

5. Enter your serial number exactly as it appears on the envelope;


uppercase and lowercase characters must be entered exactly as
shown. When you’re finished, you will see the screen shown in
figure A.1, which asks for the activation key.

Fox Software Product Installation

Fig. A.1.
Entering the
Enter your FoxPro Serial Number: FMD@31122 Activation key.

Enter your Activation Key: oevzbti

Cc) 1989 Fox Software


470 Using FoxPro

6. Enter the activation key exactly as it appears on the envelope.


You must enter upper- and lowercase letters exactly as they
appear on the envelope. If you want to “test drive” FoxPro, enter
the Demonstration Activation Key, otherwise enter the live 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.

Please select your monitor type:

Generic Color (CGA, EGA, UGA>


Fig. A.2. Generic Monochrome eS
Selecting a Compaq Plasma - Color Mode
5 Compaq Plasma- Monochrome Mode
monitor type for Toshiba 3280
FoxPro, Toshiba 5208 (Color)
Toshiba 5288 CMonochrome-like>

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

7. In the window labeled CONTENTS, move the highlight up and down


using the up- and down-arrow keys, and select what you want to
install by pressing the space bar. When you have selected the
programs you want to install, press Enter. Following is a summary
of what is included in the Optional Products menu:

I Help File. This file is useful while you’re learning FoxPro.

4 Small Help File. This is a Help file with abbreviated command


explanations. If you install the full-sized Help file, there’s no
need to install this one too. As you become more expert
with FoxPro, you may want to replace the full Help file with
this one to conserve disk space.
Appendix A: Installing FoxPro Aral

FoxPro Optional Products Installation Procedure


Press Spacebar to select current item Press ft! arrow keys to move cursor
Press F2 to select all items Press Enter to install selected items
Press F3 to deselect all items Press Esc to abort installation

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 Tutorial Files. A series of program and database files that


form the FoxPro tutorial. If you’re new to FoxPro, this is an
excellent introduction.

I Goodies. Optional programs that you may use when you


become quite familiar with FoxPro. You don’t need these to
Start.

“I Demo Application. A full application showing off FoxPro. It’s


interesting to play around with, but you will find yourself
erasing it after several sessions.

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

J FoxDoc. FoxDoc is a program that documents FoxPro


application programs. If you’re an experienced FoxBase+ or
dBASE IV programmer and expect to be writing FoxPro code
right away, install this. Otherwise, leave it off until you’re
ready to do some FoxPro programming.

Q) FoxView. FoxView is the FoxPro screen editing program.


With it you create screens for FoxPro to use. This option is a
necessity; install it.
472 Using FoxPro

J FoxGen. FoxView uses FoxGen to transform your screen


designs to FoxPro code, so you should install this option.

1 FoxCode. FoxCode goes with FoxGen.

‘1 Compiled Templates. These are used by FoxGen to .translate


screen design to files that FoxPro can use. You should install
these templates if you go beyond the bare-bones use of
FoxPro.

1 Template Source. These programs are what created the


Compiled Templates. In Using FoxPro, you will make some
changes to these source files, so install them also.

8. Once you have specified what optional products you want


installed, press Enter and follow FoxPro’s instructions for disk
changes. When FoxPro is done, you are returned to the C:
prompt, now in the directory you defined for FoxPro.

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

MKDIR C: \FOXPRO \dir_name


Appendix A: Installing FoxPro 4735

where dirname is the name of the directory you want to create. Then,
move to this directory by typing

CD \FOXPRO \dirname

again where dirname is the directory you just created

Next, set 2 path so that DOS knows where to find FoxPro by typing

PATH = C: \FOXPRO

and enter the command

FOXPRO

You should see the FoxPro opening screen (see fig A‘5). Now turn to
Ouick Start 1 and have fun!

7a San ees

Susten. File Edit Database Record Progran Uindou

eect meoereree oad Perera Fig. A.5.


2 ca
os oa ae “ai The FoxPro
es ee = opening screen
= Ped ee ee = = oo as
eames = = fea ee CRE == ee E]
fa at aS = = ae ra ea a
fe i = oy fel fa ea ie
fe = eat tien st Si a fea ot
wa oa = wa we = fod
ae ca — «se me
374 Using FoxPro
Index

&& comment character, 340


* comment character, 340
< Uess than) logical expression, 343 backspace key, 13
<= (less than or equal to) logical expression, bands
344 Detail, 126—130, 259-261
<> (not equal) logical expression, 344 Group Footer, 147
= (equal) logical expression, 343 Group Header, 147, 263-264
> (greater than) logical expression, 343 PgFoot, 126, 131-132, 135
>= (greater than or equal to) logical expression, PgHead,
126, 131-132, 134
344 Summary, 136-141
? command, 351 Title, 136-137
?? command, 351-352 BAR() function, 323
@GET command, 204, 223-225, 352-355 batch files, 237-238
@SAY command, 204, 228-229, 352-355 BOF() function, 109
BORDER _STRING option (DEFINE WINDOW
command), 329
A
Box (Report menu) option, 150-151
ACTIVATE MENU command, 292, 315-317 Browse menu
ACTIVATE WINDOW command, 331-332 Move Field option, 94
adding Resize Partitions option, 95
calculated fields to reports, 131 Unlink Partitions option, 95
comments to programs, 339-340 Browse window, 19-21, 92-98
database fields to reports, 128 customizing, 93-95
lines to reports, 130 deleting data, 19-20
titles to reports, 28-29 deleting records, 20—21
~ALIGNMENT system print variable, 278 editing data, 19-20
ALLTRIM() function, 109 options, 96-98
Alt-W (Window menu) key, 17 partitioning, 95
AND logical expression, 344 scrolling, 15
applications undoing delete, 20
activating menus, 317
creating with FoxView, 284-289
deactivating menus, 318
defining menu pads, 290-291, 316-317 calculated fields, 131
defining pop-up menus, 294—306 CDOW() function, 110
defining windows, 328-331 character fields, 60
designing, 312-332 check boxes, 48
help systems, 325-328 choosing commands from menus, 46
menu structure, 289-306, 312-325 CHR() function, 330
procedures, 301-306 clauses
prototypes, 314 For, 110-113,
142
windows screen commands, 331-332 FUNCTION, 356-357
arguments, 108 RANGE, 216-217
Average (Database menu) option, 102

375
376 Using FoxPro

Scope, 142-143 SET CLOCK, 240


VALID, 216-220 SET COLOR, 333-335
While, 110-113, 142 SET COLOR SET TO, 335
CLOSE/NOCLOSE option (DEFINE WINDOW SET CONFIRM, 240
command), 330 SET HEADING, 240
COLOR option (DEFINE WINDOW command), SET HELP TO, 326-327
330 SET MOUSE, 240
COLOR SCHEME option (DEFINE WINDOW SET PROCEDURE TO, 361
command), 330 SET SAFETY, 240
colors, 330-331 SET TOP TO, 327
color pairs, 333-335 SHOW WINDOW, 331-332
setting screen attributes, 332-336 WAIT, 227-229, 350-351
Colors (Window menu) option, 335 comments
column headings, 134 && character, 340
combining memory variables, 341-342 * character, 340
command line, 40 adding to programs, 339-340
command string, 248 compiling template files, 214-215
Command window, 40, 247—248 COMFIG.FP file, 238-241
editing commands, 249 assigning strings to function keys, 240-241
expressions, 106 creating, 239-240
reusing commands, 249 customizing, 238-241
running reports, 274 replacing default text editor, 241
commands SET AUTOSAVE command, 240
?, 351-352 SET BELL command, 240
??, 351-352 SET CLOCK command, 240
@GET, 204, 223-225, 352-355 SET CONFIRM command, 240
@SAY, 204, 228-229, 352-355 SET HEADING command, 240
ACTIVATE MENU, 292, 315-317 SET MOUSE command, 240
ACTIVATE WINDOW, 331-332 SET SAFETY command, 240
DEACTIVATE MENU, 315, 318 context-sensitive help systems, 326-328
DEACTIVATE WINDOW, 331-332 Continue (Record menu) option, 98
DEFINE BAR, 322 controlling index, 75-76
DEFINE MENU, 291, 315 controlling/controlled databases, 185-187,
DEFINE PAD, 291, 316 192-194
DEFINE POPUP, 294-295, 318-321 Count (Database menu) option, 102-103
DEFINE WINDOW, 329-330 CTOD() function, 110
DO, 43 Ctrl-A (Select All) key, 244
editing, 249 Ctrl-C (Copy fields) key, 244
ENDPRINTJOB, 275-279 Ctrl-F (Find) key, 244
HIDE WINDOW, 331-332 Ctrl-F1 (Cycle Windows) key, 244
INPUT, 350-351 Ctrl-F2 (Command Window) key, 244
JOIN, 265-268 Ctrl-F7 (Move Window) key, 17, 244
MODIFY COMMAND, 338 Ctrl-F8 (Size Window) key, 18, 244
ON SELECTION PAD, 291, 316-317 Ctrl-F10 (Zoom) key, 244
ON SELECTION POPUP, 296-297, 323 Ctrl-G (Find again) key, 244
PRINTJOB, 275-279 Ctrl-M (Move) key, 47
PROCEDURE, 322-324 Ctrl-S (Size) key, 48
READ, 354 Ctrl-T (Delete record) key, 244
reusing, 249 Ctrl-T (mark record) key, 98-99
SET ALTERNATE, 278-279 Ctrl-V (Paste) key, 244
SET AUTOSAVE, 239-240 Ctrl-X (Cut fields) key, 244
SET BELL, 240 Ctrl-Z (Zoom) key, 48
Index Sr

cursor-movement keys, 13-16 DIOCO 110


dialogs, 50 MONTH(), 109
text editor, 203-204 date memory variables, 115
custom data-entry screens, 81-9} DEACTIVATE MENU command, 315, 318
custom reports, 275-279 DEACTIVATE WINDOW command, 331-332
cutting and pasting fields, 163-164 deactivating applications menus, 318
debugging with Trace window, 307-310
default data-entry window, 80-81
D DEFINE BAR command, 322
DEFINE MENU command, 291, 315
data
DEFINE PAD command, 291, 316
deleting, 19-20, 98-100
DEFINE POPUP command, 294-295, 318-321
deleting from Record menu, 98-99
DEFINE WINDOW command, 329-330
editing, 19-20, 41
BORDER _STRING option, 329
entering, 14, 41, 79-81, 92
CLOSE/NOCLOSE option, 330
marking, 98-100
COLOR option, 330
recalling, 99
COLOR SCHEME option, 330
undeleting, 20
DOUBLE option, 329
data dictionary, 56-58
FLOAT/NOFLOAT option, 330
data entities, 180-181
GROW/NOGROW option, 330
data-entry screens, 204-215
NONE option, 329
Data Grouping (Report menu) option, 145
PANEL option, 329
data types, 59
SHADOW option, 330
character, 60
SYSTEM option, 329
date, 61
TITLE option, 329
float, 61
ZOOM/NOZOOM option, 330
logical, 61
defining
memo, 62
database structure, 68-71
numeric, 61
fields, 70-71
picture, 62
indexes, 71-74
Database menu, 101-103
menu pads, 290-291, 316-317
Average option, 102
pop-up menus, 294-306, 318-325
Count option, 102-103
views, 76
Pack option, 100
windows for applications, 328-331
Report option, 142-143, 273-274
Delete (Record menu) option, 98-99
Sum option, 102
deleting
databases
data, 19-20, 98-100
attaching indexes, 74—75
data from Record menu, 98—99
defining structure, 68-71
lines, 130
designing, 53-59
records, 20-21
flat files, 33-34
designing databases, 53-59
joining, 205-268
data dictionary, 56-58
loading files into FoxView, 204—206
output, 54-55
packing, 100
structure, 58-59
relational, 33-36, 179-187
designing reports, 126-141
See Also relational databases
relational databases, 256-259
sorting, 63, 116-118
Detail band, 126-130, 259-261
structure, 58-59
dialogs, 38, 48
date fields, 61
check boxes, 48
date functions, 109-110
cursor-movement keys, 50
CDOW(), 110
Expression Builder, 64-67, 105-108
CTODQ), 110
Fields, 73
DOW(), 109
a a a re Sen AE a Se ae

478 Using FoxPro

Open Index File, 73-74 formatting in reports, 133


pop-up controls, 49-50 group summary, 148-149
radio buttons, 49 HELP, 325
Report, 273-274 inserting, 69
Scope, 102-105 logical, 61
scrollable lists, 49 memo, 62, 152
Setup, 72 naming, 12-13
Structure, 69-71 numeric, 61
text boxes, 50 order, 69
text buttons, 48 picture, 62
directories, 232-238 repositioning with FoxView, 206—207
DO CASE..ENDCASE flow of control construct, stretching in reports, 270-271
348-350 styling in reports, 133
DO command, 43 summary, 135-141
DO WHILE..ENDDO flow of control construct, TOPICS, 325
226-229, 345-347 totaling, 137-141
DOS file structure, 232-238 width, 12-13
DOUBLE option (DEFINE WINDOW command), Fields (Report menu) option, 260
329 Fields dialog, 73
DOW() function, 109 File menu, 10—12
DTOC() function, 110 filters, 73, 93
Find (Record menu) option, 96-97
finding records, 96-98
E with Record menu, 221-222
flat database files, 33-34
editing data, 41
float fields, 61
Browse window, 19-20
FLOAT/NOFLOAT option (DEFINE WINDOW
editing text, 202-204
command), 330
ENDPRINTJOB command, 275-279
flow of control constructs, 343-350
entering data, 14, 41, 79-81, 92
DO CASE..ENDCASE, 348-350
custom data-entry screens, 81-91
DO WHILE..ENDDO, 226-229, 345-347
default data-entry window, 80-81
FOR..ENDFOR, 347
Entity-Relationship (E-R) diagrams, 184-187
IF..ELSE..ENDIF, 344—345
EOF() function, 109
SCAN..ENDSCAN, 348
Expression Builder dialog, 64-67, 105-108
FMT files (changing to PRG files), 222
expressions, 64-67, 106—108, 111-113
footers, 131-132
For clauses, 110-113, 142
F FOR..ENDFOR flow of control
construct, 347
Fl (Help) key, 245 formatting data on-screen, 356-358
F4 (Directory) key, 245 formatting fields in reports, 133
F5 (List Structure) key, 245 FoxBase + , 36, 40—43
F6 (Display Status) key, 245 relational databases, 194-195
F9 (Append) key, 245 saving views, 196-197
Field (Report menu) option, 137-138 FoxBase + /Mac, 37
fields, 59 FoxPro, 41—43
character, 60 customizing, 238-241
creating, 12-13 environment, 37—40
cutting and pasting, 163-164 hardware requirements, 367
data, 61 installing, 368-373
defining, 70-71 FoxView
float, 61 adding boxes to screens, 86-87
Index 479

adding text to screens, 85 MONTH(), 109


changing data-entry labels, 84-85 POPUP(), 323
compiling template files, 214—215 PROMPT(), 323
creating applications, 284-289, REPLACE ALL WITH UPPER, 109
creating data-entry screens, 81-91, 204-215 RIGHT(), 109
default screen, 82-84 SQRT(), 109
Function codes, 88-89 STR(), 342
generating Format screens, 90-91 string, 109
generating forms, 209-211 SUM(), 108-109
loading database files, 204—206 user-defined, 220-221
modifying template files, 211-214
moving objects, 85 G
objects, 84—85
picture clauses, 87-89 generating
Picture Template codes, 88-89 Format screens from FoxView, 90-91
repositioning fields, 206-207 forms in FoxView, 209-211
Screen view, 84 reports, 23-29, 41-42
starting, 82 graphics, 150-151
Table view, 84 Group Footer band, 147
template files, 209-215 Group Header band, 147
using screens in FoxPro, 90-91 relational databases, 263-264
FUNCTION clauses, 356-357 group summary fields, 148-149
codes, 356-357 grouping records, 144-149
function keys relational databases, 262—264
assigning strings, 240-241 GROW/NOGROW option (DEFINE WINDOW
Ctrl-F1 (Cycle Windows), 244 command), 330
Ctrl-F2 (Command Window), 244
Ctrl-F7 (Move Window), 17, 244
Ctrl-F8 (Size Window), 18, 244 H
Ctrl-F10 (Zoom), 244
hardware requirements, 367
Fl (Help), 245
headers, 131—132
F4 (Directory), 245
HELP field, 325
F5 (List Structure), 245
help systems
F6 (Display Status), 245
context-sensitive, 326-328
F9 (Append), 245
creating, 325-328
Shift-F10 (stop macro record), 246
creating database, 326-328
Reoclions
ALLTRIM(), 109
HELP field, 325
BAR(Q), 323 TOPICS field, 325
BOF(), 109 HIDE WINDOW command, 331-332

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

380 Using FoxPro

single-field, 64 _LMARGIN system pont vanable, 27S


INPUT command, 350-351 leading database Ales into PoxView, 204-206
input into programs, 350-351 Locate (Record mena) option, 97-98
INPUT command, 350-351 logical expressions
WAIT command, 350-351 < (less than) 343
Ins key, 14 <= (less than or equal t), 344
inserting fields, 69 <> (rot equal), 344
_—
installing FoxPro, 367-3
~ >
3 = (equal), 343
> (greater than), 343
>= (greater than or equal to), 344
J-K AND, 344
QR, 344
JOIN command, 265-268
logical fields, Ol
joining relational databases, 265-208
logical functions, 109
Keyboard, 39-40
BOFQ, 109
windows, +7—48
BOR), 109
Keys
logical memory variables, U5
AleW (Window menu), 17
loops, &e flow ef control constructs, 348
backspace, 13
combinations for macros, 246
Ctrl-A (Select AID), 244
Ctrl-C (Copy fields), 244
Ctrl-F (Find), 244 Macro (System menu) option, 245
Ctrl-Fl (Cycle Windows), 244 macros, 244-245
Ctrl-F2 (Command Window), 244 key combinations, 246
Ctrl-F7 (Move Window), 17, 244 running, 246
Ctrl-FS (Size Window), 1S, 244 saving, 245
Ctrl-F10 (Zoom), 244 Storing, 245
Ctrl-G (Find again), 244 marking data, 98-100
Ctrl-M (Move), 47 math functions, LOS—100
CtrLS (Size), 48 LENQ, 109°
Ctrl-T (Mark record) key, 98-99, 244 MAXQ), 109
Ctrl-V (Paste), 244 MINQ, 109
Ctrl-X (Cut fields), 244 SQRTQO, 109
Ctrl-Z (Zoom), 48 SUMQ, 109
cursor movement, 13-16, 50 MAX() function, 109
Fl (Help), 245 memo fields, 62, 152
F+ (Directory), 245 memory variables, 114-116, 34Q-342
F5 (List Structure), 245 @GET command, 223-225
F6 (Display Status), 245 character, 115
FO (Append), 245 combining, 341-342
Ins, 14 date, 115
Shift-FLO (stop macro record), 246 input into, 350-351
Shift-Tab (scroll left), 16 logical, 115
Tab (scroll right), 16 numeric, 115
text editor cursor movement, 203-204 STRQ function, 342
menu options
Average, 102
L Box, 150-151
Layout window, 25-29, 126-128 Colors, 335
LEN() function, 109
Continue, 9S
line and box drawing, 150-151 Count, 102-103
Data Grouping, 145
index 381
Dds, ¥6,99 is)
Fild, 137-138
Fits, ON SELECTION PAD cxomnmand, 291, 316-317
Find, 96-97 ON SELECTION POPUP comunand, 296-297, 424
line, G79 Open index File Gatley, 75-74
Micro, 245 OR cds exgrewun, 544
Mowe Fis, 94 output to “ren
Puch, 1009 1 cnmmnand, 951-592
PROMPT FIELD, 319 4 commas, FA—-SS2
PROMPT FILES, 520-321
PLOUMPT STRUCTURE. 320-321
nike bepent, 172 Pp
Rech,
hegnt, 142-143, L73-274 Yuk (Datos mem) option, 109
puking tottome, 21, 100
Revie Pass, FS
Pee numbers, 135
CA IT
tuma, 102 Page Preview win, 26-27, 129-19)
Vile/aesenary, 195-137 PANEL option (DEFINE WINDOW command), 329
iniek Pattuns, FS watimning rows widow, FS
Ie pats, 254
PALA, LOIS, BAZ-32S hang from FoxPro, 296-237
os, comms, Yo -POOPIES sytem pri vate, Z78
Keg, L9-I, 314-325 _PECODE sytem pris variable, 276
Paun bad, 126, 131-135
Datos, 1901-104, 142-143
CRxGT HE, BIEL, WB PHiicws bend, 126, 131-134
DEFINE MENT commucad, 315 PICTURE dauses, 356-358
Ahan, GB, LPI-L, BVG-BAT pine fits, 62
dem pop, 294-YH, 318-325 -VIENGTH waem pran vaiale, 278
Fhe, 10-12
popup coms, A
popup menus
dius, 318-325
prcechases, 322-524
POPUP.) function, 323
MIN ) faction, 109
VMAIEY COVUMASL maaan, FA
PRINTJOS command, 275-279
wma, vesanfae Bes ts ForVuew, 211-214 PROCEDURE command, 322-324
proceduse fhes, 1-362
WMONTH ) ftom, 109
practices, PN-W6
moms, 9 \
prxcciures for popup menus, 322-324
sx Sie, 16
wassrns, Lo-GT rvgun thes
opening, 338
Mowe Fd (Growsee menu) atom, 94
progamning 20)
contig memory vases, 441-342
N comets, 599-F0O
aston requrts, Z73—-279
wena, Gets, 12-13 écuggug, WIT310
NONE option (DEFINE CINDOW command ), 329 flow A commrA comsructs, 444-40
suunetia feds, G1 formating dita n-IEen, 456-358
suunetic sens VAIS, 115 FONCTION clauses, 356-357
muaxementiong Coumers, 346-347
eugnt, FOG
logged express, 345-344
WARL: A AE ED
Sow A contd comircucts, 343
OL NS a ee

FBZ Using FoxPro


Using FoxPro

memory variables, 340-342 joining, 265-268


opening program files, 338 reports, 171-176, 197, 255-272
output to screen, 351-355 testing, 197
PICTURE clauses, 356-358 testing relation, 169-170
procedure files, 361-362 work areas, 160-161, 189-191
procedures, 301-306 REPLACE ALL WITH UPPER function, 109
sample programs, 363-365 replacing default text editor, 241
structured programs, 358-362 Report (Database menu) option, 142-143,
subprograms, 359-362 273-274
Trace window, 251-252, 307-310 Report dialog
PROMPT FIELD option, 319 Console on/off option, 274
PROMPT FILES option, 320—321 For option, 273
PROMPT STRUCTURE option, 320-321 Heading option, 274
PROMPT() function, 323 No Eject option, 273
prototype applications, 314 options, 273
_PSPACING system print variable, 278 Plain option, 273
Scope option, 273
Summary, 273
Q-R To File option, 274
To Print option, 274
Quick Report (Report menu) option, 172 While option, 273
radio buttons, 49 Report menu
RANGE clauses, 216—217 Box option, 150-151
READ command, 354 Data Grouping option, 145
Recall (Record menu) option, 99 Field option, 137-138
recalling data marked for deletion, 99 Fields option, 260
Record menu, 96-97 Quick Report Option, 172
Continue option, 98 Title/Summary option, 136-137
Delete option, 98-99 Report Writer, 23-29
Find option, 96-97 reports
Locate option, 97-98 adding calculated fields, 131
Recall option, 99 adding database fields, 128
Seek option, 96-97 adding lines, 130
records, 59 bands, 126-128
deleting, 20-21 column headings, 134
finding, 96-98 creating, 127-130
finding with Record menu, 221—222 deleting lines, 130
grouping, 144-149 designing, 126-141
searching, 96—98 footers, 131-132
relational databases, 33-36, 179-181 formatting fields, 133
creating, 157-166, 188-194 generating, 23-29, 41-42
controlling/controlled databases, 185-187, graphics, 150-151
192-194 group summary fields, 148-149
cutting and pasting fields, 163-164 grouping records, 144-149
data entities, 180-181 headers, 131-132
data-entry screens, 204-215 line and box drawing, 150-151
defining relation, 166-170, 192-194 memo fields, 152
designing, 181-187 objects, 126
designing reports, 256-259 page numbers, 135
Entity-Relationship (E-R) diagrams, 184—187 programming custom, 275-279
FoxBase+ , 194-195 relational databases, 171-176, 197, 255-272
Group Header band, 263-264 designing, 256-259
indexes, 268-269
Index 38 4

grouping, 262-264 Shift-F10 (stop macro record) key, 246


placing fields in Detail band, 259-261 Shift-Tab (scroll left) key, 16
sorting on controlled database fields, SHOW WINDOW command, 331-332
264-265 single-field indexes, 64
running, 142-143 sizing windows, 17-18, 48
running from Command window, 274 sorting databases, 63, 116-118
saving, 30-32 sorting reports on controlled database fields,
setting system print variables, 277-279 264-265
stretching fields, 270-271 SQRT() function, 109
styling fields, 133 starting FoxView, 82
summary fields, 135-141 STR() function, 342
titles, 28-29, 132, 135-137 stretching fields in reports, 270-271
totaling fields, 137-141 string functions, 109
Resize Partitions (Browse menu) ALLTRIM(), 109
option, 95 REPLACE ALL WITH UPPER, 109
RIGHT() function, 109 RIGHT(), 109
~RMARGIN system print variable, 278 strings
assigning to function keys, 240-241
Structure dialog, 69-71
S structured programs, 358-362
styling fields in reports, 133
sample programs, 363-365
subdirectories, 232-238
SCAN..ENDSCAN flow of control
construct, 348
subprograms, 359-362
Sum (Database menu) option, 102
Scope clauses, 142-143
SUM() function, 108-109
Scope dialog, 102-105
screens
Summary band, 136-141
summary fields, 135-141
color pairs, 333-335
System menu Macro option, 245
creating data-entry, 81-91
SYSTEM option (DEFINE WINDOW command),
setting color attributes, 332-336
scrollable lists, 49 329
scrolling, 15
system print variables, 277—279
_~ALIGNMENT, 278
with mouse, 16
_INDENT, 278
searching records, 96-98
_LMARGIN, 278
Seek (Record menu) option, 96-97
-PCOPIES, 278
selecting menus, 44—46
=PECODER2/&
SET ALTERNATE command, 278-279
_~PLENGTH, 278
SET AUTOSAVE command, 239-240
_~PSPACING, 278
SET BELL command, 240
~RMARGIN, 278
SET CLOCK command, 240
SET COLOR command, 333-335
SET COLOR SET TO command, 335 T
SET CONFIRM command, 240
SET HEADING command, 240 Tab (scroll right) key, 16
SET HELP TO command, 326-327 template files in FoxView, 209-215
SET MOUSE command, 240 testing relational databases, 169-170, 197
SET PROCEDURE TO command, 361 text boxes, 50
SET SAFETY command, 240 text buttons, 48
SET TOP TO command, 327 text editors, 202-204
setting screen color attributes, 332-336 cursor-movement keys, 203-204
Setup dialog, 72 replacing default, 241
SHADOW option (DEFINE WINDOW command), thumb, 16
330 Title band, 136-137
384 Using FoxPro

TITLE option (DEFINE WINDOW command), 329 W-Z


Title/Summary (Report menu) option, 136-137
titles WAIT command, 227-229, 350—351
adding to reports, 28—29 While clauses, 110-113, 142
reports, 132, 135-137 Window menu, 17
TOPICS field, 325 Colors option, 335
totaling fields in reports, 137-141 windows, 10, 38
Trace window, 251-252, 307-310 applications screen commands, 331-332
Browse, 15, 19-21, 92-98
changing shape, 17-18
U-V Command, 40, 247-249, 274
undeleting data, 20 default data-entry, 80-81
defining applications, 328-331
Unlink Partitions (Browse menu)
option, 95 keyboard, 47—48
Layout, 25-29, 126-128
user-defined functions (UDF), 220-221
VALID clauses, 216-220 epetead sc aus
View window, 76 ae pee y
indexes 21-23 Page Preview, 26—27, 129-130
,
saving views, 170-171, 196 sizing, 48
work areas, 160-161, 189-191 Trace, 251-252, 307-310
views View, 21-23, 76, 170-171,
creating, 242-243 189-191, 196
defining, 76 zooming, 18, 48
opening, 243 work areas, 160-161, 189-191
saving, 76-77, 170-171, 196 capac ee
FoxBase + , 196-197 multiple, 190-191
ZOOM/NOZOOM option (DEFINE WINDOW
command), 330

- 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

Name Method of Payment:


Title Check (_] (Please enclose in envelope. )

Compuny Charge My: VISAL_] MasterCard []


City American Express [_]
State ZIP Charge#

Phone No ( ) Expiration Date

Order No. Title Price Total

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

2 BUSINESS REPLY MAIL


First Class Permit No. 9918 Indianapolis, IN

Postage will be paid by addressee

OU
11711 N. College
Carmel, IN 46032

NO POSTAGE
NECESSARY
IF MAILED
IN THE
UNITED STATES

BUSINESS REPLY MAIL


First Class Permit No. 9918 Indianapolis, IN

Postage will be paid by addressee

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

Quick Start tutorials get you up and_running quickly!

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

You might also like